Search is not available for this dataset
repo stringlengths 2 152 ⌀ | file stringlengths 15 239 | code stringlengths 0 58.4M | file_length int64 0 58.4M | avg_line_length float64 0 1.81M | max_line_length int64 0 12.7M | extension_type stringclasses 364 values |
|---|---|---|---|---|---|---|
Grid2Op | Grid2Op-master/grid2op/tests/notebooks_getting_started.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
try:
import shutil
import copy
import pdb
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor, CellExecutionError
from grid2op.tests.helper_path_test import *
import os
import unittest
import time
import warnings
CAN_COMPUTE = None
except ImportError as exc_:
CAN_COMPUTE = exc_
NOTEBOOK_PATHS = os.path.abspath(os.path.join(PATH_DATA_TEST, "../../getting_started"))
VERBOSE_TIMER = True
def delete_all(folder):
"""
Delete all the files in a folder recursively.
Parameters
----------
folder: ``str``
The folder in which we delete everything
Returns
-------
None
"""
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print("Failed to delete %s. Reason: %s" % (file_path, e))
def export_all_notebook(folder_in):
"""
Parameters
----------
folder_in: ``str``
The folder in which we look for ipynb files
folder_out: ``str``
The folder in which we save the py file.
Returns
-------
res: ``list``
Return the list of notebooks names
"""
res = []
for filename in os.listdir(folder_in):
if os.path.splitext(filename)[1] == ".ipynb":
notebook_filename = os.path.join(folder_in, filename)
res.append(notebook_filename)
return res
class RAII_tf_log:
def __init__(self):
self.previous = None
if "TF_CPP_MIN_LOG_LEVEL" in os.environ:
self.previous = copy.deepcopy(os.environ["TF_CPP_MIN_LOG_LEVEL"])
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
def __del__(self):
if self.previous is not None:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = self.previous
# notebook names are hard coded because if i change them, i need also to change the
# readme and the documentation
class RAII_Timer:
"""
class to have an approximation of the runtime of the notebook.
This is a rough approximation to reduce time spent in certain notebooks and should not be
used for another purpose.
"""
def __init__(self, str_=""):
self._time = time.perf_counter()
self.str_ = str_
def __del__(self):
if VERBOSE_TIMER:
print(
f"Execution time for {self.str_}: {time.perf_counter() - self._time:.3f} s"
)
class TestNotebook(unittest.TestCase):
def _aux_funct_notebook(self, notebook_filename):
assert os.path.exists(notebook_filename), f"{notebook_filename} do not exists!"
with open(notebook_filename) as f:
nb = nbformat.read(f, as_version=4)
try:
ep = ExecutePreprocessor(timeout=60, store_widget_state=True)
try:
ep.preprocess(nb, {"metadata": {"path": NOTEBOOK_PATHS}})
except CellExecutionError as exc_:
raise
except Exception as exc_:
# error with tqdm progress bar i believe
pass
except CellExecutionError as exc_:
raise
except Exception:
pass
def _check_for_baselines(self):
try:
import l2rpn_baselines
except ImportError as exc_:
self.skipTest("l2rpn baseline is not available")
def test_notebook0_1(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook0_1")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "00_SmallExample.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook1(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
return # takes 80s and is useless i think, as it tests only basics things
timer = RAII_Timer("test_notebook1")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "01_Grid2opFramework.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook2(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook2")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "02_Observation.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook3(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook3")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "03_Action.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook4(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
self._check_for_baselines()
raii_ = RAII_tf_log()
timer = RAII_Timer("test_notebook4")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "04_TrainingAnAgent.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook5(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook5")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "05_StudyYourAgent.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook6(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook6")
notebook_filename = os.path.join(
NOTEBOOK_PATHS, "06_Redispatching_Curtailment.ipynb"
)
self._aux_funct_notebook(notebook_filename)
def test_notebook7(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
self._check_for_baselines()
raii_ = RAII_tf_log()
timer = RAII_Timer("test_notebook7")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "07_MultiEnv.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook8(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
# display notebook, might not be super useful to test it in the unit test (saves another 1-2 minutes)
return
timer = RAII_Timer("test_notebook8")
notebook_filename = os.path.join(
NOTEBOOK_PATHS, "08_PlottingCapabilities.ipynb"
)
self._aux_funct_notebook(notebook_filename)
def test_notebook9(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
return # test the opponent and the maintenance, not much there but takes 80s so... not a lot to do
timer = RAII_Timer("test_notebook9")
notebook_filename = os.path.join(
NOTEBOOK_PATHS, "09_EnvironmentModifications.ipynb"
)
self._aux_funct_notebook(notebook_filename)
def test_notebook10(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
timer = RAII_Timer("test_notebook10")
notebook_filename = os.path.join(NOTEBOOK_PATHS, "10_StorageUnits.ipynb")
self._aux_funct_notebook(notebook_filename)
def test_notebook_aub(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
raii_ = RAII_tf_log()
timer = RAII_Timer("test_notebook_aub")
notebook_filename = os.path.join(
NOTEBOOK_PATHS,
"AUB_EECE699_20201103_ReinforcementLearningApplication.ipynb",
)
self._aux_funct_notebook(notebook_filename)
def test_notebook_ieeebda(self):
if CAN_COMPUTE is not None:
self.skipTest(f"{CAN_COMPUTE}")
# this test takes 3 mins alone, for a really small benefit, so i skip it for sake of time
return
self._check_for_baselines()
timer = RAII_Timer("test_notebook_ieeebda")
notebook_filename = os.path.join(
NOTEBOOK_PATHS, "IEEE BDA Tutorial Series.ipynb"
)
self._aux_funct_notebook(notebook_filename)
if __name__ == "__main__":
unittest.main()
| 8,691 | 32.821012 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Action.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import json
import re
import warnings
import unittest
import numpy as np
from abc import ABC, abstractmethod
import grid2op
from grid2op.tests.helper_path_test import *
from grid2op.dtypes import dt_int, dt_float, dt_bool
from grid2op.Exceptions import *
from grid2op.Action import *
from grid2op.Rules import RulesChecker, DefaultRules
from grid2op.Space import GridObjects
from grid2op.Space.space_utils import save_to_dict
# TODO check that if i set the element of a powerline to -1, then it's working as intended (disconnect both ends)
import pdb
def _get_action_grid_class():
GridObjects.env_name = "test_action_env"
GridObjects.n_gen = 5
GridObjects.name_gen = np.array(["gen_{}".format(i) for i in range(5)])
GridObjects.n_load = 11
GridObjects.name_load = np.array(["load_{}".format(i) for i in range(11)])
GridObjects.n_line = 20
GridObjects.name_line = np.array(["line_{}".format(i) for i in range(20)])
GridObjects.n_sub = 14
GridObjects.name_sub = np.array(["sub_{}".format(i) for i in range(14)])
GridObjects.sub_info = np.array(
[3, 7, 5, 6, 5, 6, 3, 2, 5, 3, 3, 3, 4, 3], dtype=dt_int
)
GridObjects.load_to_subid = np.array([1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13])
GridObjects.gen_to_subid = np.array([0, 1, 2, 5, 7])
GridObjects.line_or_to_subid = np.array(
[0, 0, 1, 1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 8, 8, 9, 11, 12]
)
GridObjects.line_ex_to_subid = np.array(
[1, 4, 2, 3, 4, 3, 4, 6, 8, 5, 10, 11, 12, 7, 8, 9, 13, 10, 12, 13]
)
GridObjects.load_to_sub_pos = np.array([4, 2, 5, 4, 4, 4, 1, 1, 1, 2, 1])
GridObjects.gen_to_sub_pos = np.array([2, 5, 3, 5, 1])
GridObjects.line_or_to_sub_pos = np.array(
[0, 1, 1, 2, 3, 1, 2, 3, 4, 3, 1, 2, 3, 1, 2, 2, 3, 0, 0, 1]
)
GridObjects.line_ex_to_sub_pos = np.array(
[0, 0, 0, 0, 1, 1, 2, 0, 0, 0, 2, 2, 3, 0, 1, 2, 2, 0, 0, 0]
)
GridObjects.load_pos_topo_vect = np.array(
[7, 12, 20, 25, 30, 41, 43, 46, 49, 53, 56]
)
GridObjects.gen_pos_topo_vect = np.array([2, 8, 13, 31, 36])
GridObjects.line_or_pos_topo_vect = np.array(
[0, 1, 4, 5, 6, 11, 17, 18, 19, 24, 27, 28, 29, 33, 34, 39, 40, 42, 48, 52]
)
GridObjects.line_ex_pos_topo_vect = np.array(
[3, 21, 10, 15, 22, 16, 23, 32, 37, 26, 47, 50, 54, 35, 38, 44, 57, 45, 51, 55]
)
GridObjects.redispatching_unit_commitment_availble = True
GridObjects.gen_type = np.array(["thermal"] * 5)
GridObjects.gen_pmin = np.array([0.0] * 5)
GridObjects.gen_pmax = np.array([100.0] * 5)
GridObjects.gen_min_uptime = np.array([0] * 5)
GridObjects.gen_min_downtime = np.array([0] * 5)
GridObjects.gen_cost_per_MW = np.array([70.0] * 5)
GridObjects.gen_startup_cost = np.array([0.0] * 5)
GridObjects.gen_shutdown_cost = np.array([0.0] * 5)
GridObjects.gen_redispatchable = np.array([True, False, False, True, False])
GridObjects.gen_max_ramp_up = np.array([10.0, 5.0, 15.0, 7.0, 8.0])
GridObjects.gen_max_ramp_down = np.array([11.0, 6.0, 16.0, 8.0, 9.0])
GridObjects.gen_renewable = ~GridObjects.gen_redispatchable
GridObjects.n_storage = 2
GridObjects.name_storage = np.array(["storage_0", "storage_1"])
GridObjects.storage_to_subid = np.array([1, 2])
GridObjects.storage_to_sub_pos = np.array([6, 4])
GridObjects.storage_pos_topo_vect = np.array([9, 14])
GridObjects.storage_type = np.array(["battery"] * 2)
GridObjects.storage_Emax = np.array([100.0, 100.0])
GridObjects.storage_Emin = np.array([0.0, 0.0])
GridObjects.storage_max_p_prod = np.array([10.0, 10.0])
GridObjects.storage_max_p_absorb = np.array([15.0, 15.0])
GridObjects.storage_marginal_cost = np.array([0.0, 0.0])
GridObjects.storage_loss = np.array([0.0, 0.0])
GridObjects.storage_discharging_efficiency = np.array([1.0, 1.0])
GridObjects.storage_charging_efficiency = np.array([1.0, 1.0])
GridObjects._topo_vect_to_sub = np.repeat(
np.arange(GridObjects.n_sub), repeats=GridObjects.sub_info
)
GridObjects.glop_version = grid2op.__version__
GridObjects._PATH_ENV = None
json_ = {
"glop_version": grid2op.__version__,
"name_gen": ["gen_0", "gen_1", "gen_2", "gen_3", "gen_4"],
"name_load": [
"load_0",
"load_1",
"load_2",
"load_3",
"load_4",
"load_5",
"load_6",
"load_7",
"load_8",
"load_9",
"load_10",
],
"name_line": [
"line_0",
"line_1",
"line_2",
"line_3",
"line_4",
"line_5",
"line_6",
"line_7",
"line_8",
"line_9",
"line_10",
"line_11",
"line_12",
"line_13",
"line_14",
"line_15",
"line_16",
"line_17",
"line_18",
"line_19",
],
"name_sub": [
"sub_0",
"sub_1",
"sub_2",
"sub_3",
"sub_4",
"sub_5",
"sub_6",
"sub_7",
"sub_8",
"sub_9",
"sub_10",
"sub_11",
"sub_12",
"sub_13",
],
"name_storage": ["storage_0", "storage_1"],
"env_name": "test_action_env",
"sub_info": [3, 7, 5, 6, 5, 6, 3, 2, 5, 3, 3, 3, 4, 3],
"load_to_subid": [1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13],
"gen_to_subid": [0, 1, 2, 5, 7],
"line_or_to_subid": [
0,
0,
1,
1,
1,
2,
3,
3,
3,
4,
5,
5,
5,
6,
6,
8,
8,
9,
11,
12,
],
"line_ex_to_subid": [
1,
4,
2,
3,
4,
3,
4,
6,
8,
5,
10,
11,
12,
7,
8,
9,
13,
10,
12,
13,
],
"storage_to_subid": [1, 2],
"load_to_sub_pos": [4, 2, 5, 4, 4, 4, 1, 1, 1, 2, 1],
"gen_to_sub_pos": [2, 5, 3, 5, 1],
"line_or_to_sub_pos": [
0,
1,
1,
2,
3,
1,
2,
3,
4,
3,
1,
2,
3,
1,
2,
2,
3,
0,
0,
1,
],
"line_ex_to_sub_pos": [
0,
0,
0,
0,
1,
1,
2,
0,
0,
0,
2,
2,
3,
0,
1,
2,
2,
0,
0,
0,
],
"storage_to_sub_pos": [6, 4],
"load_pos_topo_vect": [7, 12, 20, 25, 30, 41, 43, 46, 49, 53, 56],
"gen_pos_topo_vect": [2, 8, 13, 31, 36],
"line_or_pos_topo_vect": [
0,
1,
4,
5,
6,
11,
17,
18,
19,
24,
27,
28,
29,
33,
34,
39,
40,
42,
48,
52,
],
"line_ex_pos_topo_vect": [
3,
21,
10,
15,
22,
16,
23,
32,
37,
26,
47,
50,
54,
35,
38,
44,
57,
45,
51,
55,
],
"storage_pos_topo_vect": [9, 14],
"gen_type": ["thermal"] * 5,
"gen_pmin": [0.0] * 5,
"gen_pmax": [100.0] * 5,
"gen_redispatchable": [True, False, False, True, False],
"gen_renewable": [False, True, True, False, True],
"gen_max_ramp_up": [10.0, 5.0, 15.0, 7.0, 8.0],
"gen_max_ramp_down": [11.0, 6.0, 16.0, 8.0, 9.0],
"gen_min_uptime": [0] * 5,
"gen_min_downtime": [0] * 5,
"gen_cost_per_MW": [70.0] * 5,
"gen_startup_cost": [0.0] * 5,
"gen_shutdown_cost": [0.0] * 5,
"storage_type": ["battery"] * 2,
"storage_Emax": [100.0, 100.0],
"storage_Emin": [0.0, 0.0],
"storage_max_p_prod": [10.0, 10.0],
"storage_max_p_absorb": [15.0, 15.0],
"storage_marginal_cost": [0.0, 0.0],
"storage_loss": [0.0, 0.0],
"storage_charging_efficiency": [1.0, 1.0],
"storage_discharging_efficiency": [1.0, 1.0],
"grid_layout": None,
"shunt_to_subid": None,
"name_shunt": None,
"dim_alarms": 0,
"alarms_area_names": [],
"alarms_lines_area": {},
"alarms_area_lines": [],
"dim_alerts": 0,
"alertable_line_names": [],
"alertable_line_ids": [],
"_PATH_ENV": None,
"assistant_warning_type": None
}
GridObjects.shunts_data_available = False
my_cls = GridObjects.init_grid(GridObjects, force=True)
return my_cls, json_
class TestActionBase(ABC):
@abstractmethod
def _action_setup(self):
pass
def _skipMissingKey(self, key):
if key not in self.authorized_keys:
unittest.TestCase.skipTest(self, f"Skipped: Missing authorized_key {key}")
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
self.ActionSpaceClass = ActionSpace.init_grid(GridObjects_cls)
act_cls = self._action_setup()
self.helper_action = self.ActionSpaceClass(
GridObjects_cls,
legal_action=self.game_rules.legal_action,
actionClass=act_cls,
)
self.helper_action.seed(42)
# save_to_dict(self.res, self.helper_action, "subtype", lambda x: re.sub("(<class ')|('>)", "", "{}".format(x)))
save_to_dict(
self.res,
self.helper_action,
"_init_subtype",
lambda x: re.sub(
"(<class ')|(\\.init_grid\\.<locals>\\.res)|('>)", "", "{}".format(x)
),
)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def tearDown(self):
self.authorized_keys = {}
self.gridobj._clear_class_attribute()
def test_reset_modified_flags(self):
act = self.helper_action.sample()
act._reset_modified_flags()
assert not act._modif_inj
assert not act._modif_set_bus
assert not act._modif_change_bus
assert not act._modif_set_status
assert not act._modif_change_status
assert not act._modif_redispatch
assert not act._modif_storage
assert not act._modif_curtailment
def test_get_array_from_attr_name(self):
act = self.helper_action.sample()
with self.assertRaises(Grid2OpException):
act._get_array_from_attr_name("toto")
def test_assign_attr_from_name(self):
key = "set_line_status"
if key in self.authorized_keys:
unittest.TestCase.skipTest(
self, f'Skipped: key "{key}" is present, this test supposes it\'s not'
)
act = self.helper_action.sample()
with self.assertRaises(AmbiguousAction):
act._assign_attr_from_name(
"_set_line_status", np.zeros(self.helper_action.n_line)
)
def test_eq_none(self):
act = self.helper_action.sample()
assert not (act == None)
def test_eq_diff_grid(self):
act = self.helper_action.sample()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_ref = grid2op.make("rte_case5_example", test=True)
act_ref = env_ref.action_space()
assert not (act == act_ref)
def test_from_vect_nan(self):
"""test of the issue https://github.com/rte-france/Grid2Op/issues/173"""
vect = np.full(self.helper_action.n, fill_value=np.NaN, dtype=float)
if self.helper_action.n > 0:
with self.assertRaises(NonFiniteElement):
act = self.helper_action.from_vect(vect)
else:
act = self.helper_action.from_vect(vect)
dn_act = self.helper_action()
assert act == dn_act
def compare_vect(self, pred, true):
return np.max(np.abs(pred - true)) <= self.tolvect
def test_call(self):
action = self.helper_action()
(
dict_injection,
set_status,
switch_status,
set_topo_vect,
switcth_topo_vect,
redispatching,
storage,
shunts,
) = action()
def test_compare(self):
action = self.helper_action()
action2 = self.helper_action()
assert action == action2
def test_instanciate_action(self):
"""
test i can instanciate an action without crashing
:return:
"""
action = self.helper_action()
def test_size(self):
action = self.helper_action()
action.size()
def test_proper_size(self):
action = self.helper_action()
assert action.size() == self.size_act
def test_size_action_space(self):
assert self.helper_action.size() == self.size_act
def test_print_notcrash(self):
"""
test the conversion to str does not crash
:return:
"""
action = self.helper_action({})
a = "{}".format(action)
def test_change_p(self):
"""
:return:
"""
self._skipMissingKey("injection")
new_vect = np.random.randn(self.helper_action.n_load).astype(dt_float)
action = self.helper_action({"injection": {"load_p": new_vect}})
self.compare_vect(action._dict_inj["load_p"], new_vect)
for i in range(self.helper_action.n_load):
assert action.effect_on(load_id=i)["new_p"] == new_vect[i]
def test_change_v(self):
"""
:return:
"""
self._skipMissingKey("injection")
new_vect = np.random.randn(self.helper_action.n_gen).astype(dt_float)
action = self.helper_action({"injection": {"prod_v": new_vect}})
self.compare_vect(action._dict_inj["prod_v"], new_vect)
for i in range(self.helper_action.n_gen):
assert action.effect_on(gen_id=i)["new_v"] == new_vect[i]
def test_change_p_q(self):
"""
:return:
"""
self._skipMissingKey("injection")
new_vect = np.random.randn(self.helper_action.n_load).astype(dt_float)
new_vect2 = np.random.randn(self.helper_action.n_load).astype(dt_float)
action = self.helper_action(
{"injection": {"load_p": new_vect, "load_q": new_vect2}}
)
assert self.compare_vect(action._dict_inj["load_p"], new_vect)
assert self.compare_vect(action._dict_inj["load_q"], new_vect2)
for i in range(self.helper_action.n_load):
assert action.effect_on(load_id=i)["new_p"] == new_vect[i]
assert action.effect_on(load_id=i)["new_q"] == new_vect2[i]
def test_update_disconnection_1(self):
"""
Test if the disconnection is working properly
:return:
"""
self._skipMissingKey("set_line_status")
for i in range(self.helper_action.n_line):
disco = np.full(shape=self.helper_action.n_line, fill_value=0, dtype=dt_int)
disco[i] = 1
action = self.helper_action({"set_line_status": disco})
for j in range(self.helper_action.n_line):
assert (
action.effect_on(line_id=j)["set_line_status"] == disco[j]
), "problem with line {} if line {} is disconnected".format(j, i)
assert action.effect_on(line_id=j)["change_line_status"] == False
def test_update_disconnection_m1(self):
"""
Test if the disconnection is working properly
:return:
"""
self._skipMissingKey("set_line_status")
for i in range(self.helper_action.n_line):
disco = np.full(shape=self.helper_action.n_line, fill_value=0, dtype=dt_int)
disco[i] = -1
action = self.helper_action({"set_line_status": disco})
for j in range(self.helper_action.n_line):
assert (
action.effect_on(line_id=j)["set_line_status"] == disco[j]
), "problem with line {} if line {} is disconnected".format(j, i)
assert action.effect_on(line_id=j)["change_line_status"] == False
def test_update_hazard(self):
"""
Same test as above, but with hazard
:return:
"""
self._skipMissingKey("hazards")
for i in range(self.helper_action.n_line):
disco = np.full(
shape=self.helper_action.n_line, fill_value=False, dtype=dt_bool
)
disco[i] = True
action = self.helper_action({"hazards": disco})
for j in range(self.helper_action.n_line):
expected_res = -1 if j == i else 0
assert (
action.effect_on(line_id=j)["set_line_status"] == expected_res
), "problem with line {} if line {} is disconnected".format(j, i)
assert action.effect_on(line_id=j)["change_line_status"] == False
def test_update_status(self):
self._skipMissingKey("change_line_status")
for i in range(self.helper_action.n_line):
disco = np.full(
shape=self.helper_action.n_line, fill_value=False, dtype=dt_bool
)
disco[i] = True
action = self.helper_action({"change_line_status": disco})
for j in range(self.helper_action.n_line):
expected_res = j == i
assert action.effect_on(line_id=j)["set_line_status"] == 0
assert action.effect_on(line_id=j)["change_line_status"] == expected_res
def test_update_set_topo_by_dict_obj(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
action = self.helper_action({"set_bus": {"loads_id": [(1, 2)]}})
assert action.effect_on(load_id=1)["set_bus"] == 2
assert action.effect_on(load_id=1)["change_bus"] == False
assert action.effect_on(load_id=0)["set_bus"] == 0
assert action.effect_on(load_id=0)["change_bus"] == False
def test_update_set_topo_by_dict_sub(self):
self._skipMissingKey("set_bus")
arr = np.array([1, 1, 1, 2, 2, 2, 2], dtype=dt_int)
action = self.helper_action({"set_bus": {"substations_id": [(1, arr)]}})
assert action.effect_on(line_id=2)["set_bus_or"] == 1
assert action.effect_on(line_id=3)["set_bus_or"] == 1
assert action.effect_on(line_id=4)["set_bus_or"] == 2
assert action.effect_on(line_id=0)["set_bus_ex"] == 1
assert action.effect_on(load_id=0)["set_bus"] == 2
assert action.effect_on(gen_id=1)["set_bus"] == 2
assert action.effect_on(storage_id=0)["set_bus"] == 2
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(gen_id=0)["set_bus"] == 0
def test_update_set_topo_by_dict_sub2(self):
self._skipMissingKey("set_bus")
arr = np.array([1, 1, 1, 2, 2, 2, 2], dtype=dt_int)
arr3 = np.array([1, 2, 1, 2, 1, 2], dtype=dt_int)
action = self.helper_action(
{"set_bus": {"substations_id": [(3, arr3), (1, arr)]}}
)
assert action.effect_on(line_id=2)["set_bus_or"] == 1
assert action.effect_on(line_id=3)["set_bus_or"] == 1
assert action.effect_on(line_id=4)["set_bus_or"] == 2
assert action.effect_on(line_id=0)["set_bus_ex"] == 1
assert action.effect_on(load_id=0)["set_bus"] == 2
assert action.effect_on(gen_id=1)["set_bus"] == 2
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(gen_id=0)["set_bus"] == 0
def test_update_undo_change_bus(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("set_bus")
# Create dummy change_bus action
action = self.helper_action({"change_bus": {"loads_id": [1]}})
# Check it is valid
assert action.effect_on(load_id=0)["set_bus"] == 0
assert action.effect_on(load_id=0)["change_bus"] == False
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(load_id=1)["change_bus"] == True
# Save a copy
action_copy = copy.deepcopy(action)
# Update it
action.update({"change_bus": {"loads_id": [1]}})
# Check it's updated
assert action.effect_on(load_id=0)["set_bus"] == 0
assert action.effect_on(load_id=0)["change_bus"] == False
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(load_id=1)["change_bus"] == False
# Update back to original
action.update({"change_bus": {"loads_id": [1]}})
# Check it's updated
assert action.effect_on(load_id=0)["set_bus"] == 0
assert action.effect_on(load_id=0)["change_bus"] == False
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(load_id=1)["change_bus"] == True
# Check it's equal to original
assert action == action_copy
def test_update_change_bus_by_dict_obj(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("set_bus")
action = self.helper_action({"change_bus": {"loads_id": [1]}})
assert action.effect_on(load_id=1)["set_bus"] == 0
assert action.effect_on(load_id=1)["change_bus"] == True
assert action.effect_on(load_id=0)["set_bus"] == 0
assert action.effect_on(load_id=0)["change_bus"] == False
def test_update_change_bus_by_dict_sub(self):
self._skipMissingKey("change_bus")
arr = np.array([True, True, True, False, False, False, False], dtype=dt_bool)
action = self.helper_action({"change_bus": {"substations_id": [(1, arr)]}})
assert action.effect_on(line_id=2)["change_bus_or"] == True
assert action.effect_on(line_id=3)["change_bus_or"] == True
assert action.effect_on(line_id=4)["change_bus_or"] == False
assert action.effect_on(line_id=0)["change_bus_ex"] == True
assert action.effect_on(load_id=0)["change_bus"] == False
assert action.effect_on(gen_id=1)["change_bus"] == False
assert action.effect_on(storage_id=0)["change_bus"] == False
assert action.effect_on(load_id=1)["change_bus"] == False
assert action.effect_on(gen_id=0)["change_bus"] == False
def test_update_change_bus_by_dict_sub2(self):
self._skipMissingKey("change_bus")
arr = np.array([True, True, True, False, False, False, False], dtype=dt_bool)
arr3 = np.array([True, False, True, False, True, False], dtype=dt_bool)
action = self.helper_action(
{"change_bus": {"substations_id": [(3, arr3), (1, arr)]}}
)
assert action.effect_on(line_id=2)["change_bus_or"] == True
assert action.effect_on(line_id=3)["change_bus_or"] == True
assert action.effect_on(line_id=4)["change_bus_or"] == False
assert action.effect_on(line_id=0)["change_bus_ex"] == True
assert action.effect_on(load_id=0)["change_bus"] == False
assert action.effect_on(gen_id=1)["change_bus"] == False
assert action.effect_on(load_id=1)["change_bus"] == False
assert action.effect_on(gen_id=0)["change_bus"] == False
def test_ambiguity_topo(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
# i switch the bus of the origin of powerline 1
action = self.helper_action({"change_bus": {"lines_or_id": [1]}})
action.update(
{"set_bus": {"lines_or_id": [(1, 1)]}}
) # i set the origin of powerline 1 to bus 1
try:
action()
raise RuntimeError("This should hav thrown an InvalidBusStatus error")
except InvalidBusStatus as e:
pass
def test_ambiguity_line_status_when_set_and_change(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("change_line_status")
arr = np.zeros(self.helper_action.n_line, dtype=dt_int)
arr[1] = -1
# i switch set the status of powerline 1 to "disconnected"
action = self.helper_action({"set_line_status": arr})
action.update({"change_line_status": [1]}) # i asked to change this status
try:
action()
raise RuntimeError("This should hav thrown an InvalidBusStatus error")
except InvalidLineStatus as e:
pass
def test_ambiguity_line_reconnected_without_bus(self):
self.skipTest("deprecated with backend action")
self._skipMissingKey("set_line_status")
arr = np.zeros(self.helper_action.n_line)
arr[1] = 1
action = self.helper_action(
{"set_line_status": arr}
) # i switch set the status of powerline 1 to "connected"
# and i don't say on which bus to connect it
try:
action()
raise RuntimeError(
"This should have thrown an InvalidBusStatus error for {}"
"".format(self.helper_action.actionClass)
)
except InvalidLineStatus as e:
pass
def test_set_status_and_setbus_isambiguous(self):
"""
:return:
"""
self._skipMissingKey("set_bus")
self._skipMissingKey("set_line_status")
arr = np.array([1, 1, 1, 2, 2, 2, 0], dtype=dt_int)
id_ = 2
action = self.helper_action({"set_bus": {"substations_id": [(1, arr)]}})
arr2 = np.zeros(self.helper_action.n_line, dtype=dt_int)
arr2[id_] = -1
action.update({"set_line_status": arr2})
try:
action()
raise RuntimeError("This should have thrown an InvalidBusStatus error")
except InvalidLineStatus as e:
pass
def test_hazard_overides_setbus(self):
"""
:return:
"""
self._skipMissingKey("set_bus")
self._skipMissingKey("hazards")
arr = np.array([1, 1, 1, 2, 2, 2, 2], dtype=dt_int)
id_ = 2
action = self.helper_action({"set_bus": {"substations_id": [(1, arr)]}})
assert action.effect_on(line_id=id_)["set_bus_or"] == 1, "fail for {}".format(
self.helper_action.actionClass
)
action.update({"hazards": [id_]})
assert action.effect_on(line_id=id_)["set_bus_or"] == 0, "fail for {}".format(
self.helper_action.actionClass
)
assert (
action.effect_on(line_id=id_)["set_line_status"] == -1
), "fail for {}".format(self.helper_action.actionClass)
assert action.effect_on(line_id=id_)["set_bus_ex"] == 0, "fail for {}".format(
self.helper_action.actionClass
)
def test_action_str(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
arr1 = np.array([False, False, False, True, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_1 = 1
id_2 = 12
action = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
res = action.__str__()
act_str = (
"This action will:\n\t - NOT change anything to the injections"
"\n\t - NOT perform any redispatching action\n"
"\t - NOT modify any storage capacity\n"
"\t - NOT perform any curtailment"
"\n\t - NOT force any line status\n"
"\t - NOT switch any line status"
"\n\t - Change the bus of the following element(s):"
"\n\t \t - Switch bus of line (origin) id 4 [on substation 1]"
"\n\t \t - Switch bus of load id 0 [on substation 1]"
"\n\t \t - Switch bus of generator id 1 [on substation 1]"
"\n\t \t - Switch bus of storage id 0 [on substation 1]"
"\n\t - Set the bus of the following element(s):"
"\n\t \t - Assign bus 1 to line (extremity) id 18 [on substation 12]"
"\n\t \t - Assign bus 1 to line (origin) id 19 [on substation 12]"
"\n\t \t - Assign bus 2 to load id 9 [on substation 12]"
"\n\t \t - Assign bus 2 to line (extremity) id 12 [on substation 12]"
)
assert res == act_str
def test_to_vect(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
arr1 = np.array([False, False, False, True, True, True, False], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_1 = 1
id_2 = 12
action = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
res = action.to_vect()
tmp = np.zeros(self.size_act)
if "curtail" in action.authorized_keys:
# for curtailment, at the end, and by default its -1
tmp[-action.n_gen :] = -1
# compute the "set_bus" vect
id_set = np.where(np.array(action.attr_list_vect) == "_set_topo_vect")[0][0]
size_before = 0
for el in action.attr_list_vect[:id_set]:
arr_ = action._get_array_from_attr_name(el)
size_before += arr_.shape[0]
tmp[size_before : (size_before + action.dim_topo)] = np.array(
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
2,
2,
0,
0,
0,
]
)
id_change = np.where(np.array(action.attr_list_vect) == "_change_bus_vect")[0][
0
]
size_before = 0
for el in action.attr_list_vect[:id_change]:
arr_ = action._get_array_from_attr_name(el)
size_before += arr_.shape[0]
tmp[size_before : (size_before + action.dim_topo)] = 1.0 * np.array(
[
False,
False,
False,
False,
False,
False,
True,
True,
True,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
]
)
assert np.all(res[np.isfinite(tmp)] == tmp[np.isfinite(tmp)])
assert np.all(np.isfinite(res) == np.isfinite(tmp))
def test__eq__(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
arr1 = np.array([False, False, False, True, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_1 = 1
id_2 = 12
action1 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
action2 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
action3 = self.helper_action()
test = type(action1).assert_grid_correct_cls()
assert action1 == action2
assert action1 != action3
def test_from_vect_dn(self):
action1 = self.helper_action({})
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_change_bus(self):
arr1 = np.array([False, False, False, True, True, True, False], dtype=dt_bool)
id_1 = 1
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action(
{"change_bus": {"substations_id": [(id_1, arr1)]}}
)
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_set_bus(self):
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_2 = 12
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}}
)
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_set_line_status(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action({"set_line_status": [(1, -1)]})
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_change_line_status(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action({"change_line_status": [2]})
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_redisp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action({"redispatch": [(0, -7.42)]})
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect_storage(self):
"""test from vect also work with storage action"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
action1 = self.helper_action({"set_storage": [(0, -7.42)]})
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_from_vect(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
arr1 = np.array([False, False, False, True, True, True, False], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_1 = 1
id_2 = 12
action1 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
action2 = self.helper_action({})
vect_act1 = action1.to_vect()
action2.from_vect(vect_act1)
# if i load an action with from_vect it's equal to the original one
assert action1 == action2
vect_act2 = action2.to_vect()
# if i convert it back to a vector, it's equal to the original converted vector
assert np.all(
vect_act1[np.isfinite(vect_act2)] == vect_act2[np.isfinite(vect_act2)]
)
assert np.all(np.isfinite(vect_act1) == np.isfinite(vect_act2))
def test_call_change_set(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
self._skipMissingKey("set_line_status")
self._skipMissingKey("change_line_status")
self._skipMissingKey("injection")
arr1 = np.array([False, False, False, True, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
id_1 = 1
id_2 = 12
new_vect = np.random.randn(self.helper_action.n_load).astype(dt_int)
new_vect2 = np.random.randn(self.helper_action.n_load).astype(dt_int)
change_status_orig = np.random.randint(0, 2, self.helper_action.n_line).astype(
dt_bool
)
set_status_orig = np.random.randint(-1, 2, self.helper_action.n_line)
set_status_orig[change_status_orig] = 0
change_topo_vect_orig = np.random.randint(
0, 2, self.helper_action.dim_topo
).astype(dt_bool)
# powerline that are set to be reconnected, can't be moved to another bus
change_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == 1]
] = False
change_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == 1]
] = False
# powerline that are disconnected, can't be moved to the other bus
change_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == -1]
] = False
change_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == -1]
] = False
set_topo_vect_orig = np.random.randint(0, 3, self.helper_action.dim_topo)
set_topo_vect_orig[change_topo_vect_orig] = 0 # don't both change and set
# I need to make sure powerlines that are reconnected are indeed reconnected to a bus
set_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == 1]
] = 1
set_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == 1]
] = 1
# I need to make sure powerlines that are disconnected are not assigned to a bus
set_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == -1]
] = 0
set_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == -1]
] = 0
action = self.helper_action(
{
"change_bus": change_topo_vect_orig,
"set_bus": set_topo_vect_orig,
"injection": {"load_p": new_vect, "load_q": new_vect2},
"change_line_status": change_status_orig,
"set_line_status": set_status_orig,
}
)
(
dict_injection,
set_status,
change_status,
set_topo_vect,
switcth_topo_vect,
redispatching,
storage,
shunts,
) = action()
assert "load_p" in dict_injection
assert np.all(dict_injection["load_p"] == new_vect)
assert "load_q" in dict_injection
assert np.all(dict_injection["load_q"] == new_vect2)
assert np.all(set_status == set_status_orig)
assert np.all(change_status == change_status_orig)
assert np.all(set_topo_vect == set_topo_vect_orig)
assert np.all(switcth_topo_vect == change_topo_vect_orig)
def test_get_topological_impact(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
self._skipMissingKey("set_line_status")
self._skipMissingKey("change_line_status")
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = 1
do_nothing = self.helper_action({})
aff_lines, aff_subs = do_nothing.get_topological_impact()
assert np.sum(aff_lines) == 0
assert np.sum(aff_subs) == 0
act_sub1 = self.helper_action(
{"change_bus": {"substations_id": [(id_1, arr1)]}}
)
aff_lines, aff_subs = act_sub1.get_topological_impact()
assert np.sum(aff_lines) == 0
assert np.sum(aff_subs) == 1
assert aff_subs[id_1]
act_sub1_sub12 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
}
)
aff_lines, aff_subs = act_sub1_sub12.get_topological_impact()
assert np.sum(aff_lines) == 0
assert np.sum(aff_subs) == 2
assert aff_subs[id_1]
assert aff_subs[id_2]
act_sub1_sub12_line1 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
}
)
aff_lines, aff_subs = act_sub1_sub12_line1.get_topological_impact()
assert np.sum(aff_lines) == 1
assert aff_lines[id_line] == 1
assert np.sum(aff_subs) == 2
assert aff_subs[id_1]
assert aff_subs[id_2]
act_sub1_sub12_line1_line2 = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
}
)
aff_lines, aff_subs = act_sub1_sub12_line1_line2.get_topological_impact()
assert np.sum(aff_lines) == 2
assert aff_lines[id_line] == 1
assert aff_lines[id_line2] == 1
assert np.sum(aff_subs) == 2
assert aff_subs[id_1]
assert aff_subs[id_2]
def test_to_dict(self):
dict_ = self.helper_action.cls_to_dict()
for el in dict_:
assert el in self.res, f"missing key {el} in self.res"
for el in self.res:
assert el in dict_, f"missing key {el} in dict_"
for el in self.res:
val = dict_[el]
val_res = self.res[el]
if val is None and val_res is not None:
raise AssertionError(f"val is None and val_res is not None: val_res: {val_res}")
if val is not None and val_res is None:
raise AssertionError(f"val is not None and val_res is None: val {val}")
if val is None and val_res is None:
continue
ok_ = np.array_equal(val, val_res)
assert ok_, (f"values different for {el}: "
f"{dict_[el]}"
f"{self.res[el]}")
def test_from_dict(self):
res = ActionSpace.from_dict(self.res)
assert np.all(res.name_gen == self.helper_action.name_gen)
assert np.all(res.name_load == self.helper_action.name_load)
assert np.all(res.name_line == self.helper_action.name_line)
assert np.all(res.sub_info == self.helper_action.sub_info)
assert np.all(res.load_to_subid == self.helper_action.load_to_subid)
assert np.all(res.gen_to_subid == self.helper_action.gen_to_subid)
assert np.all(res.line_or_to_subid == self.helper_action.line_or_to_subid)
assert np.all(res.line_ex_to_subid == self.helper_action.line_ex_to_subid)
assert np.all(res.load_to_sub_pos == self.helper_action.load_to_sub_pos)
assert np.all(res.gen_to_sub_pos == self.helper_action.gen_to_sub_pos)
assert np.all(res.line_or_to_sub_pos == self.helper_action.line_or_to_sub_pos)
assert np.all(res.line_ex_to_sub_pos == self.helper_action.line_ex_to_sub_pos)
assert np.all(res.load_pos_topo_vect == self.helper_action.load_pos_topo_vect)
assert np.all(res.gen_pos_topo_vect == self.helper_action.gen_pos_topo_vect)
assert np.all(
res.line_or_pos_topo_vect == self.helper_action.line_or_pos_topo_vect
)
assert np.all(
res.line_ex_pos_topo_vect == self.helper_action.line_ex_pos_topo_vect
)
# pdb.set_trace()
assert issubclass(res.actionClass, self.helper_action._init_subtype)
def test_json_serializable(self):
dict_ = self.helper_action.cls_to_dict()
res = json.dumps(obj=dict_, indent=4, sort_keys=True)
def test_json_loadable(self):
dict_ = self.helper_action.cls_to_dict()
tmp = json.dumps(obj=dict_, indent=4, sort_keys=True)
res = ActionSpace.from_dict(json.loads(tmp))
assert np.all(res.name_gen == self.helper_action.name_gen)
assert np.all(res.name_load == self.helper_action.name_load)
assert np.all(res.name_line == self.helper_action.name_line)
assert np.all(res.sub_info == self.helper_action.sub_info)
assert np.all(res.load_to_subid == self.helper_action.load_to_subid)
assert np.all(res.gen_to_subid == self.helper_action.gen_to_subid)
assert np.all(res.line_or_to_subid == self.helper_action.line_or_to_subid)
assert np.all(res.line_ex_to_subid == self.helper_action.line_ex_to_subid)
assert np.all(res.load_to_sub_pos == self.helper_action.load_to_sub_pos)
assert np.all(res.gen_to_sub_pos == self.helper_action.gen_to_sub_pos)
assert np.all(res.line_or_to_sub_pos == self.helper_action.line_or_to_sub_pos)
assert np.all(res.line_ex_to_sub_pos == self.helper_action.line_ex_to_sub_pos)
assert np.all(res.load_pos_topo_vect == self.helper_action.load_pos_topo_vect)
assert np.all(res.gen_pos_topo_vect == self.helper_action.gen_pos_topo_vect)
assert np.all(
res.line_or_pos_topo_vect == self.helper_action.line_or_pos_topo_vect
)
assert np.all(
res.line_ex_pos_topo_vect == self.helper_action.line_ex_pos_topo_vect
)
assert issubclass(res.actionClass, self.helper_action._init_subtype)
def test_as_dict(self):
act = self.helper_action({})
dict_ = act.as_dict()
assert dict_ == {}
def test_to_from_vect_action(self):
act = self.helper_action({})
vect_ = act.to_vect()
act2 = self.helper_action.from_vect(vect_)
assert act == act2
def test_sum_shape_equal_size(self):
act = self.helper_action({})
assert act.size() == np.sum(act.shape())
def test_shape_correct(self):
act = self.helper_action({})
assert act.shape().shape == act.dtype().shape
def test_redispatching(self):
self._skipMissingKey("redispatch")
act = self.helper_action({"redispatch": (1, 10)})
act = self.helper_action({"redispatch": [(1, 10), (2, 100)]})
act = self.helper_action(
{"redispatch": np.array([10.0, 20.0, 30.0, 40.0, 50.0])}
)
def test_possibility_reconnect_powerlines(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_bus")
self.helper_action.legal_action = DefaultRules()
act = self.helper_action.reconnect_powerline(line_id=1, bus_or=1, bus_ex=1)
line_impact, sub_impact = act.get_topological_impact()
assert np.sum(line_impact) == 1
assert np.sum(sub_impact) == 0
act = self.helper_action.reconnect_powerline(line_id=1, bus_or=1, bus_ex=1)
act.update({"set_bus": {"generators_id": [(1, 2)]}})
line_impact, sub_impact = act.get_topological_impact()
assert np.sum(line_impact) == 1
assert np.all(sub_impact == [False, True] + [False for _ in range(12)])
act = self.helper_action.reconnect_powerline(line_id=1, bus_or=1, bus_ex=1)
act.update({"set_bus": {"generators_id": [(0, 2)]}})
line_impact, sub_impact = act.get_topological_impact()
assert np.sum(line_impact) == 1
assert np.all(sub_impact == [True] + [False for _ in range(13)])
# there were a bug that occurred when updating an action, some vectors were not reset
act = self.helper_action.reconnect_powerline(line_id=1, bus_or=1, bus_ex=1)
line_impact, sub_impact = act.get_topological_impact()
assert np.sum(line_impact) == 1
assert np.sum(sub_impact) == 0
act.update({"set_bus": {"generators_id": [(1, 2)]}})
line_impact, sub_impact = act.get_topological_impact()
assert np.sum(line_impact) == 1
assert np.all(sub_impact == [False, True] + [False for _ in range(12)])
def test_extract_from_vect(self):
self._skipMissingKey("set_line_status")
act = self.helper_action()
vect = act.to_vect()
res = self.helper_action.extract_from_vect(vect, "_set_line_status")
assert np.all(res == act._set_line_status)
def test_sample(self):
try:
for i in range(30):
act = self.helper_action.sample()
except Exception as exc_:
assert False, f"sample() raised error {exc_}"
class TestAction(TestActionBase, unittest.TestCase):
"""
Test suite using the BaseAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=BaseAction)
return BaseAction
class TestTopologyAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologyAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologyAction)
return TopologyAction
class TestDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the DispatchAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=DispatchAction)
return DispatchAction
class TestTopologyAndDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologyAndDispatchAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologyAndDispatchAction)
return TopologyAndDispatchAction
class TestTopologySetAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologySetAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologySetAction)
return TopologySetAction
class TestTopologySetAndDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologySetAndDispatchAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologySetAndDispatchAction)
return TopologySetAndDispatchAction
class TestTopologyChangeAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologySetAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologyChangeAction)
return TopologyChangeAction
class TestTopologyChangeAndDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the TopologyChangeAndDispatchAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=TopologyChangeAndDispatchAction)
return TopologyChangeAndDispatchAction
class TestPowerlineSetAction(TestActionBase, unittest.TestCase):
"""
Test suite using the PowerlineSetAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=PowerlineSetAction)
return PowerlineSetAction
class TestPowerlineChangeAction(TestActionBase, unittest.TestCase):
"""
Test suite using the PowerlineChangeAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=PowerlineChangeAction)
return PowerlineChangeAction
class TestPowerlineSetAndDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the PowerlineSetAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=PowerlineSetAndDispatchAction)
return PowerlineSetAndDispatchAction
class TestPowerlineChangeAndDispatchAction(TestActionBase, unittest.TestCase):
"""
Test suite using the PowerlineChangeAction class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=PowerlineChangeAndDispatchAction)
return PowerlineChangeAndDispatchAction
class TestDontAct(TestActionBase, unittest.TestCase):
"""
Test suite using the DontAct class
"""
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=DontAct)
return DontAct
class TestIADD:
"""Test that act += act2 equals what we want and don't use data it is not allowed to"""
def _skipMissingKey(self, key, act):
if key not in act.attr_list_set:
unittest.TestCase.skipTest(self, "Skipped: Missing authorized_key {key}")
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
self.n_line = 20
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
self.ActionSpaceClass = ActionSpace.init_grid(self.gridobj)
# self.size_act = 229
self.action_space_1 = self.get_action_space_1()
self.action_space_2 = self.get_action_space_2()
np.random.seed(42)
def aux_get_act(self, helper_action):
template_act = helper_action()
dict_act = {}
tmp_inj = {}
if "load_p" in template_act.attr_list_set:
tmp_inj["load_p"] = np.random.randn(helper_action.n_load).astype(dt_float)
if "load_q" in template_act.attr_list_set:
tmp_inj["load_q"] = np.random.randn(helper_action.n_load).astype(dt_float)
if "prod_p" in template_act.attr_list_set:
tmp_inj["prod_p"] = np.random.randn(helper_action.n_gen).astype(dt_float)
if "prod_v" in template_act.attr_list_set:
tmp_inj["prod_v"] = np.random.randn(helper_action.n_gen).astype(dt_float)
if dict_act:
dict_act["injection"] = tmp_inj
if "_hazards" in template_act.attr_list_set:
dict_act["hazards"] = np.random.choice(
[True, False], helper_action.n_line
).astype(dt_bool)
if "_maintenance" in template_act.attr_list_set:
dict_act["maintenance"] = np.random.choice(
[True, False], helper_action.n_line
).astype(dt_bool)
if "_redispatch" in template_act.attr_list_set:
dict_act["redispatch"] = np.random.randn(helper_action.n_gen).astype(
dt_float
)
dict_act["redispatch"] -= np.mean(dict_act["redispatch"])
if "_set_line_status" in template_act.attr_list_set:
# i dont test the line reconnection...
dict_act["set_line_status"] = np.random.choice(
[-1, 0], helper_action.n_line
).astype(dt_int)
if "_switch_line_status" in template_act.attr_list_set:
# i dont test the line reconnection...
dict_act["change_line_status"] = np.random.choice(
[True, False], helper_action.n_line
).astype(dt_bool)
if "_set_topo_vect" in template_act.attr_list_set:
# i dont test the line reconnection...
dict_act["set_bus"] = np.random.choice(
[1, 2], helper_action.dim_topo
).astype(dt_int)
if "_change_bus_vect" in template_act.attr_list_set:
# i dont test the line reconnection...
dict_act["change_bus"] = np.random.choice(
[True, False], helper_action.dim_topo
).astype(dt_bool)
return helper_action(dict_act)
def test_iadd_modify(self):
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("error")
if act2.attr_list_set - act1.attr_list_set:
# it should raise a warning if i attempt to set an attribute it's not supposed to
with self.assertWarns(UserWarning):
act1 += act2
else:
# i can add it i check it's properly added, without warnings
act1 += act2
# i now test all attributes have been modified for attributes in both
for attr_nm in act1.attr_list_set & act2.attr_list_set:
assert np.any(
act1.__dict__[attr_nm] != act1_init.__dict__[attr_nm]
), "error, attr {} has not been updated".format(attr_nm)
# for all in act1 not in act2, nothing should have changed
for attr_nm in act1.attr_list_set - act2.attr_list_set:
if attr_nm == "_set_line_status" or attr_nm == "_set_topo_vect":
# these vector can be changed if act2 allows for "change_line_status" or "change_bus"
# TODO improve these tests
continue
if (
attr_nm == "_switch_line_status"
or attr_nm == "_change_bus_vect"
):
# these vector can be changed if act2 allows for "set_line_status" or "set_bus"
# TODO improve these tests
continue
assert np.all(
act1.__dict__[attr_nm] == act1_init.__dict__[attr_nm]
), "error, attr {} has been updated".format(attr_nm)
def test_iadd_change_set_status(self):
self._skipMissingKey("change_line_status", self.action_space_1)
self._skipMissingKey("set_line_status", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
act1 += act2
assert np.sum(act1._switch_line_status[act2._set_line_status != 0]) == 0
def test_iadd_set_change_status(self):
self._skipMissingKey("set_line_status", self.action_space_1)
self._skipMissingKey("change_line_status", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
act1 += act2
# if act1 set a line but act2 change it, then it's equivalent to act1 set to the other value
indx_change = (act1._set_line_status != 0) & (act2._switch_line_status)
assert np.all(
act1._set_line_status[indx_change]
!= act1_init._set_line_status[indx_change]
)
# if act1 does not set, but act2 change, then act1 is not affected (for set)
indx_same = (act1._set_line_status == 0) & (act2._switch_line_status)
assert np.all(
act1._set_line_status[indx_same] == act1_init._set_line_status[indx_same]
)
def test_iadd_change_set_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
self._skipMissingKey("set_bus", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
act1 += act2
assert np.sum(act1._change_bus_vect[act2._set_topo_vect != 0]) == 0
def test_iadd_set_change_bus(self):
self._skipMissingKey("set_bus", self.action_space_1)
self._skipMissingKey("change_bus", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
act1 += act2
# if act1 set a line but act2 change it, then it's equivalent to act1 set to the other value
indx_change = (act1._set_topo_vect != 0) & (act2._change_bus_vect)
assert np.all(
act1._set_topo_vect[indx_change] != act1_init._set_topo_vect[indx_change]
)
# if act1 does not set, but act2 change, then act1 is not affected (for set)
indx_same = (act1._set_topo_vect == 0) & (act2._change_bus_vect)
assert np.all(
act1._set_topo_vect[indx_same] == act1_init._set_topo_vect[indx_same]
)
def test_iadd_empty_change_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
act1 = self.action_space_1({})
act2 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
# Iadd change
act1 += act2
assert act2._change_bus_vect[0] == True
assert act2._change_bus_vect[1] == True
assert act1._change_bus_vect[0] == True
assert act1._change_bus_vect[1] == True
assert np.any(act1._set_topo_vect != 0) == False
def test_iadd_change_change_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
act1 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
act2 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
# Iadd change
act1 += act2
assert act2._change_bus_vect[0] == True
assert act2._change_bus_vect[1] == True
assert act1._change_bus_vect[0] == False
assert act1._change_bus_vect[1] == False
assert np.any(act1._set_topo_vect != 0) == False
def test_add_modify(self):
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
list_2 = copy.deepcopy(act2.attr_list_set)
list_1 = copy.deepcopy(act1.attr_list_set)
with warnings.catch_warnings():
warnings.filterwarnings("error")
if len(list_2 - list_1):
# it should raise a warning if i attempt to set an attribute it's not supposed to
with self.assertWarns(UserWarning):
res = act1 + act2
else:
# i can add it i check it's properly added, without warnings
res = act1 + act2
# i now test all attributes have been modified for attributes in both
for attr_nm in res.attr_list_set & act2.attr_list_set:
assert np.any(
getattr(res, attr_nm) != getattr(act1_init, attr_nm)
), "error, attr {} has not been updated (case 0)".format(attr_nm)
# for all in act1 not in act2, nothing should have changed
for attr_nm in res.attr_list_set - act2.attr_list_set:
if attr_nm == "_set_line_status" or attr_nm == "_set_topo_vect":
# these vector can be changed if act2 allows for "change_line_status" or "change_bus"
# TODO improve these tests
continue
if (
attr_nm == "_switch_line_status"
or attr_nm == "_change_bus_vect"
):
# these vector can be changed if act2 allows for "set_line_status" or "set_bus"
# TODO improve these tests
continue
assert np.all(
getattr(res, attr_nm) == getattr(act1_init, attr_nm)
), "error, attr {} has been updated (case 1)".format(attr_nm)
def test_add_change_set_status(self):
self._skipMissingKey("change_line_status", self.action_space_1)
self._skipMissingKey("set_line_status", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
res = act1 + act2
assert np.sum(res._switch_line_status[act2._set_line_status != 0]) == 0
def test_add_set_change_status(self):
self._skipMissingKey("set_line_status", self.action_space_1)
self._skipMissingKey("change_line_status", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
res = act1 + act2
# if act1 set a line but act2 change it, then it's equivalent to act1 set to the other value
indx_change = (res._set_line_status != 0) & (act2._switch_line_status)
assert np.all(
res._set_line_status[indx_change] != act1_init._set_line_status[indx_change]
)
# if act1 does not set, but act2 change, then act1 is not affected (for set)
indx_same = (res._set_line_status == 0) & (act2._switch_line_status)
assert np.all(
res._set_line_status[indx_same] == act1_init._set_line_status[indx_same]
)
def test_add_change_set_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
self._skipMissingKey("set_bus", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
res = act1 + act2
assert np.sum(res._change_bus_vect[act2._set_topo_vect != 0]) == 0
def test_add_set_change_bus(self):
self._skipMissingKey("set_bus", self.action_space_1)
self._skipMissingKey("change_bus", self.action_space_2)
act1_init = self.aux_get_act(self.action_space_1)
act1 = copy.deepcopy(act1_init)
act2 = self.aux_get_act(self.action_space_2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# proper warnings are handled above
res = act1 + act2
# if act1 set a line but act2 change it, then it's equivalent to act1 set to the other value
indx_change = (res._set_topo_vect != 0) & (act2._change_bus_vect)
assert np.all(
res._set_topo_vect[indx_change] != act1_init._set_topo_vect[indx_change]
)
# if act1 does not set, but act2 change, then act1 is not affected (for set)
indx_same = (res._set_topo_vect == 0) & (act2._change_bus_vect)
assert np.all(
res._set_topo_vect[indx_same] == act1_init._set_topo_vect[indx_same]
)
def test_add_empty_change_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
act1 = self.action_space_1({})
act2 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
# add change
res = act1 + act2
assert act2._change_bus_vect[0] == True
assert act2._change_bus_vect[1] == True
assert res._change_bus_vect[0] == True
assert res._change_bus_vect[1] == True
assert np.any(res._set_topo_vect != 0) == False
def test_add_change_change_bus(self):
self._skipMissingKey("change_bus", self.action_space_1)
act1 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
act2 = self.action_space_1({"change_bus": {"substations_id": [(0, [0, 1])]}})
# add change
res = act1 + act2
assert act2._change_bus_vect[0] == True
assert act2._change_bus_vect[1] == True
assert res._change_bus_vect[0] == False
assert res._change_bus_vect[1] == False
assert np.any(res._set_topo_vect != 0) == False
# TODO a generic method to build them all maybe ?
class TestDontAct_PowerlineChangeAndDispatchAction(TestIADD, unittest.TestCase):
"""
Test suite using the DontAct class
"""
def get_action_space_1(self):
return self.ActionSpaceClass(
self.gridobj, legal_action=self.game_rules.legal_action, actionClass=DontAct
)
def get_action_space_2(self):
return self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=PowerlineChangeAndDispatchAction,
)
class TestPowerlineChangeAndDispatchAction_PowerlineChangeAndDispatchAction(
TestIADD, unittest.TestCase
):
"""
Test suite using the DontAct class
"""
def get_action_space_1(self):
return self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=PowerlineChangeAndDispatchAction,
)
def get_action_space_2(self):
return self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=PowerlineChangeAndDispatchAction,
)
class TestTopologyAndDispatchAction_PowerlineChangeAndDispatchAction(
TestIADD, unittest.TestCase
):
"""
Test suite using the DontAct class
"""
def get_action_space_1(self):
return self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=TopologyAndDispatchAction,
)
def get_action_space_2(self):
return self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=PowerlineChangeAndDispatchAction,
)
class TestTopologicalImpact(unittest.TestCase):
# weird stuf to avoid copy paste and inheritance
def _action_setup(self):
return TopologyAndDispatchAction
def setUp(self):
TestActionBase.setUp(self)
def test_no_inj_possible(self):
donothing = self.helper_action()
donothing._dict_inj["prod_p"] = 0.0
with self.assertRaises(AmbiguousAction):
_ = donothing()
def test_get_topo_imp_dn(self):
donothing = self.helper_action()
lines_impacted, subs_impacted = donothing.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 0
def test_get_topo_imp_changebus(self):
changelor = self.helper_action({"change_bus": {"lines_or_id": [0]}})
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[0]
changelex = self.helper_action({"change_bus": {"lines_ex_id": [0]}})
lines_impacted, subs_impacted = changelex.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[1]
changeload = self.helper_action({"change_bus": {"loads_id": [0]}})
lines_impacted, subs_impacted = changeload.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[1]
changegen = self.helper_action({"change_bus": {"generators_id": [0]}})
lines_impacted, subs_impacted = changegen.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[0]
def test_get_topo_imp_setbus(self):
changelor = self.helper_action({"set_bus": {"lines_or_id": [(0, 2)]}})
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[0]
changelex = self.helper_action({"set_bus": {"lines_ex_id": [(0, 2)]}})
lines_impacted, subs_impacted = changelex.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[1]
changeload = self.helper_action({"set_bus": {"loads_id": [(0, 2)]}})
lines_impacted, subs_impacted = changeload.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[1]
changegen = self.helper_action({"set_bus": {"generators_id": [(0, 2)]}})
lines_impacted, subs_impacted = changegen.get_topological_impact()
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 1
assert subs_impacted[0]
def test_get_topo_imp_changestatus(self):
changelor = self.helper_action({"change_line_status": [7]})
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 0
assert lines_impacted[7]
def test_get_topo_imp_setstatus_down(self):
changelor = self.helper_action({"set_line_status": [(9, -1)]})
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 0
assert lines_impacted[9]
def test_get_topo_imp_setstatus_up(self):
changelor = self.helper_action(
{
"set_line_status": [(9, 1)],
"set_bus": {"lines_or_id": [(9, 2)], "lines_ex_id": [(9, 2)]},
}
)
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 0
assert lines_impacted[9]
def test_get_topo_imp_setstatus_up_2(self):
# i set a status (no substation impacted, one line impacted)
# plus I change the topology of one element (one sub impacted, no line impacted)
l_id = 0
changelor = self.helper_action(
{
"set_line_status": [(l_id, 1)],
"set_bus": {"lines_or_id": [(l_id, 2)], "lines_ex_id": [(l_id, 2)]},
}
)
changelor.update({"set_bus": {"generators_id": [(0, 2)]}})
lines_impacted, subs_impacted = changelor.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 1
assert lines_impacted[l_id]
assert subs_impacted[0]
def test_get_topo_imp_setstatus_up_alreadyup(self):
l_id = 15
powerline_status = np.full(self.n_line, fill_value=True, dtype=dt_bool)
changelor = self.helper_action(
{
"set_line_status": [(l_id, 1)],
"set_bus": {"lines_or_id": [(l_id, 1)], "lines_ex_id": [(l_id, 1)]},
}
)
# powerline is already connected
# i fake connect it, so it's like changing both its ends
lines_impacted, subs_impacted = changelor.get_topological_impact(
powerline_status
)
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 2
assert lines_impacted[l_id]
assert subs_impacted[self.res["line_or_to_subid"][l_id]]
assert subs_impacted[self.res["line_ex_to_subid"][l_id]]
def test_get_topo_imp_setstatus_up_alreadyup2(self):
# change a line that is already reconnected (2 subs) + 1 line
# and i change the object on same substation, should count as 0
l_id = 0
powerline_status = np.full(self.n_line, fill_value=True, dtype=dt_bool)
changelor = self.helper_action(
{
"set_line_status": [(l_id, 1)],
"set_bus": {"lines_or_id": [(l_id, 1)], "lines_ex_id": [(l_id, 1)]},
}
)
changelor.update({"set_bus": {"generators_id": [(0, 2)]}})
# powerline is already connected
# i fake connect it, so it's like changing both its ends
lines_impacted, subs_impacted = changelor.get_topological_impact(
powerline_status
)
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 2
assert lines_impacted[l_id]
assert subs_impacted[self.res["line_or_to_subid"][l_id]]
assert subs_impacted[self.res["line_ex_to_subid"][l_id]]
assert subs_impacted[0]
def test_get_topo_imp_setstatus_up_isdown(self):
l_id = 15
powerline_status = np.full(self.n_line, fill_value=True, dtype=dt_bool)
powerline_status[l_id] = False
changelor = self.helper_action(
{
"set_line_status": [(l_id, 1)],
"set_bus": {"lines_or_id": [(l_id, 1)], "lines_ex_id": [(l_id, 1)]},
}
)
# this is a real reconnection, is concerns only the powerline
lines_impacted, subs_impacted = changelor.get_topological_impact(
powerline_status
)
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 0
assert lines_impacted[l_id]
def test_get_topo_imp_setstatus_down_alreadydown(self):
self.skipTest("does not pass but should imho")
l_id = 12
powerline_status = np.full(self.n_line, fill_value=True, dtype=dt_bool)
powerline_status[l_id] = False
changelor = self.helper_action({"set_line_status": [(l_id, -1)]})
# powerline is already disconnected
lines_impacted, subs_impacted = changelor.get_topological_impact(
powerline_status
)
assert np.sum(lines_impacted) == 0
assert np.sum(subs_impacted) == 0
def test_get_topo_imp_setstatus_down_isup(self):
l_id = 3
powerline_status = np.full(self.n_line, fill_value=True, dtype=dt_bool)
changelor = self.helper_action({"set_line_status": [(l_id, -1)]})
# this is a real reconnection, is concerns only the powerline
lines_impacted, subs_impacted = changelor.get_topological_impact(
powerline_status
)
assert np.sum(lines_impacted) == 1
assert np.sum(subs_impacted) == 0
assert lines_impacted[l_id]
class TestDeepCopy(unittest.TestCase):
def test_alarm(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("l2rpn_icaps_2021", test=True) as env:
act = env.action_space()
act.raise_alarm = [0]
cpy = copy.deepcopy(act)
assert cpy == act
assert np.all(cpy.raise_alarm == [True, False, False])
def test_redisp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("l2rpn_icaps_2021", test=True) as env:
act = env.action_space()
act.redispatch = [(0, -1.0)]
cpy = copy.deepcopy(act)
assert cpy == act
assert cpy.redispatch[0] == -1.0
def test_storage(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("educ_case14_storage", test=True) as env:
act = env.action_space()
act.storage_p = [(0, -1.0)]
cpy = copy.deepcopy(act)
assert cpy == act
assert cpy.storage_p[0] == -1.0
def test_topo(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("l2rpn_case14_sandbox", test=True) as env:
# set line status
act = env.action_space()
act.set_line_status = [(0, -1)]
cpy = copy.deepcopy(act)
assert cpy == act
assert cpy.set_line_status[0] == -1
# change line status
act = env.action_space()
act.change_line_status = [0]
cpy = copy.deepcopy(act)
assert cpy == act
assert cpy.change_line_status[0]
# set_bus
act = env.action_space()
act.set_bus = [(0, 1), (1, 2), (2, 1)]
cpy = copy.deepcopy(act)
assert cpy == act
assert np.all(cpy.set_bus[:3] == [1, 2, 1])
# change_bus
act = env.action_space()
act.change_bus = [0, 1, 2]
cpy = copy.deepcopy(act)
assert cpy == act
assert np.all(cpy.change_bus[:3] == [True, True, True])
if __name__ == "__main__":
unittest.main()
| 87,872 | 36.568619 | 141 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_ActionProperties.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import re
from grid2op.tests.helper_path_test import *
from grid2op.dtypes import dt_int, dt_float, dt_bool
from grid2op.Exceptions import *
from grid2op.Action import *
from grid2op.Rules import RulesChecker
from grid2op.Space.space_utils import save_to_dict
from grid2op.tests.test_Action import _get_action_grid_class
import pdb
class TestSetBus(unittest.TestCase):
"""test the property to set the bus of the action"""
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
# self.size_act = 229
self.ActionSpaceClass = ActionSpace.init_grid(self.gridobj)
# self.helper_action = ActionSpace(self.gridobj, legal_action=self.game_rules.legal_action)
self.helper_action = self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=CompleteAction,
) # TopologySetAndStorageAction would be better
self.helper_action.seed(42)
# save_to_dict(self.res, self.helper_action, "subtype", lambda x: re.sub("(<class ')|('>)", "", "{}".format(x)))
save_to_dict(
self.res,
self.helper_action,
"_init_subtype",
lambda x: re.sub(
"(<class ')|(\\.init_grid\\.<locals>\\.res)|('>)", "", "{}".format(x)
),
)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def test_load_set_bus_array(self):
li_orig = [1, 2, -1, 2, 1, 0, 2, 1, 0, 1, 2] # because i have 11 loads
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.load_set_bus = tmp # ok
assert np.all(act.load_set_bus == tmp)
# array too short
with self.assertRaises(IllegalAction):
act = self.helper_action()
act.load_set_bus = tmp[:-1]
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# array too big
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp2 = np.concatenate((tmp, (1,)))
act.load_set_bus = tmp2
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# float vect
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp3 = np.array(li_orig).astype(dt_float)
act.load_set_bus = tmp3
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the value too small
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp4 = np.array(li_orig)
tmp4[2] = -2
act.load_set_bus = tmp4
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the value too large
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp5 = np.array(li_orig)
tmp5[2] = 3
act.load_set_bus = tmp5
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp6 = np.array(li_orig).astype(str)
tmp6[2] = "toto"
act.load_set_bus = tmp6
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
def test_load_set_bus_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.load_set_bus = (1, 1)
assert np.all(act.load_set_bus == [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (3.0, 1)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (False, 1)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = ("toto", 1)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (1, "toto")
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (11, 1)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (-1, 1)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (1,)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.load_set_bus = (1, 2, 3)
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
def test_load_set_bus_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 2, -1, 2, 1, 0, 2, 1, 0, 1, 2] # because i have 11 loads
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.load_set_bus = li_orig
assert np.all(act.load_set_bus == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.load_set_bus = tmp0
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(2)
act.load_set_bus = tmp1
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.load_set_bus = tmp3
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[2] = -2
act.load_set_bus = tmp4
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[2] = 3
act.load_set_bus = tmp5
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[2] = "toto"
act.load_set_bus = tmp6
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
def test_load_set_bus_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (2, -1), (5, 2)]
# ok
act = self.helper_action()
act.load_set_bus = li_orig
assert np.all(act.load_set_bus == [1, 0, -1, 0, 0, 2, 0, 0, 0, 0, 0])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.load_set_bus = tmp3
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[2] = (3, -2)
act.load_set_bus = tmp4
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[2] = (3, 3)
act.load_set_bus = tmp5
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[2] = ("toto", 1)
act.load_set_bus = tmp6
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[2] = (3, "toto")
act.load_set_bus = tmp7
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((11, 1))
act.load_set_bus = tmp8
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.load_set_bus = tmp9
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
act.load_set_bus = [(el, 2) for el in range(act.n_load)]
assert np.all(act.load_set_bus == 2)
def test_load_set_bus_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1, 2: -1, 5: 2}
# ok
act = self.helper_action()
act.load_set_bus = dict_orig
assert np.all(act.load_set_bus == [1, 0, -1, 0, 0, 2, 0, 0, 0, 0, 0])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.load_set_bus = tmp3
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[2] = -2
act.load_set_bus = tmp4
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[2] = 3
act.load_set_bus = tmp5
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.load_set_bus = tmp6
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[3] = "tata"
act.load_set_bus = tmp7
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[11] = 1
act.load_set_bus = tmp8
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.load_set_bus = tmp9
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
def test_load_set_bus_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"load_0": 1, "load_2": -1, "load_5": 2}
# ok
act = self.helper_action()
act.load_set_bus = dict_orig
assert np.all(act.load_set_bus == [1, 0, -1, 0, 0, 2, 0, 0, 0, 0, 0])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.load_set_bus = tmp6
assert np.all(
act.load_set_bus == 0
), "a load has been modified by an illegal action"
def test_gen_set_bus_array(self):
li_orig = [1, 2, -1, 2, 1] # because i have 5 gens
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.gen_set_bus = tmp # ok
assert np.all(act.gen_set_bus == tmp)
# array too short
with self.assertRaises(IllegalAction):
act = self.helper_action()
act.gen_set_bus = tmp[:-1]
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# array too big
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp2 = np.concatenate((tmp, (1,)))
act.gen_set_bus = tmp2
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# float vect
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp3 = np.array(li_orig).astype(dt_float)
act.gen_set_bus = tmp3
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the value too small
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp4 = np.array(li_orig)
tmp4[2] = -2
act.gen_set_bus = tmp4
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the value too large
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp5 = np.array(li_orig)
tmp5[2] = 3
act.gen_set_bus = tmp5
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type
with self.assertRaises(IllegalAction):
act = self.helper_action()
tmp6 = np.array(li_orig).astype(str)
tmp6[2] = "toto"
act.gen_set_bus = tmp6
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
def test_gen_set_bus_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.gen_set_bus = (1, 1)
assert np.all(act.gen_set_bus == [0, 1, 0, 0, 0])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (3.0, 1)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (False, 1)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = ("toto", 1)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (1, "toto")
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (6, 1)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (-1, 1)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (1,)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.gen_set_bus = (1, 2, 3)
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
def test_gen_set_bus_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 2, -1, 2, 1] # because i have 5 gens
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.gen_set_bus = li_orig
assert np.all(act.gen_set_bus == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.gen_set_bus = tmp0
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(2)
act.gen_set_bus = tmp1
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.gen_set_bus = tmp3
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[2] = -2
act.gen_set_bus = tmp4
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[2] = 3
act.gen_set_bus = tmp5
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[2] = "toto"
act.gen_set_bus = tmp6
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
def test_gen_set_bus_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (2, -1), (4, 2)]
# ok
act = self.helper_action()
act.gen_set_bus = li_orig
assert np.all(act.gen_set_bus == [1, 0, -1, 0, 2])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.gen_set_bus = tmp3
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[2] = (3, -2)
act.gen_set_bus = tmp4
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[2] = (3, 3)
act.gen_set_bus = tmp5
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[2] = ("toto", 1)
act.gen_set_bus = tmp6
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[2] = (3, "toto")
act.gen_set_bus = tmp7
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((5, 1))
act.gen_set_bus = tmp8
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.gen_set_bus = tmp9
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# when the list has exactly the same size
act = self.helper_action()
act.gen_set_bus = [(el, 2) for el in range(act.n_gen)]
assert np.all(act.gen_set_bus == 2)
def test_gen_set_bus_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1, 2: -1, 4: 2}
# ok
act = self.helper_action()
act.gen_set_bus = dict_orig
assert np.all(act.gen_set_bus == [1, 0, -1, 0, 2])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.gen_set_bus = tmp3
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[2] = -2
act.gen_set_bus = tmp4
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[2] = 3
act.gen_set_bus = tmp5
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.gen_set_bus = tmp6
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[3] = "tata"
act.gen_set_bus = tmp7
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[11] = 1
act.gen_set_bus = tmp8
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.gen_set_bus = tmp9
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
def test_gen_set_bus_dict_with_name(self):
"""test the set attribute when dict are given with key = names"""
dict_orig = {"gen_0": 1, "gen_2": -1, "gen_4": 2}
# ok
act = self.helper_action()
act.gen_set_bus = dict_orig
assert np.all(act.gen_set_bus == [1, 0, -1, 0, 2])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown gen
act.gen_set_bus = tmp6
assert np.all(
act.gen_set_bus == 0
), "a gen has been modified by an illegal action"
def test_storage_set_bus_array(self):
li_orig = [1, 2] # because i have 2 loads
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.storage_set_bus = tmp # ok
assert np.all(act.storage_set_bus == tmp)
# array too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = tmp[0]
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# array too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (1,)))
act.storage_set_bus = tmp2
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# float vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.array(li_orig).astype(dt_float)
act.storage_set_bus = tmp3
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = np.array(li_orig)
tmp4[1] = -2
act.storage_set_bus = tmp4
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = np.array(li_orig)
tmp5[1] = 3
act.storage_set_bus = tmp5
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
act.storage_set_bus = tmp6
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
def test_storage_set_bus_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.storage_set_bus = (1, 1)
assert np.all(act.storage_set_bus == [0, 1])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (1.0, 1)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (False, 1)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = ("toto", 1)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (1, "toto")
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (11, 1)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (-1, 1)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (1,)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.storage_set_bus = (1, 2, 3)
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
def test_storage_set_bus_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 2] # because i have 2 storage unit
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.storage_set_bus = li_orig
assert np.all(act.storage_set_bus == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.storage_set_bus = tmp0
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(2)
act.storage_set_bus = tmp1
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.storage_set_bus = tmp3
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = -2
act.storage_set_bus = tmp4
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = 3
act.storage_set_bus = tmp5
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[1] = "toto"
act.storage_set_bus = tmp6
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
def test_storage_set_bus_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (1, 2)]
# ok
act = self.helper_action()
act.storage_set_bus = li_orig
assert np.all(act.storage_set_bus == [1, 2])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.storage_set_bus = tmp3
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = (1, -2)
act.storage_set_bus = tmp4
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = (1, 3)
act.storage_set_bus = tmp5
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[1] = ("toto", 1)
act.storage_set_bus = tmp6
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[1] = (3, "toto")
act.storage_set_bus = tmp7
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((2, 1))
act.storage_set_bus = tmp8
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.storage_set_bus = tmp9
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
act.storage_set_bus = [(el, 2) for el in range(act.n_storage)]
assert np.all(act.storage_set_bus == 2)
def test_storage_set_bus_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1}
# ok
act = self.helper_action()
act.storage_set_bus = dict_orig
assert np.all(act.storage_set_bus == [1, 0])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.storage_set_bus = tmp3
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[1] = -2
act.storage_set_bus = tmp4
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[1] = 3
act.storage_set_bus = tmp5
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.storage_set_bus = tmp6
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[1] = "tata"
act.storage_set_bus = tmp7
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[2] = 1
act.storage_set_bus = tmp8
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.storage_set_bus = tmp9
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
def test_storage_set_bus_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"storage_0": 1}
# ok
act = self.helper_action()
act.storage_set_bus = dict_orig
assert np.all(act.storage_set_bus == [1, 0])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.storage_set_bus = tmp6
assert np.all(
act.storage_set_bus == 0
), "a storage unit has been modified by an illegal action"
def test_line_or_set_bus_array(self):
li_orig = [
1,
2,
-1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
] # because i have 20 lines
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.line_or_set_bus = tmp # ok
assert np.all(act.line_or_set_bus == tmp)
# array too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = tmp[0]
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# array too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (1,)))
act.line_or_set_bus = tmp2
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# float vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.array(li_orig).astype(dt_float)
act.line_or_set_bus = tmp3
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = np.array(li_orig)
tmp4[1] = -2
act.line_or_set_bus = tmp4
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = np.array(li_orig)
tmp5[1] = 3
act.line_or_set_bus = tmp5
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_line_or_set_bus_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.line_or_set_bus = (1, 1)
assert np.all(act.line_or_set_bus == [0, 1] + [0 for _ in range(18)])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (1.0, 1)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (False, 1)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = ("toto", 1)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (1, "toto")
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (21, 1)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (-1, 1)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (1,)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_or_set_bus = (1, 2, 3)
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_line_or_set_bus_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 2, -1] + [0 for _ in range(17)] # because i have 2 storage unit
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.line_or_set_bus = li_orig
assert np.all(act.line_or_set_bus == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.line_or_set_bus = tmp0
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(2)
act.line_or_set_bus = tmp1
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.line_or_set_bus = tmp3
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = -2
act.line_or_set_bus = tmp4
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = 3
act.line_or_set_bus = tmp5
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[1] = "toto"
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_line_or_set_bus_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (1, 2)]
# ok
act = self.helper_action()
act.line_or_set_bus = li_orig
assert np.all(act.line_or_set_bus == [1, 2] + [0 for _ in range(18)])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.line_or_set_bus = tmp3
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = (1, -2)
act.line_or_set_bus = tmp4
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = (1, 3)
act.line_or_set_bus = tmp5
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[1] = ("toto", 1)
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[1] = (3, "toto")
act.line_or_set_bus = tmp7
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((21, 1))
act.line_or_set_bus = tmp8
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.line_or_set_bus = tmp9
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
act.line_or_set_bus = [(el, 2) for el in range(act.n_line)]
assert np.all(act.line_or_set_bus == 2)
def test_line_or_set_bus_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1}
# ok
act = self.helper_action()
act.line_or_set_bus = dict_orig
assert np.all(act.line_or_set_bus == [1, 0] + [0 for _ in range(18)])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.line_or_set_bus = tmp3
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[1] = -2
act.line_or_set_bus = tmp4
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[1] = 3
act.line_or_set_bus = tmp5
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[1] = "tata"
act.line_or_set_bus = tmp7
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[21] = 1
act.line_or_set_bus = tmp8
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.line_or_set_bus = tmp9
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_line_or_set_bus_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"line_0": 1}
# ok
act = self.helper_action()
act.line_or_set_bus = dict_orig
assert np.all(act.line_or_set_bus == [1, 0] + [0 for _ in range(18)])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_line_ex_set_bus_array(self):
li_orig = [
1,
2,
-1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
] # because i have 20 lines
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.line_ex_set_bus = tmp # ok
assert np.all(act.line_ex_set_bus == tmp)
# array too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = tmp[0]
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
# array too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (1,)))
act.line_ex_set_bus = tmp2
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
# float vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.array(li_orig).astype(dt_float)
act.line_ex_set_bus = tmp3
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = np.array(li_orig)
tmp4[1] = -2
act.line_ex_set_bus = tmp4
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = np.array(li_orig)
tmp5[1] = 3
act.line_ex_set_bus = tmp5
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
act.line_ex_set_bus = tmp6
assert np.all(
act.line_ex_set_bus == 0
), "a line (ext) unit has been modified by an illegal action"
def test_line_ex_set_bus_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.line_ex_set_bus = (1, 1)
assert np.all(act.line_ex_set_bus == [0, 1] + [0 for _ in range(18)])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (1.0, 1)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (False, 1)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = ("toto", 1)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (1, "toto")
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (21, 1)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (-1, 1)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (1,)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_ex_set_bus = (1, 2, 3)
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
def test_line_ex_set_bus_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 2, -1] + [0 for _ in range(17)] # because i have 2 storage unit
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.line_ex_set_bus = li_orig
assert np.all(act.line_ex_set_bus == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.line_ex_set_bus = tmp0
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(2)
act.line_ex_set_bus = tmp1
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.line_ex_set_bus = tmp3
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = -2
act.line_ex_set_bus = tmp4
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = 3
act.line_ex_set_bus = tmp5
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[1] = "toto"
act.line_ex_set_bus = tmp6
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
def test_line_ex_set_bus_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (1, 2)]
# ok
act = self.helper_action()
act.line_ex_set_bus = li_orig
assert np.all(act.line_ex_set_bus == [1, 2] + [0 for _ in range(18)])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.line_ex_set_bus = tmp3
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = (1, -2)
act.line_ex_set_bus = tmp4
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = (1, 3)
act.line_ex_set_bus = tmp5
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[1] = ("toto", 1)
act.line_ex_set_bus = tmp6
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[1] = (3, "toto")
act.line_ex_set_bus = tmp7
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((21, 1))
act.line_ex_set_bus = tmp8
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.line_ex_set_bus = tmp9
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
act.line_ex_set_bus = [(el, 2) for el in range(act.n_line)]
assert np.all(act.line_ex_set_bus == 2)
def test_line_ex_set_bus_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1}
# ok
act = self.helper_action()
act.line_ex_set_bus = dict_orig
assert np.all(act.line_ex_set_bus == [1, 0] + [0 for _ in range(18)])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.line_ex_set_bus = tmp3
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[1] = -2
act.line_ex_set_bus = tmp4
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[1] = 3
act.line_ex_set_bus = tmp5
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.line_ex_set_bus = tmp6
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[1] = "tata"
act.line_ex_set_bus = tmp7
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[21] = 1
act.line_ex_set_bus = tmp8
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.line_ex_set_bus = tmp9
assert np.all(
act.line_ex_set_bus == 0
), "a line (ex) unit has been modified by an illegal action"
def test_line_ex_set_bus_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"line_0": 1}
# ok
act = self.helper_action()
act.line_or_set_bus = dict_orig
assert np.all(act.line_or_set_bus == [1, 0] + [0 for _ in range(18)])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.line_or_set_bus = tmp6
assert np.all(
act.line_or_set_bus == 0
), "a line (origin) unit has been modified by an illegal action"
def test_set_by_sub(self):
# TODO more thorough testing !!!
act = self.helper_action()
act.sub_set_bus = (1, (1, 1, -1, 1, 2, 1, -1))
aff_lines, aff_subs = act.get_topological_impact()
assert aff_subs[1]
assert np.sum(aff_subs) == 1
with self.assertRaises(IllegalAction):
act.sub_set_bus = (1, (1, 1, -1, 1, 2, 3, -1)) # one too high
with self.assertRaises(IllegalAction):
act.sub_set_bus = (1, (1, 1, -1, 1, 2, -2, -1)) # one too low
with self.assertRaises(IllegalAction):
act.sub_set_bus = (1, (1, 1, -1, 1, 2, -1)) # too short
with self.assertRaises(IllegalAction):
act.sub_set_bus = (1, (1, 1, -1, 1, 2, 1, 2, 2)) # too big
with self.assertRaises(IllegalAction):
act.sub_set_bus = np.zeros(act.dim_topo + 1, dtype=int) # too long
with self.assertRaises(IllegalAction):
act.sub_set_bus = np.zeros(act.dim_topo - 1, dtype=int) # too short
# ok
tmp = np.zeros(act.dim_topo, dtype=int) # too short
tmp[:10] = 1
act.sub_set_bus = tmp
aff_lines, aff_subs = act.get_topological_impact()
assert aff_subs[0]
assert aff_subs[1]
assert np.sum(aff_subs) == 2
def test_change_by_sub(self):
# TODO more thorough testing !!!
act = self.helper_action()
act.sub_change_bus = (1, (True, True, True, False, False, True, False))
aff_lines, aff_subs = act.get_topological_impact()
assert aff_subs[1]
assert np.sum(aff_subs) == 1
with self.assertRaises(IllegalAction):
act.sub_change_bus = (
1,
(True, True, True, False, False, True),
) # too short
with self.assertRaises(IllegalAction):
act.sub_change_bus = (
1,
(True, True, True, False, False, True, False, True),
) # too big
with self.assertRaises(IllegalAction):
act.sub_change_bus = np.zeros(act.dim_topo + 1, dtype=int) # too long
with self.assertRaises(IllegalAction):
act.sub_change_bus = np.zeros(act.dim_topo - 1, dtype=int) # too short
with self.assertRaises(IllegalAction):
act.sub_change_bus = np.zeros(act.dim_topo - 1, dtype=int) # wrong type
with self.assertRaises(IllegalAction):
act.sub_change_bus = np.zeros(act.dim_topo - 1, dtype=float) # wrong type
# ok
tmp = np.zeros(act.dim_topo, dtype=bool) # too short
tmp[:10] = True
act.sub_change_bus = tmp
aff_lines, aff_subs = act.get_topological_impact()
assert aff_subs[0]
assert aff_subs[1]
assert np.sum(aff_subs) == 2
class TestSetStatus(unittest.TestCase):
"""test the property to set the status of the action"""
# TODO test the act.set_bus too here !
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
# self.size_act = 229
self.ActionSpaceClass = ActionSpace.init_grid(self.gridobj)
# self.helper_action = ActionSpace(self.gridobj, legal_action=self.game_rules.legal_action)
self.helper_action = self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=PowerlineSetAction,
)
self.helper_action.seed(42)
# save_to_dict(self.res, self.helper_action, "subtype", lambda x: re.sub("(<class ')|('>)", "", "{}".format(x)))
save_to_dict(
self.res,
self.helper_action,
"_init_subtype",
lambda x: re.sub(
"(<class ')|(\\.init_grid\\.<locals>\\.res)|('>)", "", "{}".format(x)
),
)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def test_line_set_status_array(self):
li_orig = [
1,
1,
-1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
] # because i have 20 lines
tmp = np.array(li_orig)
# first set of tests, with numpy array
act = self.helper_action()
act.line_set_status = tmp # ok
assert np.all(act.line_set_status == tmp)
# array too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = tmp[0]
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# array too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (1,)))
act.line_set_status = tmp2
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# float vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.array(li_orig).astype(dt_float)
act.line_set_status = tmp3
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = np.array(li_orig)
tmp4[1] = -2
act.line_set_status = tmp4
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = np.array(li_orig)
tmp5[1] = 2
act.line_set_status = tmp5
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
act.line_ex_set_bus = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
def test_line_set_status_tuple(self):
# second set of tests, with tuple
act = self.helper_action()
act.line_set_status = (1, 1)
assert np.all(act.line_set_status == [0, 1] + [0 for _ in range(18)])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (1.0, 1)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (False, 1)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = ("toto", 1)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (1, "toto")
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (21, 1)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (-1, 1)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# not enough element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (1,)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# too much element in the tuple
act = self.helper_action()
with self.assertRaises(IllegalAction):
act.line_set_status = (1, 2, 3)
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
def test_line_set_status_list_asarray(self):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1, 1, -1] + [0 for _ in range(17)] # because i have 2 storage unit
tmp = np.array(li_orig)
# ok
act = self.helper_action()
act.line_set_status = li_orig
assert np.all(act.line_set_status == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
act.line_set_status = tmp0
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(1)
act.line_set_status = tmp1
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [float(el) for el in li_orig]
act.line_set_status = tmp3
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = -2
act.line_set_status = tmp4
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = 2
act.line_set_status = tmp5
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[1] = "toto"
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
def test_line_set_status_list_oftuple(self):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1), (1, 1)]
# ok
act = self.helper_action()
act.line_set_status = li_orig
assert np.all(act.line_set_status == [1, 1] + [0 for _ in range(18)])
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
act.line_set_status = tmp3
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4[1] = (1, -2)
act.line_set_status = tmp4
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5[1] = (1, 2)
act.line_set_status = tmp5
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[1] = ("toto", 1)
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[1] = (3, "toto")
act.line_set_status = tmp7
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((21, 1))
act.line_set_status = tmp8
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
act.line_set_status = tmp9
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
act.line_set_status = [(el, 1) for el in range(act.n_line)]
assert np.all(act.line_set_status == 1)
def test_line_set_status_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1}
# ok
act = self.helper_action()
act.line_set_status = dict_orig
assert np.all(act.line_set_status == [1, 0] + [0 for _ in range(18)])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.line_set_status = tmp3
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[1] = -2
act.line_set_status = tmp4
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[1] = 3
act.line_set_status = tmp5
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[1] = "tata"
act.line_set_status = tmp7
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[21] = 1
act.line_set_status = tmp8
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.line_set_status = tmp9
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
def test_line_set_status_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"line_0": 1}
# ok
act = self.helper_action()
act.line_set_status = dict_orig
assert np.all(act.line_set_status == [1, 0] + [0 for _ in range(18)])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
class TestChangeBus(unittest.TestCase):
"""test the property to set the bus of the action"""
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
# self.size_act = 229
self.ActionSpaceClass = ActionSpace.init_grid(self.gridobj)
# self.helper_action = ActionSpace(self.gridobj, legal_action=self.game_rules.legal_action)
self.helper_action = self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=CompleteAction,
) # TopologyChangeAndStorageAction would be better
self.helper_action.seed(42)
# save_to_dict(self.res, self.helper_action, "subtype", lambda x: re.sub("(<class ')|('>)", "", "{}".format(x)))
save_to_dict(
self.res,
self.helper_action,
"_init_subtype",
lambda x: re.sub(
"(<class ')|(\\.init_grid\\.<locals>\\.res)|('>)", "", "{}".format(x)
),
)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def _aux_change_bus_int(self, name_el, nb_el, prop="change_bus"):
"""first set of test by giving the id of the object i want to change"""
act = self.helper_action()
prop_name = f"{name_el}_{prop}"
setattr(act, prop_name, 1)
assert np.all(
getattr(act, prop_name) == [False, True] + [False for _ in range(nb_el - 2)]
)
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, 3.0)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, False)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, "toto")
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, "toto"))
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, nb_el + 1)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, -1)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
def test_load_change_bus_int(self):
self._aux_change_bus_int("load", self.helper_action.n_load)
def test_gen_change_bus_int(self):
self._aux_change_bus_int("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_int(self):
self._aux_change_bus_int("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_int(self):
self._aux_change_bus_int("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_int(self):
self._aux_change_bus_int("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_int(self):
self._aux_change_bus_int(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
def _aux_change_bus_tuple(self, name_el, nb_el, prop="change_bus"):
"""first set of test by giving the a tuple: should be deactivated!"""
act = self.helper_action()
prop_name = f"{name_el}_{prop}"
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1,))
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, False))
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, False, 3))
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
def test_load_change_bus_tuple(self):
self._aux_change_bus_tuple("load", self.helper_action.n_load)
def test_gen_change_bus_tuple(self):
self._aux_change_bus_tuple("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_tuple(self):
self._aux_change_bus_tuple("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_tuple(self):
self._aux_change_bus_tuple("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_tuple(self):
self._aux_change_bus_tuple("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_tuple(self):
self._aux_change_bus_tuple(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
def _aux_change_bus_arraybool(self, name_el, nb_el, prop="change_bus"):
"""test by giving the a complete an array of bool (all the vector)"""
prop_name = f"{name_el}_{prop}"
li_orig = [False, True] + [False for _ in range(nb_el - 2)]
tmp = np.array(li_orig)
tmp_dt_bool = np.array(li_orig).astype(dt_bool)
tmp_bool = np.array(li_orig).astype(bool)
act = self.helper_action()
setattr(act, prop_name, tmp)
assert np.all(
getattr(act, prop_name) == [False, True] + [False for _ in range(nb_el - 2)]
)
act = self.helper_action()
setattr(act, prop_name, tmp_dt_bool)
assert np.all(
getattr(act, prop_name) == [False, True] + [False for _ in range(nb_el - 2)]
)
act = self.helper_action()
setattr(act, prop_name, tmp_bool)
assert np.all(
getattr(act, prop_name) == [False, True] + [False for _ in range(nb_el - 2)]
)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, tmp[:-1])
assert np.all(
~getattr(act, prop_name)
), "a load has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp_1 = np.concatenate((tmp, (False,)))
setattr(act, prop_name, tmp_1)
assert np.all(
~getattr(act, prop_name)
), "a load has been modified by an illegal action"
def test_load_change_bus_arraybool(self):
self._aux_change_bus_arraybool("load", self.helper_action.n_load)
def test_gen_change_bus_arraybool(self):
self._aux_change_bus_arraybool("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_arraybool(self):
self._aux_change_bus_arraybool("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_arraybool(self):
self._aux_change_bus_arraybool("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_arraybool(self):
self._aux_change_bus_arraybool("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_arraybool(self):
self._aux_change_bus_arraybool(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
def _aux_change_bus_arrayint(self, name_el, nb_el, prop="change_bus"):
"""test by giving the a numpy array of int"""
prop_name = f"{name_el}_{prop}"
li_orig = [0, 1]
tmp = np.array(li_orig)
tmp_dt_int = np.array(li_orig).astype(dt_int)
tmp_int = np.array(li_orig).astype(int)
act = self.helper_action()
setattr(act, prop_name, tmp)
assert np.all(
getattr(act, prop_name) == [True, True] + [False for _ in range(nb_el - 2)]
)
act = self.helper_action()
setattr(act, prop_name, tmp_dt_int)
assert np.all(
getattr(act, prop_name) == [True, True] + [False for _ in range(nb_el - 2)]
)
act = self.helper_action()
setattr(act, prop_name, tmp_int)
assert np.all(
getattr(act, prop_name) == [True, True] + [False for _ in range(nb_el - 2)]
)
# one id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (-1,)))
setattr(act, prop_name, tmp2)
assert np.all(
~getattr(act, prop_name)
), "a load has been modified by an illegal action"
# one id too high
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.concatenate((tmp, (nb_el,)))
setattr(act, prop_name, tmp3)
assert np.all(
~getattr(act, prop_name)
), "a load has been modified by an illegal action"
def test_load_change_bus_arrayint(self):
self._aux_change_bus_arrayint("load", self.helper_action.n_load)
def test_gen_change_bus_arrayint(self):
self._aux_change_bus_arrayint("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_arrayint(self):
self._aux_change_bus_arrayint("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_arrayint(self):
self._aux_change_bus_arrayint("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_arrayint(self):
self._aux_change_bus_arrayint("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_arrayint(self):
self._aux_change_bus_arrayint(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
def _aux_change_bus_listbool(self, name_el, nb_el, prop="change_bus"):
"""
test by giving the a complete a list of bool (all the vector)
has been deactivate because of impossibility to check the test with `li_5`
below
"""
prop_name = f"{name_el}_{prop}"
li_orig = [False, True] + [False for _ in range(nb_el)]
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, li_orig)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, li_orig[:-1])
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
li_2 = copy.deepcopy(li_orig)
li_2.append(True)
setattr(act, prop_name, li_2)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# list mixed types (str)
act = self.helper_action()
with self.assertRaises(IllegalAction):
li_3 = copy.deepcopy(li_orig)
li_3.append("toto")
setattr(act, prop_name, li_3)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# list mixed types (float)
act = self.helper_action()
with self.assertRaises(IllegalAction):
li_4 = copy.deepcopy(li_orig)
li_4.append(1.0)
setattr(act, prop_name, li_4)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# list mixed types (int)
act = self.helper_action()
with self.assertRaises(IllegalAction):
li_5 = copy.deepcopy(li_orig)
li_5.append(1)
setattr(act, prop_name, li_5)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
def test_load_change_bus_listbool(self):
self._aux_change_bus_listbool("load", nb_el=self.helper_action.n_load)
def test_gen_change_bus_listbool(self):
self._aux_change_bus_listbool("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_listbool(self):
self._aux_change_bus_listbool("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_listbool(self):
self._aux_change_bus_listbool("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_listbool(self):
self._aux_change_bus_listbool("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_listbool(self):
self._aux_change_bus_listbool(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
def _aux_change_bus_listint(self, name_el, nb_el, prop="change_bus"):
"""
test by giving the a a list of int
"""
prop_name = f"{name_el}_{prop}"
li_orig = [0]
act = self.helper_action()
setattr(act, prop_name, li_orig)
assert np.all(
getattr(act, prop_name) == [True, False] + [False for _ in range(nb_el - 2)]
)
# one id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = copy.deepcopy(li_orig)
tmp2.append(-1)
setattr(act, prop_name, tmp2)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# one id too high
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = copy.deepcopy(li_orig)
tmp3.append(nb_el)
setattr(act, prop_name, tmp3)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# one string
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(li_orig)
tmp4.append("toto")
setattr(act, prop_name, tmp4)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# one float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5.append(1.0)
setattr(act, prop_name, tmp5)
assert np.all(
~getattr(act, prop_name)
), f"a {name_el} has been modified by an illegal action"
# test it revert back to proper thing
act = self.helper_action()
setattr(act, prop_name, li_orig)
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(li_orig)
tmp5.append(1.0)
setattr(act, prop_name, tmp5)
assert np.all(
getattr(act, prop_name) == [True, False] + [False for _ in range(nb_el - 2)]
)
# test if change twice it's equivalent to not changing at all
act = self.helper_action()
setattr(act, prop_name, li_orig)
assert np.all(
getattr(act, prop_name) == [True, False] + [False for _ in range(nb_el - 2)]
)
setattr(act, prop_name, li_orig)
assert np.all(
getattr(act, prop_name)
== [False, False] + [False for _ in range(nb_el - 2)]
)
def test_load_change_bus_listint(self):
self._aux_change_bus_listint("load", nb_el=self.helper_action.n_load)
def test_gen_change_bus_listint(self):
self._aux_change_bus_listint("gen", nb_el=self.helper_action.n_gen)
def test_storage_change_bus_listint(self):
self._aux_change_bus_listint("storage", nb_el=self.helper_action.n_storage)
def test_line_or_change_bus_listint(self):
self._aux_change_bus_listint("line_or", nb_el=self.helper_action.n_line)
def test_line_ex_change_bus_listint(self):
self._aux_change_bus_listint("line_ex", nb_el=self.helper_action.n_line)
def test_line_change_status_bus_listint(self):
self._aux_change_bus_listint(
"line", nb_el=self.helper_action.n_line, prop="change_status"
)
class TestSetValues(unittest.TestCase):
"""test the property to set continuous values"""
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls, self.res = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
# self.size_act = 229
self.ActionSpaceClass = ActionSpace.init_grid(self.gridobj)
# self.helper_action = ActionSpace(self.gridobj, legal_action=self.game_rules.legal_action)
self.helper_action = self.ActionSpaceClass(
self.gridobj,
legal_action=self.game_rules.legal_action,
actionClass=CompleteAction,
)
self.helper_action.seed(42)
# save_to_dict(self.res, self.helper_action, "subtype", lambda x: re.sub("(<class ')|('>)", "", "{}".format(x)))
save_to_dict(
self.res,
self.helper_action,
"_init_subtype",
lambda x: re.sub(
"(<class ')|(\\.init_grid\\.<locals>\\.res)|('>)", "", "{}".format(x)
),
)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def _aux_change_val_tuple(self, name_el, nb_el, prop_name):
"""first set of test by giving the id of the object i want to change"""
this_zero = [0.0 for _ in range(nb_el)]
# regular modification
act = self.helper_action()
setattr(act, prop_name, (1, 1.0))
assert np.all(
getattr(act, prop_name) == [0.0, 1.0] + [0.0 for _ in range(nb_el - 2)]
)
# nan action: should be discarded
act = self.helper_action()
setattr(act, prop_name, (1, np.NaN))
assert np.all(getattr(act, prop_name) == [0.0 for _ in range(nb_el)])
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (3.0, 1.0))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (False, 1.0))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, ("toto", 1.0))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, "toto"))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, False))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (nb_el + 1, 1.0))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (-1, 1.0))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# tuple wrong size
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1,))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# tuple wrong size
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, 1.0, 1))
assert np.all(
getattr(act, prop_name) == this_zero
), f"a {name_el} has been modified by an illegal action"
# test correct canceling
act = self.helper_action()
setattr(act, prop_name, (1, 1.0))
with self.assertRaises(IllegalAction):
setattr(act, prop_name, (1, 1.0, 1))
assert np.all(
getattr(act, prop_name) == [0.0, 1.0] + [0.0 for _ in range(nb_el - 2)]
)
def test_redisp_tuple(self):
self._aux_change_val_tuple("redisp", self.helper_action.n_gen, "redispatch")
def test_storage_power_tuple(self):
self._aux_change_val_tuple("storage", self.helper_action.n_storage, "storage_p")
def _aux_set_val_array(self, name_el, nb_el, prop_name):
li_orig = [1.0, -1.0] + [0.0 for _ in range(nb_el - 2)]
tmp = np.array(li_orig)
tmp_dt_float = np.array(li_orig).astype(dt_float)
tmp_np_float = np.array(li_orig).astype(float)
# first set of tests, with numpy array
act = self.helper_action()
setattr(act, prop_name, tmp) # ok
assert np.all(getattr(act, prop_name) == li_orig)
act = self.helper_action()
setattr(act, prop_name, tmp_dt_float) # ok
assert np.all(getattr(act, prop_name) == li_orig)
act = self.helper_action()
setattr(act, prop_name, tmp_np_float) # ok
assert np.all(getattr(act, prop_name) == li_orig)
# array too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
setattr(act, prop_name, tmp[0])
assert np.all(getattr(act, prop_name) == 0)
# array too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp2 = np.concatenate((tmp, (1,)))
setattr(act, prop_name, tmp2)
assert np.all(getattr(act, prop_name) == 0)
# bool vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = np.array(li_orig).astype(dt_bool)
setattr(act, prop_name, tmp3)
assert np.all(getattr(act, prop_name) == 0)
# int vect
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = np.array(li_orig).astype(dt_int)
setattr(act, prop_name, tmp4)
assert np.all(getattr(act, prop_name) == 0)
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
setattr(act, prop_name, tmp6)
assert np.all(getattr(act, prop_name) == 0)
# test reset ok
act = self.helper_action()
setattr(act, prop_name, tmp) # ok
with self.assertRaises(IllegalAction):
tmp6 = np.array(li_orig).astype(str)
tmp6[1] = "toto"
setattr(act, prop_name, tmp6)
assert np.all(getattr(act, prop_name) == li_orig)
def test_redisp_array(self):
self._aux_set_val_array("redisp", self.helper_action.n_gen, "redispatch")
def test_storage_power_array(self):
self._aux_set_val_array("storage", self.helper_action.n_storage, "storage_p")
def _aux_set_val_list_asarray(self, name_el, nb_el, prop_name):
"""test the set attribute when list are given (list convertible to array)"""
li_orig = [1.0, -1.0] + [0 for _ in range(nb_el - 2)]
tmp = np.array(li_orig)
# ok
act = self.helper_action()
setattr(act, prop_name, li_orig)
assert np.all(getattr(act, prop_name) == tmp)
# list too short
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp0 = copy.deepcopy(li_orig)
tmp0.pop(0)
setattr(act, prop_name, tmp0)
assert np.all(getattr(act, prop_name) == 0)
# list too big
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp1 = copy.deepcopy(li_orig)
tmp1.append(1.0)
setattr(act, prop_name, tmp1)
assert np.all(getattr(act, prop_name) == 0)
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [int(el) for el in li_orig]
setattr(act, prop_name, tmp3)
assert np.all(getattr(act, prop_name) == 0)
# wrong type
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = [str(el) for el in li_orig]
tmp6[1] = "toto"
setattr(act, prop_name, tmp6)
assert np.all(getattr(act, prop_name) == 0)
# reset ok
act = self.helper_action()
setattr(act, prop_name, li_orig)
with self.assertRaises(IllegalAction):
tmp3 = [int(el) for el in li_orig]
setattr(act, prop_name, tmp3)
assert np.all(getattr(act, prop_name) == tmp)
def test_redisp_list_asarray(self):
self._aux_set_val_list_asarray("redisp", self.helper_action.n_gen, "redispatch")
def test_storage_power_list_asarray(self):
self._aux_set_val_list_asarray(
"storage", self.helper_action.n_storage, "storage_p"
)
def _aux_set_val_list_oftuple(self, name_el, nb_el, prop_name):
"""test the set attribute when list are given (list of tuple)"""
li_orig = [(0, 1.0), (1, -1.0)]
# ok
act = self.helper_action()
setattr(act, prop_name, li_orig)
assert np.all(
getattr(act, prop_name) == [1.0, -1.0] + [0.0 for _ in range(nb_el - 2)]
)
# list of float (for the el_id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = [(float(id_), new_bus) for id_, new_bus in li_orig]
setattr(act, prop_name, tmp3)
assert np.all(getattr(act, prop_name) == 0)
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(li_orig)
tmp6[1] = ("toto", 1)
setattr(act, prop_name, tmp6)
assert np.all(getattr(act, prop_name) == 0)
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(li_orig)
tmp7[1] = (3, "toto")
setattr(act, prop_name, tmp7)
assert np.all(getattr(act, prop_name) == 0)
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(li_orig)
tmp8.append((21, 1))
setattr(act, prop_name, tmp8)
assert np.all(getattr(act, prop_name) == 0)
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(li_orig)
tmp9.append((-1, 1))
setattr(act, prop_name, tmp9)
assert np.all(getattr(act, prop_name) == 0)
# last test, when we give a list of tuple of exactly the right size
act = self.helper_action()
setattr(act, prop_name, [(el, 1) for el in range(nb_el)])
assert np.all(getattr(act, prop_name) == 1)
def test_redisp_list_oftuple(self):
self._aux_set_val_list_oftuple("redisp", self.helper_action.n_gen, "redispatch")
def test_storage_power_list_oftuple(self):
self._aux_set_val_list_oftuple(
"storage", self.helper_action.n_storage, "storage_p"
)
def todo_line_set_status_dict_with_id(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {0: 1}
# ok
act = self.helper_action()
act.line_set_status = dict_orig
assert np.all(act.line_set_status == [1, 0] + [0 for _ in range(18)])
# list of float
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp3 = {float(id_): new_bus for id_, new_bus in dict_orig.items()}
act.line_set_status = tmp3
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too small
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp4 = copy.deepcopy(dict_orig)
tmp4[1] = -2
act.line_set_status = tmp4
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# one of the bus value too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp5 = copy.deepcopy(dict_orig)
tmp5[1] = 3
act.line_set_status = tmp5
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (element id)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# wrong type (bus value)
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp7 = copy.deepcopy(dict_orig)
tmp7[1] = "tata"
act.line_set_status = tmp7
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too large
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp8 = copy.deepcopy(dict_orig)
tmp8[21] = 1
act.line_set_status = tmp8
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
# el_id too low
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp9 = copy.deepcopy(dict_orig)
tmp9[-1] = 1
act.line_set_status = tmp9
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
def todo_line_set_status_dict_with_name(self):
"""test the set attribute when list are given (list of tuple)"""
dict_orig = {"line_0": 1}
# ok
act = self.helper_action()
act.line_set_status = dict_orig
assert np.all(act.line_set_status == [1, 0] + [0 for _ in range(18)])
act = self.helper_action()
with self.assertRaises(IllegalAction):
tmp6 = copy.deepcopy(dict_orig)
tmp6["toto"] = 1 # unknown load
act.line_set_status = tmp6
assert np.all(
act.line_set_status == 0
), "a line status has been modified by an illegal action"
if __name__ == "__main__":
unittest.main()
| 121,249 | 35.775857 | 120 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Action_iadd.py | import unittest
import warnings
from abc import ABC, abstractmethod
import numpy as np
import grid2op
from grid2op.Action import *
from grid2op.dtypes import dt_float
import warnings
warnings.simplefilter("error")
class Test_iadd_Base(ABC):
@abstractmethod
def _action_setup(self):
pass
def _skipMissingKey(self, key):
if key not in self.action_t.authorized_keys:
skip_msg = f"Skipped: Missing authorized_key {key}"
unittest.TestCase.skipTest(self, skip_msg)
@classmethod
def setUpClass(cls):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
cls.action_t = cls._action_setup()
cls.env = grid2op.make(
"rte_case14_realistic", test=True, action_class=cls.action_t
)
@classmethod
def tearDownClass(cls):
cls.env.close()
def test_dn_iadd_dn(self):
# No skip for do nothing
# No skip for do nothing
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_dn_iadd_set_line(self):
# No skip for do nothing
self._skipMissingKey("set_line_status")
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_dn_iadd_change_line(self):
# No skip for do nothing
self._skipMissingKey("change_line_status")
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_dn_iadd_set_bus(self):
# No skip for do nothing
self._skipMissingKey("set_bus")
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_dn_iadd_change_bus(self):
# No skip for do nothing
self._skipMissingKey("change_bus")
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_dn_iadd_redisp(self):
# No skip for do nothing
self._skipMissingKey("redispatch")
# Create action me [dn]
act_me = self.env.action_space({})
# Test action me [dn]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_set_line_iadd_dn(self):
self._skipMissingKey("set_line_status")
# No skip for do nothing
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_set_line(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_line_status")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_set_line2(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_line_status")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(1, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == 0
assert act_oth._set_line_status[1] == -1
assert np.all(act_oth._set_line_status[2:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert act_me._set_line_status[1] == -1
assert np.all(act_me._set_line_status[2:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_set_line3(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_line_status")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, 1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == 1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(1, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == 0
assert act_oth._set_line_status[1] == -1
assert np.all(act_oth._set_line_status[2:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == 1
assert act_me._set_line_status[1] == -1
assert np.all(act_me._set_line_status[2:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_set_line4(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_line_status")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, 1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == 1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_change_line(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("change_line_status")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
# set + change = inverted change
assert act_me._set_line_status[0] == 1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_set_bus(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("set_bus")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_change_bus(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("change_bus")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_set_line_iadd_redisp(self):
self._skipMissingKey("set_line_status")
self._skipMissingKey("redispatch")
# Create action me [set_line]
act_me = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action me [set_line]
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
def test_change_line_iadd_dn(self):
self._skipMissingKey("change_line_status")
# No skip for do nothing
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_set_line(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("set_line_status")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_me._set_line_status[0] == -1
assert np.all(act_me._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_change_line(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("change_line_status")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_change_line2(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("change_line_status")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [3]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status[:3] == False)
assert act_oth._switch_line_status[3] == True
assert np.all(act_oth._switch_line_status[4:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert act_me._switch_line_status[3] == True
assert np.all(act_me._switch_line_status[4:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_set_bus(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("set_bus")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_change_bus(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("change_bus")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_line_iadd_redisp(self):
self._skipMissingKey("change_line_status")
self._skipMissingKey("redispatch")
# Create action me [change_line]
act_me = self.env.action_space({"change_line_status": [0]})
# Test action me [change_line]
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_me._switch_line_status[0] == True
assert np.all(act_me._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
def test_set_bus_iadd_dn(self):
self._skipMissingKey("set_bus")
# No skip for do nothing
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_set_line(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("set_line_status")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_change_line(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_line_status")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_set_bus(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("set_bus")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_set_bus2(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("set_bus")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [1] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 1
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 1
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_change_bus(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("change_bus")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
# Set + change = inverted
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 1
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == False)
assert np.all(act_me._redispatch == 0.0)
def test_set_bus_iadd_redisp(self):
self._skipMissingKey("set_bus")
self._skipMissingKey("redispatch")
# Create action me [set_bus]
act_me = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action me [set_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_me._set_topo_vect[0] == 2
assert np.all(act_me._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
def test_change_bus_iadd_dn(self):
self._skipMissingKey("change_bus")
# No skip for do nothing
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_bus_iadd_set_line(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("set_line_status")
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_bus_iadd_change_line(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("change_line_status")
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_bus_iadd_set_bus(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("set_bus")
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_bus_iadd_change_bus(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("change_bus")
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == False)
assert np.all(act_me._redispatch == 0.0)
def test_change_bus_iadd_redisp(self):
self._skipMissingKey("change_bus")
self._skipMissingKey("redispatch")
# Create action me [change_bus]
act_me = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action me [change_bus]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert np.all(act_me._redispatch == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_me._change_bus_vect[0] == True
assert np.all(act_me._change_bus_vect[1:] == False)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
def test_redisp_iadd_dn(self):
self._skipMissingKey("redispatch")
# No skip for do nothing
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [dn]
act_oth = self.env.action_space({})
# Test action oth [dn]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_redisp_iadd_set_line(self):
self._skipMissingKey("redispatch")
self._skipMissingKey("set_line_status")
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [set_line]
act_oth = self.env.action_space({"set_line_status": [(0, -1)]})
# Test action oth [set_line]
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert act_oth._set_line_status[0] == -1
assert np.all(act_oth._set_line_status[1:] == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_redisp_iadd_change_line(self):
self._skipMissingKey("redispatch")
self._skipMissingKey("change_line_status")
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [change_line]
act_oth = self.env.action_space({"change_line_status": [0]})
# Test action oth [change_line]
assert np.all(act_oth._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert act_oth._switch_line_status[0] == True
assert np.all(act_oth._switch_line_status[1:] == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_redisp_iadd_set_bus(self):
self._skipMissingKey("redispatch")
self._skipMissingKey("set_bus")
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [set_bus]
act_oth = self.env.action_space(
{
"set_bus": {
"substations_id": [(0, [2] + [0] * (self.env.sub_info[0] - 1))]
}
}
)
# Test action oth [set_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert act_oth._set_topo_vect[0] == 2
assert np.all(act_oth._set_topo_vect[1:] == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_redisp_iadd_change_bus(self):
self._skipMissingKey("redispatch")
self._skipMissingKey("change_bus")
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [change_bus]
act_oth = self.env.action_space(
{
"change_bus": {
"substations_id": [
(0, [True] + [False] * (self.env.sub_info[0] - 1))
]
}
}
)
# Test action oth [change_bus]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert np.all(act_oth._redispatch == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert act_oth._change_bus_vect[0] == True
assert np.all(act_oth._change_bus_vect[1:] == False)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
def test_redisp_iadd_redisp(self):
self._skipMissingKey("redispatch")
self._skipMissingKey("redispatch")
# Create action me [redisp]
act_me = self.env.action_space({"redispatch": {2: 1.42}})
# Test action me [redisp]
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
# Create action oth [redisp]
act_oth = self.env.action_space({"redispatch": {2: 1.42}})
# Test action oth [redisp]
assert np.all(act_oth._set_line_status == 0)
assert np.all(act_oth._switch_line_status == False)
assert np.all(act_oth._set_topo_vect == 0)
assert np.all(act_oth._change_bus_vect == 0)
assert act_oth._redispatch[2] == dt_float(1.42)
assert np.all(act_oth._redispatch[:2] == 0.0)
assert np.all(act_oth._redispatch[3:] == 0.0)
# Iadd actions
act_me += act_oth
# Test combination:
assert np.all(act_me._set_line_status == 0)
assert np.all(act_me._switch_line_status == False)
assert np.all(act_me._set_topo_vect == 0)
assert np.all(act_me._change_bus_vect == 0)
assert act_me._redispatch[2] == dt_float(1.42 * 2.0)
assert np.all(act_me._redispatch[:2] == 0.0)
assert np.all(act_me._redispatch[3:] == 0.0)
class Test_iadd_CompleteAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: CompleteAction
"""
@classmethod
def _action_setup(self):
return CompleteAction
class Test_iadd_DispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: DispatchAction
"""
@classmethod
def _action_setup(self):
return DispatchAction
class Test_iadd_DontAct(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: DontAct
"""
@classmethod
def _action_setup(self):
return DontAct
class Test_iadd_PlayableAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: PlayableAction
"""
@classmethod
def _action_setup(self):
return PlayableAction
class Test_iadd_PowerlineChangeAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: PowerlineChangeAction
"""
@classmethod
def _action_setup(self):
return PowerlineChangeAction
class Test_iadd_PowerlineChangeAndDispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: PowerlineChangeAndDispatchAction
"""
@classmethod
def _action_setup(self):
return PowerlineChangeAndDispatchAction
class Test_iadd_PowerlineSetAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: PowerlineSetAction
"""
@classmethod
def _action_setup(self):
return PowerlineSetAction
class Test_iadd_PowerlineSetAndDispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: PowerlineSetAndDispatchAction
"""
@classmethod
def _action_setup(self):
return PowerlineSetAndDispatchAction
class Test_iadd_TopologyAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologyAction
"""
@classmethod
def _action_setup(self):
return TopologyAction
class Test_iadd_TopologyAndDispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologyAndDispatchAction
"""
@classmethod
def _action_setup(self):
return TopologyAndDispatchAction
class Test_iadd_TopologyChangeAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologyChangeAction
"""
@classmethod
def _action_setup(self):
return TopologyChangeAction
class Test_iadd_TopologyChangeAndDispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologyChangeAndDispatchAction
"""
@classmethod
def _action_setup(self):
return TopologyChangeAndDispatchAction
class Test_iadd_TopologySetAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologySetAction
"""
@classmethod
def _action_setup(self):
return TopologySetAction
class Test_iadd_TopologySetAndDispatchAction(Test_iadd_Base, unittest.TestCase):
"""
Action iadd test suite for subclass: TopologySetAndDispatchAction
"""
@classmethod
def _action_setup(self):
return TopologySetAndDispatchAction
if __name__ == "__main__":
unittest.main()
| 69,628 | 35.454974 | 84 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Agent.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import time
import warnings
import pandapower as pp
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.Exceptions import *
from grid2op.MakeEnv import make
from grid2op.Agent import (
PowerLineSwitch,
TopologyGreedy,
DoNothingAgent,
RecoPowerlineAgent,
FromActionsListAgent,
)
from grid2op.Parameters import Parameters
from grid2op.dtypes import dt_float
from grid2op.Agent import RandomAgent
import pdb
DEBUG = False
if DEBUG:
print("pandapower version : {}".format(pp.__version__))
class TestAgent(HelperTests):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_redisp", test=True, param=param)
def tearDown(self):
self.env.close()
def _aux_test_agent(self, agent, i_max=30):
done = False
i = 0
beg_ = time.perf_counter()
cum_reward = dt_float(0.0)
obs = self.env.get_obs()
reward = 0.0
time_act = 0.0
all_acts = []
while not done:
# print("_______________")
beg__ = time.perf_counter()
act = agent.act(obs, reward, done)
all_acts.append(act)
end__ = time.perf_counter()
obs, reward, done, info = self.env.step(
act
) # should load the first time stamp
time_act += end__ - beg__
cum_reward += reward
i += 1
if i > i_max:
break
end_ = time.perf_counter()
if DEBUG:
li_text = [
"Env: {:.2f}s",
"\t - apply act {:.2f}s",
"\t - run pf: {:.2f}s",
"\t - env update + observation: {:.2f}s",
"\t - time env obs space: {:.2f}s",
"BaseAgent: {:.2f}s",
"Total time: {:.2f}s",
"Cumulative reward: {:1f}",
]
msg_ = "\n".join(li_text)
print(
msg_.format(
self.env._time_apply_act
+ self.env._time_powerflow
+ self.env._time_extract_obs, # env
self.env._time_apply_act, # apply act
self.env._time_powerflow, # run pf
self.env._time_extract_obs, # env update + obs
self.env.observation_space._update_env_time, # time get topo vect
time_act,
end_ - beg_,
cum_reward,
)
)
return i, cum_reward, all_acts
def test_0_donothing(self):
agent = DoNothingAgent(self.env.action_space)
with warnings.catch_warnings():
warnings.filterwarnings("error")
i, cum_reward, all_acts = self._aux_test_agent(agent)
assert i == 31, "The powerflow diverged before step 30 for do nothing"
expected_reward = dt_float(35140.027)
expected_reward = dt_float(35140.03125 / 12.)
assert (
np.abs(cum_reward - expected_reward, dtype=dt_float) <= self.tol_one
), f"The reward has not been properly computed {cum_reward} instead of {expected_reward}"
def test_1_powerlineswitch(self):
agent = PowerLineSwitch(self.env.action_space)
with warnings.catch_warnings():
warnings.filterwarnings("error")
i, cum_reward, all_acts = self._aux_test_agent(agent)
assert (
i == 31
), "The powerflow diverged before step 30 for powerline switch agent"
# switch to using df_float in the reward, change then the results
expected_reward = dt_float(35147.55859375)
expected_reward = dt_float(35147.7685546 / 12.)
assert (
np.abs(cum_reward - expected_reward) <= self.tol_one
), f"The reward has not been properly computed {cum_reward} instead of {expected_reward}"
def test_2_busswitch(self):
agent = TopologyGreedy(self.env.action_space)
with warnings.catch_warnings():
warnings.filterwarnings("error")
i, cum_reward, all_acts = self._aux_test_agent(agent, i_max=10)
assert i == 11, "The powerflow diverged before step 10 for greedy agent"
# i have more actions now, so this is not correct (though it should be..
# yet a proof that https://github.com/rte-france/Grid2Op/issues/86 is grounded
expected_reward = dt_float(12075.389)
expected_reward = dt_float(12277.632)
expected_reward = dt_float(12076.35644531 / 12.)
assert (
np.abs(cum_reward - expected_reward) <= self.tol_one
), f"The reward has not been properly computed {cum_reward} instead of {expected_reward}"
class TestMake2Agents(HelperTests):
def test_2random(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("rte_case5_example", test=True)
env2 = grid2op.make("rte_case14_realistic", test=True)
agent = RandomAgent(env.action_space)
agent2 = RandomAgent(env2.action_space)
# test i can reset the env
obs = env.reset()
obs2 = env2.reset()
# test the agent can act
act = agent.act(obs, 0.0, False)
act2 = agent2.act(obs2, 0.0, False)
# test the env can step
_ = env.step(act)
_ = env2.step(act2)
env.close()
env2.close()
class TestSeeding(HelperTests):
def test_random(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True) as env:
obs = env.reset()
my_agent = RandomAgent(env.action_space)
my_agent.seed(0)
nb_test = 100
res = np.zeros(nb_test, dtype=int)
res2 = np.zeros(nb_test, dtype=int)
res3 = np.zeros(nb_test, dtype=int)
for i in range(nb_test):
res[i] = my_agent.my_act(obs, 0.0, False)
my_agent.seed(0)
for i in range(nb_test):
res2[i] = my_agent.my_act(obs, 0.0, False)
my_agent.seed(1)
for i in range(nb_test):
res3[i] = my_agent.my_act(obs, 0.0, False)
# the same seeds should produce the same sequence
assert np.all(res == res2)
# different seeds should produce different sequence
assert np.any(res != res3)
class TestRecoPowerlineAgent(HelperTests):
def test_reco_simple(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 1
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True, param=param) as env:
my_agent = RecoPowerlineAgent(env.action_space)
obs = env.reset()
assert np.sum(obs.time_before_cooldown_line) == 0
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(1, -1)]})
)
assert np.sum(obs.time_before_cooldown_line) == 1
# the agent should do nothing, as the line is still in cooldown
act = my_agent.act(obs, reward, done)
assert not act.as_dict()
obs, reward, done, info = env.step(act)
# now cooldown is over
assert np.sum(obs.time_before_cooldown_line) == 0
act2 = my_agent.act(obs, reward, done)
ddict = act2.as_dict()
assert "set_line_status" in ddict
assert "nb_connected" in ddict["set_line_status"]
assert "connected_id" in ddict["set_line_status"]
assert ddict["set_line_status"]["nb_connected"] == 1
assert ddict["set_line_status"]["connected_id"][0] == 1
def test_reco_more_difficult(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True, param=param) as env:
my_agent = RecoPowerlineAgent(env.action_space)
obs = env.reset()
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(1, -1)]})
)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(2, -1)]})
)
# the agent should do nothing, as the line is still in cooldown
act = my_agent.act(obs, reward, done)
assert not act.as_dict()
obs, reward, done, info = env.step(act)
act = my_agent.act(obs, reward, done)
assert not act.as_dict()
obs, reward, done, info = env.step(act)
# now in theory i can reconnect the first one
act2 = my_agent.act(obs, reward, done)
ddict = act2.as_dict()
assert "set_line_status" in ddict
assert "nb_connected" in ddict["set_line_status"]
assert "connected_id" in ddict["set_line_status"]
assert ddict["set_line_status"]["nb_connected"] == 1
assert ddict["set_line_status"]["connected_id"][0] == 1
# but i will not implement it on the grid
obs, reward, done, info = env.step(env.action_space())
act3 = my_agent.act(obs, reward, done)
ddict3 = act3.as_dict()
assert len(my_agent.tested_action) == 2
# and it turns out i need to reconnect the first one first
assert "set_line_status" in ddict3
assert "nb_connected" in ddict3["set_line_status"]
assert "connected_id" in ddict3["set_line_status"]
assert ddict3["set_line_status"]["nb_connected"] == 1
assert ddict3["set_line_status"]["connected_id"][0] == 1
obs, reward, done, info = env.step(act3)
act4 = my_agent.act(obs, reward, done)
ddict4 = act4.as_dict()
assert len(my_agent.tested_action) == 1
# and it turns out i need to reconnect the first one first
assert "set_line_status" in ddict4
assert "nb_connected" in ddict4["set_line_status"]
assert "connected_id" in ddict4["set_line_status"]
assert ddict4["set_line_status"]["nb_connected"] == 1
assert ddict4["set_line_status"]["connected_id"][0] == 2
class TestFromList(HelperTests):
def test_agentfromlist_empty(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True, param=param) as env:
agent = FromActionsListAgent(env.action_space, action_list=[])
obs = env.reset()
# should do nothing
act = agent.act(obs, 0.0, False)
obs, reward, done, info = env.step(act)
assert act.can_affect_something() is False
act = agent.act(obs, 0.0, False)
obs, reward, done, info = env.step(act)
assert act.can_affect_something() is False
def test_agentfromlist(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True, param=param) as env:
agent = FromActionsListAgent(
env.action_space,
action_list=[env.action_space({"set_line_status": [(0, +1)]})],
)
obs = env.reset()
# should do nothing
act = agent.act(obs, 0.0, False)
obs, reward, done, info = env.step(act)
assert act == env.action_space({"set_line_status": [(0, +1)]})
act = agent.act(obs, 0.0, False)
obs, reward, done, info = env.step(act)
assert act.can_affect_something() is False
def test_agentfromlist_creation_fails(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case5_example", test=True, param=param) as env:
with self.assertRaises(AgentError):
# action_list should be an iterable
agent = FromActionsListAgent(env.action_space, action_list=1)
with self.assertRaises(AgentError):
# action_list should contain only actions
agent = FromActionsListAgent(env.action_space, action_list=[1])
with grid2op.make(
"l2rpn_case14_sandbox", test=True, param=param
) as env2:
with self.assertRaises(AgentError):
# action_list should contain only actions from a compatible environment
agent = FromActionsListAgent(
env.action_space,
action_list=[
env2.action_space({"set_line_status": [(0, +1)]})
],
)
with grid2op.make(
"rte_case5_example", test=True, param=param, _add_to_name="toto"
) as env3:
# this should work because it's the same underlying grid
agent = FromActionsListAgent(
env.action_space,
action_list=[env3.action_space({"set_line_status": [(0, +1)]})],
)
if __name__ == "__main__":
unittest.main()
| 15,221 | 40.933884 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_AgentConverter.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import json
import re
import warnings
import pdb
from abc import ABC, abstractmethod
from grid2op.tests.helper_path_test import *
from grid2op.Agent import AgentWithConverter, MLAgent
from grid2op.Converter import IdToAct
from grid2op.Rules import AlwaysLegal
from grid2op import make
from grid2op.Parameters import Parameters
import warnings
warnings.simplefilter("error")
class TestAgent(AgentWithConverter):
def __init__(
self, action_space, env_name, action_space_converter=IdToAct, **kwargs_converter
):
AgentWithConverter.__init__(
self,
action_space,
action_space_converter=action_space_converter,
**kwargs_converter
)
self.action_space.all_actions = []
# do nothing
all_actions_tmp = [action_space()]
# powerline switch: disconnection
for i in range(action_space.n_line):
if env_name == "case14_realistic":
if i == 18:
continue
if env_name == "case5_example":
pass
all_actions_tmp.append(action_space.disconnect_powerline(line_id=i))
# other type of actions
all_actions_tmp += action_space.get_all_unitary_topologies_set(action_space)
# self.action_space.all_actions += action_space.get_all_unitary_redispatch(action_space)
if env_name == "case14_realistic":
# remove action that makes the powerflow diverge
breaking_acts = [
action_space(
{
"set_bus": {
"lines_or_id": [(7, 2), (8, 1), (9, 1)],
"lines_ex_id": [(17, 2)],
"generators_id": [(2, 2)],
"loads_id": [(4, 1)],
}
}
),
action_space(
{
"set_bus": {
"lines_or_id": [(10, 2), (11, 1), (19, 2)],
"lines_ex_id": [(16, 2)],
"loads_id": [(5, 1)],
}
}
),
action_space(
{
"set_bus": {
"lines_or_id": [(5, 1)],
"lines_ex_id": [(2, 2)],
"generators_id": [(1, 2)],
"loads_id": [(1, 1)],
}
}
),
action_space(
{
"set_bus": {
"lines_or_id": [(6, 2), (15, 2), (16, 1)],
"lines_ex_id": [(3, 2), (5, 2)],
"loads_id": [(2, 1)],
}
}
),
]
else:
breaking_acts = [
action_space(
{
"set_bus": {
"lines_or_id": [(0, 2), (1, 2), (2, 2), (3, 1)],
"generators_id": [(0, 1)],
"loads_id": [(0, 1)],
}
}
),
]
# filter out actions that break everything
all_actions = []
for el in all_actions_tmp:
if not el in breaking_acts:
all_actions.append(el)
# set the action to the action space
self.action_space.all_actions = all_actions
# add the action "reset everything to 1 bus"
self.action_space.all_actions.append(
action_space(
{
"set_bus": np.ones(action_space.dim_topo, dtype=int),
"set_line_status": np.ones(action_space.n_line, dtype=int),
}
)
)
self.nb_act_done = 0
self.act_this = True
def my_act(self, transformed_obs, reward, done=False):
if self.act_this:
res = self.nb_act_done
self.nb_act_done += 1
self.nb_act_done %= len(self.action_space.all_actions)
self.act_this = False
else:
res = -1
self.act_this = True
return res
class TestBasicConverter(unittest.TestCase):
def test_create_id2act(self):
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"rte_case5_example", param=param, gamerules_class=AlwaysLegal, test=True
)
my_agent = TestAgent(env.action_space, "rte_case5_example")
obs = env.reset()
for i in range(10):
act = my_agent.act(obs, 0, False)
obs, reward, done, info = env.step(act)
env.close()
def test_create_to_vect(self):
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"rte_case5_example", param=param, gamerules_class=AlwaysLegal, test=True
)
my_agent = MLAgent(env.action_space)
obs = env.reset()
for i in range(10):
act = my_agent.act(obs, 0, False)
obs, reward, done, info = env.step(act)
env.close()
if __name__ == "__main__":
unittest.main()
| 6,082 | 33.174157 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_AgentsFast.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import time
import warnings
import pandapower as pp
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.Exceptions import *
from grid2op.MakeEnv import make
from grid2op.Agent import DoNothingAgent, BaseAgent
from grid2op.Parameters import Parameters
from grid2op.dtypes import dt_float
from grid2op.Agent import RandomAgent
import pdb
DEBUG = False
if DEBUG:
print("pandapower version : {}".format(pp.__version__))
import warnings
warnings.simplefilter("error")
class RandomTestAgent(BaseAgent):
def act(self, observation, reward, done=False):
return self.action_space.sample()
class TestAgent(HelperTests):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_redisp", test=True, param=param)
def tearDown(self):
self.env.close()
def _aux_test_agent(self, agent, i_max=30):
done = False
i = 0
beg_ = time.perf_counter()
cum_reward = dt_float(0.0)
obs = self.env.get_obs()
reward = 0.0
time_act = 0.0
all_acts = []
while not done:
# print("_______________")
beg__ = time.perf_counter()
act = agent.act(obs, reward, done)
all_acts.append(act)
end__ = time.perf_counter()
obs, reward, done, info = self.env.step(
act
) # should load the first time stamp
time_act += end__ - beg__
cum_reward += reward
# print("reward: {}".format(reward))
# print("_______________")
# if reward <= 0 or np.any(obs.prod_p < 0):
# pdb.set_trace()
i += 1
if i > i_max:
break
end_ = time.perf_counter()
if DEBUG:
li_text = [
"Env: {:.2f}s",
"\t - apply act {:.2f}s",
"\t - run pf: {:.2f}s",
"\t - env update + observation: {:.2f}s",
"\t - time get topo vect: {:.2f}s",
"\t - time env obs space: {:.2f}s",
"BaseAgent: {:.2f}s",
"Total time: {:.2f}s",
"Cumulative reward: {:1f}",
]
msg_ = "\n".join(li_text)
print(
msg_.format(
self.env._time_apply_act
+ self.env._time_powerflow
+ self.env._time_extract_obs, # env
self.env._time_apply_act, # apply act
self.env._time_powerflow, # run pf
self.env._time_extract_obs, # env update + obs
self.env.backend._time_topo_vect, # time get topo vect
self.env.observation_space._update_env_time, # time get topo vect
time_act,
end_ - beg_,
cum_reward,
)
)
return i, cum_reward, all_acts
def test_0_donothing(self):
agent = DoNothingAgent(self.env.action_space)
with warnings.catch_warnings():
warnings.filterwarnings("error")
i, cum_reward, all_acts = self._aux_test_agent(agent)
assert i == 31, "The powerflow diverged before step 30 for do nothing"
expected_reward = dt_float(35140.027 / 12.)
expected_reward = dt_float(35140.03125 / 12.)
assert (
np.abs(cum_reward - expected_reward, dtype=dt_float) <= self.tol_one
), f"The reward has not been properly computed {cum_reward} instead of {expected_reward}"
def test_1_random(self):
agent = RandomTestAgent(self.env.action_space)
seed = 72 # don't change that !
agent.seed(seed)
with warnings.catch_warnings():
warnings.filterwarnings("error")
nb_steps, cum_reward, all_acts = self._aux_test_agent(agent)
assert nb_steps == 16, "The powerflow diverged before step 16 for RandomTestAgent"
expected_reward = dt_float(16441.488)
expected_reward = dt_float(16331.4873046875 / 12.)
expected_reward = dt_float(16331.54296875 / 12.)
assert (
np.abs(cum_reward - expected_reward, dtype=dt_float) <= self.tol_one
), f"The reward has not been properly computed {cum_reward} instead of {expected_reward}"
| 5,104 | 35.464286 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_AlarmFeature.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import unittest
import os
import tempfile
from grid2op.tests.helper_path_test import *
from grid2op.operator_attention import LinearAttentionBudget
from grid2op import make
from grid2op.Reward import RedispReward, _AlarmScore
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner
from grid2op.Environment import Environment
from grid2op.Episode import EpisodeData
class TestAlarmFeature(unittest.TestCase):
"""test the basic bahavior of the alarm feature"""
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(self.env_nm, test=True)
self.env.seed(0)
self.env.reset()
self.env.reset()
self.max_iter = 10
self.default_kwargs_att_budget = {
"max_budget": 5.0,
"budget_per_ts": 1.0 / (12.0 * 8),
"alarm_cost": 1.0,
"init_budget": 3.0,
}
def tearDown(self) -> None:
self.env.close()
def test_create_ok(self):
"""TestAlarmFeature.test_create_ok test that the stuff is created with the right parameters"""
assert self.env._has_attention_budget
assert self.env._attention_budget is not None
assert isinstance(self.env._attention_budget, LinearAttentionBudget)
assert abs(self.env._attention_budget._budget_per_ts - 1.0 / (12.0 * 8)) <= 1e-6
assert abs(self.env._attention_budget._max_budget - 5) <= 1e-6
assert abs(self.env._attention_budget._alarm_cost - 1) <= 1e-6
assert abs(self.env._attention_budget._current_budget - 3.0) <= 1e-6
with self.assertRaises(Grid2OpException):
# it raises because the default reward: AlarmReward can only be used
# if there is an alarm budget
with make(self.env_nm, has_attention_budget=False, test=True) as env:
assert env._has_attention_budget is False
assert env._attention_budget is None
with make(
self.env_nm,
has_attention_budget=False,
reward_class=RedispReward,
test=True,
) as env:
assert env._has_attention_budget is False
assert env._attention_budget is None
with make(
self.env_nm,
test=True,
kwargs_attention_budget={
"max_budget": 15,
"budget_per_ts": 1,
"init_budget": 0,
"alarm_cost": 12,
},
) as env:
assert env._has_attention_budget
assert env._attention_budget is not None
assert isinstance(env._attention_budget, LinearAttentionBudget)
assert abs(env._attention_budget._budget_per_ts - 1.0) <= 1e-6
assert abs(env._attention_budget._max_budget - 15) <= 1e-6
assert abs(env._attention_budget._alarm_cost - 12) <= 1e-6
assert abs(env._attention_budget._current_budget - 0.0) <= 1e-6
def test_budget_increases_ok(self):
"""test the attention budget properly increases when no alarm are raised
and that it does not exceed the maximum value"""
# check increaes ok normally
self.env.step(self.env.action_space())
assert (
abs(self.env._attention_budget._current_budget - (3 + 1.0 / (12.0 * 8.0)))
<= 1e-6
)
self.env.step(self.env.action_space())
assert (
abs(self.env._attention_budget._current_budget - (3 + 2.0 / (12.0 * 8.0)))
<= 1e-6
)
# check that it does not "overflow"
with make(
self.env_nm,
kwargs_attention_budget={
"max_budget": 5,
"budget_per_ts": 1,
"alarm_cost": 12,
"init_budget": 0,
},
test=True,
) as env:
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 1) <= 1e-6
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 2) <= 1e-6
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 3) <= 1e-6
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 4) <= 1e-6
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 5) <= 1e-6
env.step(self.env.action_space())
assert abs(env._attention_budget._current_budget - 5) <= 1e-6
def test_alarm_in_legal_action_ok(self):
"""I test the budget is properly updated when the action is legal and non ambiguous"""
act = self.env.action_space()
act.raise_alarm = [0]
self.env.step(act)
assert abs(self.env._attention_budget._current_budget - 2) <= 1e-6
def test_reset_ok(self):
self.env.step(self.env.action_space())
assert (
abs(self.env._attention_budget._current_budget - (3 + 1.0 / (12.0 * 8.0)))
<= 1e-6
)
self.env.reset()
assert abs(self.env._attention_budget._current_budget - 3) <= 1e-6
def test_illegal_action(self):
"""illegal action should not modify the alarm budget"""
th_budget = 3.0
act = self.env.action_space()
arr = 1 * act.set_bus
arr[:12] = 1
act.set_bus = arr
obs, reward, done, info = self.env.step(act)
assert info["is_illegal"]
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
act = self.env.action_space()
arr = 1 * act.set_bus
arr[:12] = 1
act.set_bus = arr
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
assert info["is_illegal"]
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
def test_ambiguous_action(self):
"""ambiguous action should not modify the alarm budget"""
th_budget = 3.0
act = self.env.action_space()
act.set_bus = [(0, 1)]
act.change_bus = [0]
obs, reward, done, info = self.env.step(act)
assert info["is_ambiguous"]
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
act = self.env.action_space()
act.set_bus = [(0, 1)]
act.change_bus = [0]
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
assert info["is_ambiguous"]
assert abs(self.env._attention_budget._current_budget - th_budget) <= 1e-6
def test_alarm_obs_noalarm(self):
"""test the observation is behaving correctly concerning the alarm part, when i don't send alarms"""
obs = self.env.reset()
assert abs(self.env._attention_budget._current_budget - 3.0) <= 1e-6
assert abs(obs.attention_budget - 3.0) <= 1e-6
obs, reward, done, info = self.env.step(self.env.action_space())
nb_th = 3 + 1.0 / (12.0 * 8.0)
assert abs(self.env._attention_budget._current_budget - nb_th) <= 1e-6
assert abs(obs.attention_budget - nb_th) <= 1e-6
assert obs.time_since_last_alarm == -1
def test_alarm_obs_whenalarm(self):
"""test the observation is behaving correctly concerning the alarm part, when i send alarms"""
act = self.env.action_space()
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
nb_th = 2
assert abs(self.env._attention_budget._current_budget - nb_th) <= 1e-6
assert abs(obs.attention_budget - nb_th) <= 1e-6
assert obs.time_since_last_alarm == 0
assert np.all(obs.last_alarm == [1, -1, -1])
obs, reward, done, info = self.env.step(self.env.action_space())
nb_th += 1.0 / (12.0 * 8.0)
assert abs(self.env._attention_budget._current_budget - nb_th) <= 1e-6
assert abs(obs.attention_budget - nb_th) <= 1e-6
assert obs.time_since_last_alarm == 1
assert np.all(obs.last_alarm == [1, -1, -1])
obs = self.env.reset()
nb_th = 3
assert abs(self.env._attention_budget._current_budget - nb_th) <= 1e-6
assert abs(obs.attention_budget - nb_th) <= 1e-6
assert obs.time_since_last_alarm == -1
assert np.all(obs.last_alarm == [-1, -1, -1])
def test_simulate_act_ok(self):
"""test the attention budget when simulating an ok action"""
obs = self.env.reset()
act = self.env.action_space()
act.raise_alarm = [0]
act2 = self.env.action_space()
act2.raise_alarm = [1]
# i simulate no action
sim_obs, *_ = obs.simulate(self.env.action_space())
nb_th = 3 + 1.0 / (12.0 * 8.0)
assert abs(sim_obs.attention_budget - nb_th) <= 1e-6
assert sim_obs.time_since_last_alarm == -1
assert np.all(sim_obs.last_alarm == [-1, -1, -1])
# i simulate an action, this should work as for step, if i do no actions
sim_obs, *_ = obs.simulate(act)
nb_th = 2
assert abs(sim_obs.attention_budget - nb_th) <= 1e-6
assert sim_obs.time_since_last_alarm == 0
assert np.all(sim_obs.last_alarm == [1, -1, -1])
# i simulate no action, this should remove the previous stuff and work
sim_obs, *_ = obs.simulate(self.env.action_space())
nb_th = 3 + 1.0 / (12.0 * 8.0)
assert abs(sim_obs.attention_budget - nb_th) <= 1e-6
assert sim_obs.time_since_last_alarm == -1
assert np.all(sim_obs.last_alarm == [-1, -1, -1])
# i do a step and check now
obs, *_ = self.env.step(act)
sim_obs, *_ = obs.simulate(self.env.action_space())
nb_th = 2 + 1.0 / (12.0 * 8.0)
assert abs(sim_obs.attention_budget - nb_th) <= 1e-6
assert sim_obs.time_since_last_alarm == 1
assert np.all(sim_obs.last_alarm == [1, -1, -1])
# i simulate an action, this should work as for step, if i do no actions
sim_obs, *_ = obs.simulate(act2)
nb_th = 1
assert abs(sim_obs.attention_budget - nb_th) <= 1e-6
assert sim_obs.time_since_last_alarm == 0
assert np.all(sim_obs.last_alarm == [1, 2, -1])
def _aux_trigger_cascading_failure(self):
act_ko1 = self.env.action_space()
act_ko1.line_set_status = [(56, -1)]
obs, reward, done, info = self.env.step(act_ko1)
assert not done
assert reward == 0
act_ko2 = self.env.action_space()
act_ko2.line_set_status = [(41, -1)]
obs, reward, done, info = self.env.step(act_ko2)
assert not done
assert reward == 0
act_ko3 = self.env.action_space()
act_ko3.line_set_status = [(40, -1)]
obs, reward, done, info = self.env.step(act_ko3)
assert not done
assert reward == 0
act_ko4 = self.env.action_space()
act_ko4.line_set_status = [(39, -1)]
obs, reward, done, info = self.env.step(act_ko4)
assert not done
assert reward == 0
act_ko5 = self.env.action_space()
act_ko5.line_set_status = [(13, -1)]
obs, reward, done, info = self.env.step(act_ko5)
assert not done
assert reward == 0
def test_alarm_reward_simple(self):
"""very basic test for the reward and"""
# normal step, no game over => 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert reward == 0
self.env.fast_forward_chronics(861)
obs, reward, done, info = self.env.step(self.env.action_space())
assert not done
assert reward == 0
# end of an episode, no game over: +1
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == +1
assert not obs.was_alarm_used_after_game_over
def test_reward_game_over_connex(self):
"""test i don't get any points if there is a game over for non connex grid"""
# game over not due to line disconnection, no points
obs = self.env.reset()
act_ko = self.env.action_space()
act_ko.gen_set_bus = [(0, -1)]
obs, reward, done, info = self.env.step(act_ko)
assert done
assert reward == -1
assert not obs.was_alarm_used_after_game_over
def test_reward_no_alarm(self):
"""test that i don't get any points if i don't send any alarm"""
# FYI parrallel lines:
# 48, 49 || 18, 19 || 27, 28 || 37, 38
# game not due to line disconnection, but no alarm => no points
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == -1
assert not obs.was_alarm_used_after_game_over
def test_reward_wrong_area_wrong_time(self):
"""test that i got a few point for the wrong area, but at the wrong time"""
# now i raise an alarm, and after i do a cascading failure (but i send a wrong alarm)
act = self.env.action_space()
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 0.375
assert obs.was_alarm_used_after_game_over
def test_reward_right_area_not_best_time(self):
"""test that i got some point for the right area, but at the wrong time"""
# now i raise an alarm, and after i do a cascading failure (and i send a right alarm)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 0.75
assert obs.was_alarm_used_after_game_over
def test_reward_right_time_wrong_area(self):
"""test that the alarm has half "value" if taken exactly at the right time but for the wrong area"""
# now i raise an alarm just at the right time, and after i do a cascading failure (wrong zone)
act = self.env.action_space()
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 0.5
assert obs.was_alarm_used_after_game_over
def test_reward_right_time_right_area(self):
"""test that the alarm has perfect "value" if taken exactly at the right time and for the right area"""
# now i raise an alarm just at the right time, and after i do a cascading failure (right zone)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1
assert obs.was_alarm_used_after_game_over
def test_reward_right_area_too_early(self):
"""test that the alarm is not taken into account if send too early"""
# now i raise an alarm but too early, i don't get any points (even if right zone)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
for _ in range(12):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == -1
assert not obs.was_alarm_used_after_game_over
def test_reward_correct_alarmused_right_early(self):
"""test that the maximum is taken, when an alarm is send at the right time, and another one too early"""
# now i raise two alarms: one at just the right time, another one a bit earlier, and i check the correct
# one is used
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act) # a bit too early
for _ in range(3):
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(
self.env.action_space()
) # just at the right time
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1.0 # it should count this one
assert obs.was_alarm_used_after_game_over
def test_reward_correct_alarmused_right_toolate(self):
"""test that the maximum is taken, when an alarm is send at the right time, and another one too late"""
# now i raise two alarms: one at just the right time, another one a bit later, and i check the correct
# one is used
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act) # just at the right time
for _ in range(3):
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(act) # a bit too early
for _ in range(2):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1.0 # it should count this one
assert obs.was_alarm_used_after_game_over
def test_runner(self):
"""test i can create properly a runner"""
runner = Runner(**self.env.get_params_for_runner())
# normal run
res = runner.run(nb_episode=1, nb_process=1, max_iter=self.max_iter)
assert res[0][-1] == 10
assert res[0][-2] == 10
assert res[0][-3] == 1.0
# run + episode data
with tempfile.TemporaryDirectory() as f:
res = runner.run(
nb_episode=1, nb_process=1, max_iter=self.max_iter, path_save=f
)
ep_dat = EpisodeData.from_disk(agent_path=f, name=res[0][1])
assert len(ep_dat) == 10
assert ep_dat.observations[0].attention_budget == 3
assert ep_dat.observations[1].attention_budget == 3 + 1.0 / (12.0 * 8.0)
def test_kwargs(self):
"""test the get_kwargs function properly foward the attention budget"""
env2 = Environment(**self.env.get_kwargs())
assert env2._has_attention_budget
assert env2._kwargs_attention_budget == self.default_kwargs_att_budget
assert env2._attention_budget_cls == LinearAttentionBudget
obs = env2.reset()
assert obs.attention_budget == 3
obs, reward, done, info = env2.step(env2.action_space())
assert obs.attention_budget == 3 + 1.0 / (12.0 * 8.0)
def test_simulate(self):
"""issue reported during icaps 2021"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_icaps_2021", test=True, reward_class=_AlarmScore)
env.set_thermal_limit(
[
20,
70,
36.049267,
43.361996,
407.20905,
42.96296,
23.125486,
7.005345,
61.224003,
18.283638,
20.992632,
89.384026,
117.01148,
62.883495,
44.568665,
29.756845,
14.604381,
28.99635,
124.59952,
124.59952,
38.46957,
48.00529,
112.23501,
139.56854,
57.25149,
35.785202,
31.468952,
98.922386,
97.78254,
10.58541,
7.2501163,
34.89438,
66.21333,
89.454895,
40.088715,
59.50673,
54.07072,
47.005745,
49.29639,
60.19898,
98.318146,
110.93459,
178.60854,
48.504723,
9.022086,
197.42432,
174.3434,
295.6653,
149.95523,
149.95523,
50.128273,
31.93147,
74.32939,
54.26264,
41.730865,
238.96637,
197.42432,
113.98372,
413.98587,
]
)
env.seed(0)
_ = env.reset()
# it crashed
obs, *_ = env.step(env.action_space())
obs, *_ = env.step(env.action_space())
alarm_act = env.action_space()
alarm_act.raise_alarm = [0]
obs, reward, done, info = env.step(alarm_act)
assert not done
# next step there is a game over due to
sim_obs, sim_r, sim_done, sim_info = obs.simulate(env.action_space())
assert sim_done
if __name__ == "__main__":
unittest.main()
| 22,709 | 39.698925 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_AlarmScore.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import unittest
import os
import tempfile
from grid2op.tests.helper_path_test import *
from grid2op.Parameters import Parameters
from grid2op.operator_attention import LinearAttentionBudget
from grid2op import make
from grid2op.Reward import RedispReward, _AlarmScore
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner
from grid2op.Environment import Environment
from grid2op.Episode import EpisodeData
class TestAlarmScore(unittest.TestCase):
"""test the basic bahavior of the alarm feature"""
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
self.env_nm, test=True, reward_class=_AlarmScore
) # ,param=param)
self.env.seed(0)
self.env.reset()
self.env.reset()
self.max_iter = 10
self.default_kwargs_att_budget = {
"max_budget": 3.0,
"budget_per_ts": 1.0 / (12.0 * 16),
"alarm_cost": 1.0,
"init_budget": 2.0,
}
def _aux_trigger_cascading_failure(self):
act_ko1 = self.env.action_space()
act_ko1.line_set_status = [(56, -1)]
obs, reward, done, info = self.env.step(act_ko1)
assert not done
assert reward == 0
act_ko2 = self.env.action_space()
act_ko2.line_set_status = [(41, -1)]
obs, reward, done, info = self.env.step(act_ko2)
assert not done
assert reward == 0
act_ko3 = self.env.action_space()
act_ko3.line_set_status = [(40, -1)]
obs, reward, done, info = self.env.step(act_ko3)
assert not done
assert reward == 0
act_ko4 = self.env.action_space()
act_ko4.line_set_status = [(39, -1)]
obs, reward, done, info = self.env.step(act_ko4)
assert not done
assert reward == 0
act_ko5 = self.env.action_space()
act_ko5.line_set_status = [(13, -1)]
obs, reward, done, info = self.env.step(act_ko5)
assert not done
assert reward == 0
def test_alarm_reward_simple(self):
"""very basic test for the reward and"""
# normal step, no game over => 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert reward == 0
self.env.fast_forward_chronics(861)
obs, reward, done, info = self.env.step(self.env.action_space())
assert not done
assert reward == 0
# end of an episode, no game over: +1
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == +1
assert not obs.was_alarm_used_after_game_over
def test_reward_game_over_connex(self):
"""test i don't get any points if there is a game over for non connex grid"""
# game over not due to line disconnection, no points
obs = self.env.reset()
act_ko = self.env.action_space()
act_ko.gen_set_bus = [(0, -1)]
obs, reward, done, info = self.env.step(act_ko)
assert done
assert reward == -2
assert not obs.was_alarm_used_after_game_over
def test_reward_no_alarm(self):
"""test that i don't get any points if i don't send any alarm"""
# FYI parrallel lines:
# 48, 49 || 18, 19 || 27, 28 || 37, 38
# game not due to line disconnection, but no alarm => no points
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == -2
assert not obs.was_alarm_used_after_game_over
def test_reward_wrong_area_wrong_time(self):
"""test that i got a few point for the wrong area, but at the wrong time"""
# now i raise an alarm, and after i do a cascading failure (but i send a wrong alarm)
act = self.env.action_space()
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert (
reward == 0.5
) # different from AlarmReward because mult_for_right_zone is lower here, 1.5 instead of 2
assert obs.was_alarm_used_after_game_over
def test_reward_right_area_not_best_time(self):
"""test that i got some point for the right area, but at the wrong time"""
# now i raise an alarm, and after i do a cascading failure (and i send a right alarm)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 0.75
assert obs.was_alarm_used_after_game_over
def test_reward_right_time_wrong_area(self):
"""test that the alarm has half "value" if taken exactly at the right time but for the wrong area"""
# now i raise an alarm just at the right time, and after i do a cascading failure (wrong zone)
act = self.env.action_space()
act.raise_alarm = [0]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert (
reward == 2 / 3
) # different from AlarmReward because mult_for_right_zone is lower here, 1.5 instead of 2
assert obs.was_alarm_used_after_game_over
def test_reward_right_time_right_area(self):
"""test that the alarm has perfect "value" if taken exactly at the right time and for the right area"""
# now i raise an alarm just at the right time, and after i do a cascading failure (right zone)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1
assert obs.was_alarm_used_after_game_over
def test_reward_right_area_too_early(self):
"""test that the alarm is not taken into account if send too early"""
# now i raise an alarm but too early, i don't get any points (even if right zone)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(self.env.action_space())
for _ in range(12):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == -2
assert not obs.was_alarm_used_after_game_over
def test_reward_correct_alarmused_right_early(self):
"""test that the maximum is taken, when an alarm is send at the right time, and another one too early"""
# now i raise two alarms: one at just the right time, another one a bit earlier, and i check the correct
# one is used
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act) # a bit too early
for _ in range(3):
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(act)
for _ in range(6):
obs, reward, done, info = self.env.step(
self.env.action_space()
) # just at the right time
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1.0 # it should count this one
assert obs.was_alarm_used_after_game_over
def test_reward_correct_alarmused_right_toolate(self):
"""test that the maximum is taken, when an alarm is send at the right time, and another one too late"""
# now i raise two alarms: one at just the right time, another one a bit later, and i check the correct
# one is used
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act) # just at the right time
for _ in range(3):
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(act) # a bit too early
for _ in range(2):
obs, reward, done, info = self.env.step(self.env.action_space())
self._aux_trigger_cascading_failure()
obs, reward, done, info = self.env.step(self.env.action_space())
assert done
assert reward == 1.0 # it should count this one
assert obs.was_alarm_used_after_game_over
def _is_cascade_in_zone_alarm(self, disc_lines_in_cascade, zone_alarm):
is_cascade_in_zone_alarm = False
for line_id in disc_lines_in_cascade:
zones_line = self.env.alarms_lines_area[self.env.name_line[line_id]]
if zone_alarm in zones_line:
is_cascade_in_zone_alarm = True
break
return is_cascade_in_zone_alarm
def test_reward_correct_alarm_only_cascade_right_zone(self):
"""test that the maximum is taken, when an alarm is send at the right time with only lines got diconnected at
the time of cascading failure"""
# changing parameters to allow for multiple line actions in order to create a cascading failure in one time_step
param = Parameters()
param.init_from_dict({"MAX_LINE_STATUS_CHANGED": 999})
self.env.change_parameters(param)
self.env.reset() # env.reset() to reset the parameters. Note that we also jump to a new scenario by doing
# env.reset(), which is desired here
act = self.env.action_space()
alarm_zone_id = 1 # right zone
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
act.raise_alarm = [alarm_zone_id]
disc_lines_before_cascade = []
obs, reward, done, info = self.env.step(act) # just at the right time
assert (
len(list(np.where(info["disc_lines"] == 0)[0])) == 0
) # no line disconnected before cascade
for _ in range(11):
obs, reward, done, info = self.env.step(self.env.action_space())
assert len(list(np.where(info["disc_lines"] == 0)[0])) == 0
# cascading failure in one step
act = self.env.action_space(
{"set_line_status": [(56, -1), (41, -1), (40, -1), (39, -1), (13, -1)]}
)
obs, reward, done, info = self.env.step(act)
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
assert self._is_cascade_in_zone_alarm(disc_lines_in_cascade, zone_alarm)
assert done
assert reward == 1.0 # get the max points because cascade linees in right zone
assert obs.was_alarm_used_after_game_over
def test_reward_correct_alarm_only_cascade_bad_zone(self):
"""test that the geo points are not taken, when an alarm is send at the right time, but lines only got
diconnected at the time of cascading failure in a bad zone"""
param = Parameters()
param.init_from_dict({"MAX_LINE_STATUS_CHANGED": 999})
self.env.change_parameters(param)
self.env.reset() # env.reset() to reset the parameters. Note that we also jump to a new scenario by doing
# env.reset(), which is desired here
act = self.env.action_space()
alarm_zone_id = 0 # wrong zone
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(act) # just at the right time
assert (
len(list(np.where(info["disc_lines"] == 0)[0])) == 0
) # no line disconnected before cascade
for _ in range(11):
obs, reward, done, info = self.env.step(self.env.action_space())
assert len(list(np.where(info["disc_lines"] == 0)[0])) == 0
# cascading failure in one step
act = self.env.action_space(
{"set_line_status": [(56, -1), (41, -1), (40, -1), (39, -1), (13, -1)]}
)
obs, reward, done, info = self.env.step(act)
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
assert not self._is_cascade_in_zone_alarm(disc_lines_in_cascade, zone_alarm)
assert done
assert reward == 1 / 1.5 # get the max time points but not geo points
assert obs.was_alarm_used_after_game_over
def test_alarm_reward_linedisconnection_in_window_right_time_bad_zone(self):
"""test that the geo points are not taken, when an alarm is send at the right time, and lines get
diconnected in the disconnection window before the time of cascading failure, but in a bad zone"""
# will fail at timestep 13, perfect time.
# line disconnected before cascading failure are in zone 2. During cascade we also get line disconnected in the alarm zone 1
# we should not get geo_points in the end
# dis_lines_before_cascade=[[], [], [45], [], [], [41], [], [], [40], [], []] => only line 40 should be consider for points here
# disc_lines_in_cascade= [13, 22, 23, 31, 32, 33, 34, 35, 39]
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
alarm_zone_id = 1
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
obs, reward, done, info = self.env.step(act)
if not done:
disc_lines_before_cascade.append(
list(np.where(info["disc_lines"] == 0)[0])
)
else:
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
t += 1
assert self._is_cascade_in_zone_alarm(
disc_lines_in_cascade, zone_alarm
) # a line was during the cascade disconnected in the alamr zone.
# But it is not the zone in which the first line we considered disconnected. So will not give points
assert reward == 1 / 1.5 # get points for perfect time but not for zone
def test_alarm_reward_linedisconnection_in_window_right_time_good_zone(self):
"""test that the geo points are taken, when an alarm is send at the right time, and lines get
diconnected in the disconnection window before the time of cascading failure, but in a good zone"""
# will fail at timestep 13, perfect time.
# line disconnected before cascading failure are in zone 2.
# we should get geo_points in the end
# dis_lines_before_cascade=[[], [], [45], [], [], [41], [], [], [40], [], []] => only line 40 should be consider for points here
# disc_lines_in_cascade= [13, 22, 23, 31, 32, 33, 34, 35, 39]
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
alarm_zone_id = 2
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
obs, reward, done, info = self.env.step(act)
if not done:
disc_lines_before_cascade.append(
list(np.where(info["disc_lines"] == 0)[0])
)
else:
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
t += 1
assert reward == 1 # get points for perfect time and zone
def test_alarm_reward_linedisconnection_before_window_right_time_good_zone(self):
"""test that the geo points are taken, when an alarm is send at the right time, and lines get
diconnected before the disconnection window + lines disconnected at cascading failure are in a good zone"""
# will fail at timestep 13, perfect time.
# line disconnected before cascading failure are in zone 2. During cascade we also don't get line disconnected in the alarm zone 1
# we should not get geo_points in the end
# dis_lines_before_cascade=[[], [], [45], [], [], [41], [], [], [], [], []] => only line 40 should be consider for points here
# disc_lines_in_cascade= [13, 22, 23, 31, 32, 33, 34, 35, 39]
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
alarm_zone_id = 1
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
if (
t == 9
): # disconnecting the line ourself so that it does not appear in disc_lines
# in the window_disconnection
act = self.env.action_space({"set_line_status": [(40, -1)]})
obs, reward, done, info = self.env.step(act)
if not done:
disc_lines_before_cascade.append(
list(np.where(info["disc_lines"] == 0)[0])
)
else:
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
t += 1
assert self._is_cascade_in_zone_alarm(
disc_lines_in_cascade, zone_alarm
) # a line was during the cascade disconnected in the alamr zone.
assert reward == 1 # get points for perfect time but not for zone
def test_alarm_reward_linedisconnection_in_window_right_time_bad_zone(self):
"""test that the geo points are taken, when an alarm is send at the right time, and lines get
diconnected before the disconnection window + lines disconnected at cascading failure are in a good zone"""
# line disconnected before cascading failure are in zone 2. But during cascade we get line disconnected in zone 1
# we should not get geo_points
# dis_lines_before_cascade=[[], [], [45], [], [], [41], [], [], [40], [], []] => only line 40 should be consider for points here
# disc_lines_in_cascade= [13, 22, 23, 31, 32, 33, 34, 35, 39]
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
act.raise_alarm = [1]
obs, reward, done, info = self.env.step(act) # just at the right time
t = 1
while not done:
act = self.env.action_space()
obs, reward, done, info = self.env.step(act)
t += 1
assert reward == 1 / 1.5 # get points for perfect time but not for zone
def test_alarm_reward_no_point_factor_multi_zone(self):
"""test that the geo points are not taken, when an alarm is send on multi zones"""
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
act.raise_alarm = [0, 1]
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
obs, reward, done, info = self.env.step(act)
t += 1
# But it is not the zone in which the first line we considered disconnected. So will not give points
assert reward == 1 / 1.5 # get points for perfect time but not for zone
# zero if dics
def test_alarm_after_line_diconnection_score_low(self):
"""test that the score is low when an alarm is sent at the time of an observed line disconnection
at the beginning of disconnection window"""
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
alarm_zone_id = 1
zone_alarm = self.env.alarms_area_names[alarm_zone_id]
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
if (
t == 9
): # right at the time of line disconnection in window_disconnection
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(act)
t += 1
assert np.round(reward, 2) == 0.29 # get points for perfect zone but not time
def test_alarm_after_line_diconnection_score_low_2(self):
"""test that the score is low for another alarm_best_time and alarm_window_size
when an alarm is sent at the time of an observed line disconnection
at the beginning of disconnection window"""
# changing alarm time parameters
param = self.env.parameters
param.init_from_dict({"ALARM_WINDOW_SIZE": 5, "ALARM_BEST_TIME": 7})
self.env.change_parameters(param)
self.env.reset() # env.reset() to reset the parameters. Note that this also jump to the next scenario.
self.env.reset() # we do one more env.reset() to jump back to our initial scenario among the two we have
###
# changing thermal limits to create an overload since the beginning and a slow cascading failure
new_thermal_limit = self.env.get_thermal_limit()
line_id = 45
new_thermal_limit[line_id] = new_thermal_limit[line_id] / 3
self.env.set_thermal_limit(new_thermal_limit)
act = self.env.action_space()
alarm_zone_id = 1
obs, reward, done, info = self.env.step(
act
) # first step and an overload occur on our line 45
t = 1
disc_lines_before_cascade = []
while not done: # will fail at timestep 13
act = self.env.action_space()
if (
t == 9
): # right at the time of line disconnection in window_disconnection
act.raise_alarm = [alarm_zone_id]
obs, reward, done, info = self.env.step(act)
if not done:
disc_lines_before_cascade.append(
list(np.where(info["disc_lines"] == 0)[0])
)
else:
disc_lines_in_cascade = list(np.where(info["disc_lines"] == 0)[0])
t += 1
assert np.round(reward, 2) == 0.24
| 25,596 | 43.828371 | 138 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_BackendAction.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
# do some generic tests that can be implemented directly to test if a backend implementation can work out of the box
# with grid2op.
# see an example of test_Pandapower for how to use this suit.
import unittest
import numpy as np
import warnings
import grid2op
from grid2op.Runner import Runner
from grid2op.Agent import RandomAgent, DoNothingAgent
from grid2op.Backend import PandaPowerBackend
import pdb
class TestSuitePandaPowerBackend(PandaPowerBackend):
"""Only work for the case 14 !!!"""
def __init__(self, detailed_infos_for_cascading_failures=False,
can_be_copied=True,
**kwargs):
PandaPowerBackend.__init__(
self,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
can_be_copied=can_be_copied,
**kwargs
)
# just for the test
self._nb_bus_before_for_test = 14
self._nb_line_for_test = 15
def apply_action(self, backendAction=None):
# to test the get_loads_bus, get_gen_bus, etc. function
if backendAction is None:
return
# TODO
(
active_bus,
(prod_p, prod_v, load_p, load_q, storage),
_,
shunts__,
) = backendAction()
tmp_prod_p = self._get_vector_inj["prod_p"](self._grid)
if np.any(prod_p.changed):
tmp_prod_p.iloc[prod_p.changed] = prod_p.values[prod_p.changed]
tmp_prod_v = self._get_vector_inj["prod_v"](self._grid)
if np.any(prod_v.changed):
tmp_prod_v.iloc[prod_v.changed] = (
prod_v.values[prod_v.changed] / self.prod_pu_to_kv[prod_v.changed]
)
if self._id_bus_added is not None and prod_v.changed[self._id_bus_added]:
# handling of the slack bus, where "2" generators are present.
self._grid["ext_grid"]["vm_pu"] = 1.0 * tmp_prod_v[self._id_bus_added]
tmp_load_p = self._get_vector_inj["load_p"](self._grid)
if np.any(load_p.changed):
tmp_load_p.iloc[load_p.changed] = load_p.values[load_p.changed]
tmp_load_q = self._get_vector_inj["load_q"](self._grid)
if np.any(load_q.changed):
tmp_load_q.iloc[load_q.changed] = load_q.values[load_q.changed]
if self.shunts_data_available:
shunt_p, shunt_q, shunt_bus = shunts__
if np.any(shunt_p.changed):
self._grid.shunt["p_mw"].iloc[shunt_p.changed] = shunt_p.values[
shunt_p.changed
]
if np.any(shunt_q.changed):
self._grid.shunt["q_mvar"].iloc[shunt_q.changed] = shunt_q.values[
shunt_q.changed
]
if np.any(shunt_bus.changed):
sh_service = shunt_bus.values[shunt_bus.changed] != -1
self._grid.shunt["in_service"].iloc[shunt_bus.changed] = sh_service
sh_bus1 = np.arange(len(shunt_bus))[
shunt_bus.changed & shunt_bus.values == 1
]
sh_bus2 = np.arange(len(shunt_bus))[
shunt_bus.changed & shunt_bus.values == 2
]
if len(sh_bus1) > 0:
self._grid.shunt["bus"][sh_bus1] = self.shunt_to_subid[sh_bus1]
if len(sh_bus2) > 0:
self._grid.shunt["bus"][sh_bus2] = (
self.shunt_to_subid[sh_bus2] + self._nb_bus_before_for_test
)
# i made at least a real change, so i implement it in the backend
loads_bus = backendAction.get_loads_bus()
for load_id, new_bus in loads_bus:
if new_bus == -1:
self._grid.load["in_service"][load_id] = False
else:
self._grid.load["in_service"][load_id] = True
self._grid.load["bus"][load_id] = (
self.load_to_subid[load_id]
+ (new_bus - 1) * self._nb_bus_before_for_test
)
gens_bus = backendAction.get_gens_bus()
for gen_id, new_bus in gens_bus:
if new_bus == -1:
self._grid.gen["in_service"][gen_id] = False
else:
self._grid.gen["in_service"][gen_id] = True
self._grid.gen["bus"][gen_id] = (
self.gen_to_subid[gen_id]
+ (new_bus - 1) * self._nb_bus_before_for_test
)
if (
gen_id == (self._grid.gen.shape[0] - 1)
and self._iref_slack is not None
):
self._grid.ext_grid["bus"].iat[0] = (
self.gen_to_subid[gen_id]
+ (new_bus - 1) * self._nb_bus_before_for_test
)
lines_or_bus = backendAction.get_lines_or_bus()
for line_id, new_bus in lines_or_bus:
if line_id < self._nb_line_for_test:
dt = self._grid.line
key = "from_bus"
line_id_db = line_id
else:
dt = self._grid.trafo
key = "hv_bus"
line_id_db = line_id - self._nb_line_for_test
if new_bus == -1:
dt["in_service"][line_id_db] = False
else:
dt["in_service"][line_id_db] = True
dt[key][line_id_db] = (
self.line_or_to_subid[line_id]
+ (new_bus - 1) * self._nb_bus_before_for_test
)
lines_ex_bus = backendAction.get_lines_ex_bus()
for line_id, new_bus in lines_ex_bus:
if line_id < self._nb_line_for_test:
dt = self._grid.line
key = "to_bus"
line_id_db = line_id
else:
dt = self._grid.trafo
key = "lv_bus"
line_id_db = line_id - self._nb_line_for_test
if new_bus == -1:
dt["in_service"][line_id_db] = False
else:
dt["in_service"][line_id_db] = True
dt[key][line_id_db] = (
self.line_ex_to_subid[line_id]
+ (new_bus - 1) * self._nb_bus_before_for_test
)
bus_is = self._grid.bus["in_service"]
for i, (bus1_status, bus2_status) in enumerate(active_bus):
bus_is[i] = bus1_status # no iloc for bus, don't ask me why please :-/
bus_is[i + self._nb_bus_before_for_test] = bus2_status
class TestXXXBus(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.envtest = grid2op.make(
"rte_case14_realistic",
test=True,
backend=TestSuitePandaPowerBackend(),
_add_to_name="test_get_xxx_bus_test",
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.envref = grid2op.make(
"rte_case14_realistic",
test=True,
_add_to_name="test_get_xxx_bus_ref"
)
seed = 0
self.nb_test = 10
self.max_iter = 30
self.envref.seed(seed)
self.envtest.seed(seed)
self.seeds = [
i for i in range(self.nb_test)
] # used for seeding environment and agent
def tearDown(self) -> None:
self.envref.close()
self.envtest.close()
def test_get_load_bus(self):
"""
test the methods get_load_bus works
"""
act_load = self.envref.action_space(
{"set_bus": {"loads_id": [(0, 2)], "lines_or_id": [(2, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_load)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_load)
assert not done_ref
assert obs_test.topo_vect[self.envtest.load_pos_topo_vect[0]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
def test_tricky_action(self):
"""
do an action on the generator where the slack bus is, it "broke" the "code" i used for testing
(TestSuitePandaPowerBackend)
"""
act_load = self.envref.action_space(
{"set_bus": {"generators_id": [(4, 2)], "lines_or_id": [(0, 2), (1, 1)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_load)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_load)
assert not done_ref
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
def test_get_gen_bus(self):
"""
test the methods get_gen_bus works
"""
act_gen = self.envref.action_space(
{"set_bus": {"generators_id": [(0, 2)], "lines_or_id": [(2, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_gen)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_gen)
assert not done_ref
assert obs_test.topo_vect[self.envtest.gen_pos_topo_vect[0]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
def test_get_line_or_bus(self):
"""
test the methods get_line_or_bus works (for line and transformer)
"""
act_gen = self.envref.action_space(
{"set_bus": {"generators_id": [(0, 2)], "lines_or_id": [(2, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_gen)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_gen)
assert not done_ref
assert obs_test.topo_vect[self.envtest.line_or_pos_topo_vect[2]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
# for trafo
self.envref.reset()
self.envtest.reset()
act_gen = self.envref.action_space(
{"set_bus": {"lines_ex_id": [(3, 2)], "lines_or_id": [(16, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_gen)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_gen)
assert not done_ref
assert obs_test.topo_vect[self.envtest.line_or_pos_topo_vect[16]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
def test_get_line_ex_bus(self):
"""
test the methods get_line_or_bus works (for line and transformer)
"""
act_gen = self.envref.action_space(
{"set_bus": {"lines_ex_id": [(0, 2)], "lines_or_id": [(2, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_gen)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_gen)
assert not done_ref
assert obs_test.topo_vect[self.envtest.line_ex_pos_topo_vect[0]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
# for trafo
self.envref.reset()
self.envtest.reset()
act_gen = self.envref.action_space(
{"set_bus": {"lines_ex_id": [(16, 2)], "lines_or_id": [(10, 2)]}}
)
obs_ref, reward_ref, done_ref, info_ref = self.envref.step(act_gen)
obs_test, reward_test, done_test, info_test = self.envtest.step(act_gen)
assert not done_ref
assert obs_test.topo_vect[self.envtest.line_ex_pos_topo_vect[16]] == 2
assert obs_ref == obs_test
assert reward_ref == reward_test
assert done_ref == done_test
def test_get_xxx_bus_dn(self):
"""
test the methods get_load_bus, get_gen_bus, get_lines_or_bus and get_lines_ex_bus works with do
nothing agent (more examples)
"""
runner_ref = Runner(
**self.envref.get_params_for_runner(), agentClass=DoNothingAgent
)
runner_test = Runner(
**self.envtest.get_params_for_runner(), agentClass=DoNothingAgent
)
res_ref = runner_ref.run(
nb_episode=self.nb_test,
max_iter=self.max_iter,
agent_seeds=self.seeds,
env_seeds=self.seeds,
)
res_test = runner_test.run(
nb_episode=self.nb_test,
max_iter=self.max_iter,
agent_seeds=self.seeds,
env_seeds=self.seeds,
)
assert res_ref == res_test
def test_get_xxx_bus_random(self):
"""
test the methods get_load_bus, get_gen_bus, get_lines_or_bus and get_lines_ex_bus works with random
agent (more tests)
"""
runner_ref = Runner(
**self.envref.get_params_for_runner(), agentClass=RandomAgent
)
runner_test = Runner(
**self.envtest.get_params_for_runner(), agentClass=RandomAgent
)
res_ref = runner_ref.run(
nb_episode=self.nb_test,
max_iter=self.max_iter,
agent_seeds=self.seeds,
env_seeds=self.seeds,
)
res_test = runner_test.run(
nb_episode=self.nb_test,
max_iter=self.max_iter,
agent_seeds=self.seeds,
env_seeds=self.seeds,
)
assert res_ref == res_test
if __name__ == "__main__":
unittest.main()
| 14,093 | 36.584 | 116 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_BackendConverter.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
from grid2op.Converter import BackendConverter
from grid2op.tests.helper_path_test import *
from grid2op import make
from grid2op.tests.helper_path_test import PATH_DATA_TEST_PP, PATH_DATA_TEST
from grid2op.Backend import PandaPowerBackend
from grid2op.tests.helper_path_test import HelperTests
from grid2op.tests.BaseBackendTest import BaseTestNames
from grid2op.tests.BaseBackendTest import BaseTestLoadingCase
from grid2op.tests.BaseBackendTest import BaseTestLoadingBackendFunc
from grid2op.tests.BaseBackendTest import BaseTestTopoAction
from grid2op.tests.BaseBackendTest import BaseTestEnvPerformsCorrectCascadingFailures
from grid2op.tests.BaseBackendTest import BaseTestChangeBusAffectRightBus
from grid2op.tests.BaseBackendTest import BaseTestShuntAction
from grid2op.tests.BaseBackendTest import BaseTestResetEqualsLoadGrid
from grid2op.tests.BaseBackendTest import BaseTestVoltageOWhenDisco
from grid2op.tests.BaseBackendTest import BaseTestChangeBusSlack
from grid2op.tests.BaseBackendTest import BaseIssuesTest
from grid2op.tests.BaseBackendTest import BaseStatusActions
PATH_DATA_TEST_INIT = PATH_DATA_TEST
PATH_DATA_TEST = PATH_DATA_TEST_PP
BKclass1 = PandaPowerBackend
BKclass2 = PandaPowerBackend
import warnings
warnings.simplefilter("error")
class TestLoading(HelperTests):
def test_init(self):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_realistic", test=True, backend=backend)
class TestNames(HelperTests, BaseTestNames):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
def get_path(self):
return PATH_DATA_TEST_INIT
class TestLoadingCase(HelperTests, BaseTestLoadingCase):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestLoadingBackendFunc(HelperTests, BaseTestLoadingBackendFunc):
def setUp(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestTopoAction(HelperTests, BaseTestTopoAction):
def setUp(self):
BaseTestTopoAction.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestTopoAction.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestEnvPerformsCorrectCascadingFailures(
HelperTests, BaseTestEnvPerformsCorrectCascadingFailures
):
def setUp(self):
BaseTestEnvPerformsCorrectCascadingFailures.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestEnvPerformsCorrectCascadingFailures.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
def get_casefile(self):
return "test_case14.json"
def get_path(self):
return PATH_DATA_TEST
class TestChangeBusAffectRightBus(HelperTests, BaseTestChangeBusAffectRightBus):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestShuntAction(HelperTests, BaseTestShuntAction):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestResetEqualsLoadGrid(HelperTests, BaseTestResetEqualsLoadGrid):
def setUp(self):
BaseTestResetEqualsLoadGrid.setUp(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestVoltageOWhenDisco(HelperTests, BaseTestVoltageOWhenDisco):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestChangeBusSlack(HelperTests, BaseTestChangeBusSlack):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestIssuesTest(HelperTests, BaseIssuesTest):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
class TestStatusAction(HelperTests, BaseStatusActions):
def make_backend(self, detailed_infos_for_cascading_failures=False):
backend = BackendConverter(
source_backend_class=BKclass1,
target_backend_class=BKclass2,
target_backend_grid_path=None,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
return backend
if __name__ == "__main__":
unittest.main()
| 8,548 | 34.326446 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_ChronicsHandler.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import pandas as pd
import tempfile
import re
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.dtypes import dt_int, dt_float
from grid2op.MakeEnv import make
from grid2op.Exceptions import *
from grid2op.Chronics import (
ChronicsHandler,
GridStateFromFile,
GridStateFromFileWithForecasts,
Multifolder,
GridValue,
)
from grid2op.Chronics import MultifolderWithCache
from grid2op.Backend import PandaPowerBackend
from grid2op.Parameters import Parameters
from grid2op.Rules import AlwaysLegal
from grid2op.Chronics import GridStateFromFileWithForecastsWithoutMaintenance
from grid2op.Runner import Runner
import warnings
warnings.simplefilter("error")
class TestProperHandlingHazardsMaintenance(HelperTests):
def setUp(self):
self.path_hazard = os.path.join(PATH_CHRONICS, "chronics_with_hazards")
self.path_maintenance = os.path.join(PATH_CHRONICS, "chronics_with_maintenance")
self.n_gen = 5
self.n_load = 11
self.n_lines = 20
self.order_backend_loads = [
"2_C-10.61",
"3_C151.15",
"4_C-9.47",
"5_C201.84",
"6_C-6.27",
"9_C130.49",
"10_C228.66",
"11_C-138.89",
"12_C-27.88",
"13_C-13.33",
"14_C63.6",
]
self.order_backend_prods = [
"1_G137.1",
"2_G-56.47",
"3_G36.31",
"6_G63.29",
"8_G40.43",
]
self.order_backend_lines = [
"1_2_1",
"1_5_2",
"2_3_3",
"2_4_4",
"2_5_5",
"3_4_6",
"4_5_7",
"4_7_8",
"4_9_9",
"5_6_10",
"6_11_11",
"6_12_12",
"6_13_13",
"7_8_14",
"7_9_15",
"9_10_16",
"9_14_17",
"10_11_18",
"12_13_19",
"13_14_20",
]
self.order_backend_subs = [
"bus_1",
"bus_2",
"bus_3",
"bus_4",
"bus_5",
"bus_6",
"bus_7",
"bus_8",
"bus_9",
"bus_10",
"bus_11",
"bus_12",
"bus_13",
"bus_14",
]
def test_get_maintenance_time_1d(self):
maintenance_time = GridValue.get_maintenance_time_1d(
np.array([0 for _ in range(10)])
)
assert np.all(maintenance_time == np.array([-1 for _ in range(10)]))
maintenance = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
maintenance_time = GridValue.get_maintenance_time_1d(maintenance)
assert np.all(
maintenance_time
== np.array([5, 4, 3, 2, 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1])
)
maintenance = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0])
maintenance_time = GridValue.get_maintenance_time_1d(maintenance)
assert np.all(
maintenance_time
== np.array([5, 4, 3, 2, 1, 0, 0, 0, 4, 3, 2, 1, 0, 0, -1, -1, -1])
)
maintenance = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
maintenance_duration = GridValue.get_maintenance_time_1d(maintenance)
assert np.all(
maintenance_duration
== np.array([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0])
)
def test_get_maintenance_duration_1d(self):
maintenance = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
maintenance_duration = GridValue.get_maintenance_duration_1d(maintenance)
assert np.all(
maintenance_duration
== np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
)
maintenance = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
maintenance_duration = GridValue.get_maintenance_duration_1d(maintenance)
assert np.all(
maintenance_duration
== np.array([3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0])
)
maintenance = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0])
maintenance_duration = GridValue.get_maintenance_duration_1d(maintenance)
assert np.all(
maintenance_duration
== np.array([3, 3, 3, 3, 3, 3, 2, 1, 2, 2, 2, 2, 2, 1, 0, 0, 0])
)
maintenance = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
maintenance_duration = GridValue.get_maintenance_duration_1d(maintenance)
assert np.all(
maintenance_duration
== np.array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1])
)
def test_get_hazard_duration_1d(self):
hazard = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
hazard_duration = GridValue.get_hazard_duration_1d(hazard)
assert np.all(
hazard_duration
== np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
)
hazard = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
hazard_duration = GridValue.get_hazard_duration_1d(hazard)
assert np.all(
hazard_duration
== np.array([0, 0, 0, 0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0])
)
hazard = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0])
hazard_duration = GridValue.get_hazard_duration_1d(hazard)
assert np.all(
hazard_duration
== np.array([0, 0, 0, 0, 0, 3, 2, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0])
)
hazard = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
hazard_duration = GridValue.get_hazard_duration_1d(hazard)
assert np.all(
hazard_duration
== np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 3, 2, 1])
)
def test_loadchornics_hazard_ok(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path_hazard
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.all(hazard_duration == 0)
for i in range(12):
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.sum(hazard_duration == 0) == 19
assert hazard_duration[17] == 12 - i, "error at iteration {}".format(i)
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.all(hazard_duration == 0)
def test_loadchornics_maintenance_ok(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path_maintenance
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.sum(maintenance_duration == 0) == 18
assert (
maintenance_duration[17] == 12
), "incorrect duration of maintenance on powerline 17"
assert (
maintenance_duration[19] == 12
), "incorrect duration of maintenance on powerline 19"
assert np.sum(maintenance_time == -1) == 18
assert (
maintenance_time[17] == 1
), "incorrect time for next maintenance on powerline 17"
assert (
maintenance_time[19] == 276
), "incorrect time for next maintenance on powerline 19"
for i in range(12):
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.sum(maintenance_duration == 0) == 18
assert int(maintenance_duration[17]) == int(
12 - i
), "incorrect duration of maintenance on powerline 17 at iteration {}: it is {} and should be {}".format(
i, maintenance_duration[17], int(12 - i)
)
assert (
maintenance_duration[19] == 12
), "incorrect duration of maintenance on powerline 19 at iteration {}".format(
i
)
assert np.sum(maintenance_time == -1) == 18
assert (
maintenance_time[17] == 0
), "incorrect time for next maintenance on powerline 17 at iteration {}".format(
i
)
assert (
maintenance_time[19] == 275 - i
), "incorrect time for next maintenance on powerline 19 at iteration {}".format(
i
)
(
current_datetime,
dict_,
maintenance_time,
maintenance_duration,
hazard_duration,
prod_v,
) = chron_handl.next_time_step()
assert np.sum(maintenance_duration == 0) == 19
assert (
maintenance_duration[19] == 12
), "incorrect duration of maintenance on powerline 19 at finish"
assert np.sum(maintenance_time == -1) == 19
assert (
maintenance_time[19] == 263
), "incorrect time for next maintenance on powerline 19 at finish"
class TestLoadingChronicsHandler(HelperTests):
def setUp(self):
self.path = os.path.join(PATH_CHRONICS, "chronics")
self.n_gen = 5
self.n_load = 11
self.n_lines = 20
self.order_backend_loads = [
"2_C-10.61",
"3_C151.15",
"4_C-9.47",
"5_C201.84",
"6_C-6.27",
"9_C130.49",
"10_C228.66",
"11_C-138.89",
"12_C-27.88",
"13_C-13.33",
"14_C63.6",
]
self.order_backend_prods = [
"1_G137.1",
"2_G-56.47",
"3_G36.31",
"6_G63.29",
"8_G40.43",
]
self.order_backend_lines = [
"1_2_1",
"1_5_2",
"2_3_3",
"2_4_4",
"2_5_5",
"3_4_6",
"4_5_7",
"4_7_8",
"4_9_9",
"5_6_10",
"6_11_11",
"6_12_12",
"6_13_13",
"7_8_14",
"7_9_15",
"9_10_16",
"9_14_17",
"10_11_18",
"12_13_19",
"13_14_20",
]
self.order_backend_subs = [
"bus_1",
"bus_2",
"bus_3",
"bus_4",
"bus_5",
"bus_6",
"bus_7",
"bus_8",
"bus_9",
"bus_10",
"bus_11",
"bus_12",
"bus_13",
"bus_14",
]
# Cette méthode sera appelée après chaque test.
def tearDown(self):
pass
def test_check_validity(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
backend = PandaPowerBackend()
path_matpower = PATH_DATA_TEST_PP
case_file = "test_case14.json"
backend.load_grid(path_matpower, case_file)
chron_handl.check_validity(backend)
def test_chronicsloading(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = [18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
def test_chronicsloading_chunk(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path, chunk_size=5
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = [18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
def test_chronicsloading_secondtimestep(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
_ = chron_handl.next_time_step() # should load the first time stamp
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = [18.8, 85.1, 44.3, 7.1, 10.2, 27.1, 8.2, 3.2, 5.7, 11.8, 13.8]
assert self.compare_vect(res["injection"]["load_p"], vect)
def test_chronicsloading_secondtimestep_chunksize(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path, chunk_size=1
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
_ = chron_handl.next_time_step() # should load the first time stamp
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = [18.8, 85.1, 44.3, 7.1, 10.2, 27.1, 8.2, 3.2, 5.7, 11.8, 13.8]
assert self.compare_vect(res["injection"]["load_p"], vect)
def test_done(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = [19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
assert chron_handl.done()
def test_stopiteration(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = [19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
try:
res = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
def test_name_invariant(self):
"""
Test that the crhonics are loaded in whatever format, but the order returned is consistent with the one
of the backend.
:return:
"""
path = os.path.join(PATH_CHRONICS, "chronics_reorder")
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = [18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
for i in range(287):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = [19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6]
assert self.compare_vect(res["injection"]["load_p"], vect)
try:
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
class TestLoadingChronicsHandlerWithForecast(HelperTests):
# Cette méthode sera appelée avant chaque test.
def setUp(self):
self.path = os.path.join(PATH_CHRONICS, "chronics_with_forecast")
self.n_gen = 5
self.n_load = 11
self.n_lines = 20
self.order_backend_loads = [
"2_C-10.61",
"3_C151.15",
"4_C-9.47",
"5_C201.84",
"6_C-6.27",
"9_C130.49",
"10_C228.66",
"11_C-138.89",
"12_C-27.88",
"13_C-13.33",
"14_C63.6",
]
self.order_backend_prods = [
"1_G137.1",
"2_G-56.47",
"3_G36.31",
"6_G63.29",
"8_G40.43",
]
self.order_backend_lines = [
"1_2_1",
"1_5_2",
"2_3_3",
"2_4_4",
"2_5_5",
"3_4_6",
"4_5_7",
"4_7_8",
"4_9_9",
"5_6_10",
"6_11_11",
"6_12_12",
"6_13_13",
"7_8_14",
"7_9_15",
"9_10_16",
"9_14_17",
"10_11_18",
"12_13_19",
"13_14_20",
]
self.order_backend_subs = [
"bus_1",
"bus_2",
"bus_3",
"bus_4",
"bus_5",
"bus_6",
"bus_7",
"bus_8",
"bus_9",
"bus_10",
"bus_11",
"bus_12",
"bus_13",
"bus_14",
]
# Cette méthode sera appelée après chaque test.
def tearDown(self):
pass
def compare_vect(self, pred, true):
return np.max(np.abs(pred - true)) <= self.tolvect
def test_check_validity(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFileWithForecasts, path=self.path
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
)
backend = PandaPowerBackend()
path_matpower = PATH_DATA_TEST_PP
case_file = "test_case14.json"
backend.load_grid(path_matpower, case_file)
chron_handl.check_validity(backend)
class TestLoadingChronicsHandlerPP(HelperTests):
# Cette méthode sera appelée avant chaque test.
def setUp(self):
self.pathfake = os.path.join(PATH_CHRONICS, "chronics")
self.path = os.path.join(PATH_CHRONICS, "chronics")
self.n_gen = 5
self.n_load = 11
self.n_lines = 20
self.order_backend_loads = [
"load_1_0",
"load_2_1",
"load_13_2",
"load_3_3",
"load_4_4",
"load_5_5",
"load_8_6",
"load_9_7",
"load_10_8",
"load_11_9",
"load_12_10",
]
self.order_backend_prods = [
"gen_1_0",
"gen_2_1",
"gen_5_2",
"gen_7_3",
"gen_0_4",
]
self.order_backend_lines = [
"0_1_0",
"0_4_1",
"8_9_2",
"8_13_3",
"9_10_4",
"11_12_5",
"12_13_6",
"1_2_7",
"1_3_8",
"1_4_9",
"2_3_10",
"3_4_11",
"5_10_12",
"5_11_13",
"5_12_14",
"3_6_15",
"3_8_16",
"4_5_17",
"6_7_18",
"6_8_19",
]
self.order_backend_subs = [
"sub_0",
"sub_1",
"sub_10",
"sub_11",
"sub_12",
"sub_13",
"sub_2",
"sub_3",
"sub_4",
"sub_5",
"sub_6",
"sub_7",
"sub_8",
"sub_9",
]
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
self.id_chron_to_back_load = np.array([0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9])
def test_check_validity(self):
# load a "fake" chronics with name in the correct order
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.pathfake
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
backend = PandaPowerBackend()
path_matpower = PATH_DATA_TEST_PP
case_file = "test_case14.json"
backend.load_grid(path_matpower, case_file)
chron_handl.check_validity(backend)
def test_check_validity_withdiffname(self):
# load a real chronics with different names
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
backend = PandaPowerBackend()
path_matpower = PATH_DATA_TEST_PP
case_file = "test_case14.json"
backend.load_grid(path_matpower, case_file)
chron_handl.check_validity(backend)
def test_chronicsloading(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = np.array(
[18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6]
) # what is written on the file
backend_th = vect[self.id_chron_to_back_load] # what should be in backend
assert self.compare_vect(res["injection"]["load_p"], backend_th)
def test_chronicsloading_secondtimestep(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
_ = chron_handl.next_time_step() # should load the first time stamp
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([18.8, 85.1, 44.3, 7.1, 10.2, 27.1, 8.2, 3.2, 5.7, 11.8, 13.8])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
def test_done(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
assert chron_handl.done()
def test_done_chunk_size(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path, chunk_size=1
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
assert chron_handl.done()
def test_stopiteration(self):
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=self.path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
try:
res = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
def test_stopiteration_chunk_size(self):
chron_handl = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path, chunk_size=1
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
for i in range(288):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
try:
res = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
def test_name_invariant(self):
"""
Test that the crhonics are loaded in whatever format, but the order returned is consistent with the one
of the backend.
:return:
"""
path = os.path.join(PATH_CHRONICS, "chronics_reorder")
chron_handl = ChronicsHandler(chronicsClass=GridStateFromFile, path=path)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
for i in range(287):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(res["injection"]["load_p"], vect)
try:
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
class TestLoadingMultiFolder(HelperTests):
def setUp(self):
self.path = os.path.join(PATH_CHRONICS, "test_multi_chronics")
self.n_gen = 5
self.n_load = 11
self.n_lines = 20
self.order_backend_loads = [
"load_1_0",
"load_2_1",
"load_13_2",
"load_3_3",
"load_4_4",
"load_5_5",
"load_8_6",
"load_9_7",
"load_10_8",
"load_11_9",
"load_12_10",
]
self.order_backend_prods = [
"gen_1_0",
"gen_2_1",
"gen_5_2",
"gen_7_3",
"gen_0_4",
]
self.order_backend_lines = [
"0_1_0",
"0_4_1",
"8_9_2",
"8_13_3",
"9_10_4",
"11_12_5",
"12_13_6",
"1_2_7",
"1_3_8",
"1_4_9",
"2_3_10",
"3_4_11",
"5_10_12",
"5_11_13",
"5_12_14",
"3_6_15",
"3_8_16",
"4_5_17",
"6_7_18",
"6_8_19",
]
self.order_backend_subs = [
"sub_0",
"sub_1",
"sub_10",
"sub_11",
"sub_12",
"sub_13",
"sub_2",
"sub_3",
"sub_4",
"sub_5",
"sub_6",
"sub_7",
"sub_8",
"sub_9",
]
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
self.max_iter = 10
# Cette méthode sera appelée après chaque test.
def tearDown(self):
pass
def test_stopiteration(self):
chron_handl = ChronicsHandler(
chronicsClass=Multifolder,
path=self.path,
gridvalueClass=GridStateFromFileWithForecasts,
max_iter=self.max_iter,
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
for i in range(self.max_iter):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
try:
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
def test_stopiteration_chunksize(self):
chron_handl = ChronicsHandler(
chronicsClass=Multifolder,
path=self.path,
gridvalueClass=GridStateFromFileWithForecasts,
max_iter=self.max_iter,
chunk_size=5,
)
chron_handl.initialize(
self.order_backend_loads,
self.order_backend_prods,
self.order_backend_lines,
self.order_backend_subs,
self.names_chronics_to_backend,
)
_, res, *_ = chron_handl.next_time_step() # should load the first time stamp
for i in range(self.max_iter):
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
try:
(
_,
res,
*_,
) = chron_handl.next_time_step() # should load the first time stamp
raise RuntimeError("This should have thrown a StopIteration exception")
except StopIteration:
pass
class TestEnvChunk(HelperTests):
def setUp(self):
self.max_iter = 10
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_realistic", test=True)
self.env.chronics_handler.set_max_iter(self.max_iter)
def tearDown(self):
self.env.close()
def test_normal(self):
# self.env.set_chunk_size()
self.env.reset()
i = 0
done = False
while not done:
obs, reward, done, info = self.env.step(self.env.action_space())
i += 1
assert i == self.max_iter # I used 1 data to intialize the environment
def test_normal_chunck(self):
self.env.set_chunk_size(1)
self.env.reset()
i = 0
done = False
while not done:
obs, reward, done, info = self.env.step(self.env.action_space())
i += 1
assert i == self.max_iter # I used 1 data to intialize the environment
class TestMissingData(HelperTests):
def test_load_error(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with self.assertRaises(EnvError):
with make(
"rte_case14_realistic", test=True, chronics_path="/answer/life/42"
):
pass
def run_env_till_over(self, env, max_iter):
nb_it = 0
done = False
obs = None
while not done:
obs, reward, done, info = env.step(env.action_space())
nb_it += 1
# assert i == max_iter
return nb_it, obs
def test_load_still(self):
max_iter = 10
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example",
test=True,
chronics_path=os.path.join(
PATH_CHRONICS, "5bus_example_some_missing", "chronics"
),
) as env:
# test a first time without chunks
env.set_id(0)
env.chronics_handler.set_max_iter(max_iter)
obs = env.reset()
# check that simulate is working
simul_obs, *_ = obs.simulate(env.action_space())
# check that load_p is indeed modified
assert np.all(
simul_obs.load_p
== env.chronics_handler.real_data.data.load_p_forecast[1, :]
)
# check that the environment goes till the end
nb_it, final_obs = self.run_env_till_over(env, max_iter)
assert nb_it == max_iter
# check the that the "missing" files is properly handled: data is not modified
assert np.all(obs.load_q == final_obs.load_q)
# check that other data are modified properly
assert np.any(obs.prod_p != final_obs.prod_p)
# test a second time with chunk
env.set_id(0)
env.set_chunk_size(3)
obs = env.reset()
nb_it, obs = self.run_env_till_over(env, max_iter)
assert nb_it == max_iter
pass
class TestCFFWFWM(HelperTests):
def test_load(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"),
test=True,
param=param,
) as env:
env.seed(123456) # for reproducible tests !
obs = env.reset()
# get input data, to check they were correctly applied in
linesPossiblyInMaintenance = (
env.chronics_handler.real_data.data.line_to_maintenance
)
assert np.all(
np.array(sorted(linesPossiblyInMaintenance))
== [
"11_12_13",
"12_13_14",
"16_18_23",
"16_21_27",
"22_26_39",
"26_30_56",
"2_3_0",
"30_31_45",
"7_9_9",
"9_16_18",
]
)
ChronicMonth = env.chronics_handler.real_data.data.start_datetime.month
assert ChronicMonth == 8
maxMaintenancePerDay = env.chronics_handler.real_data.data.max_daily_number_per_month_maintenance[
(ChronicMonth - 1)
]
assert maxMaintenancePerDay == 2
envLines = env.name_line
idx_linesPossiblyInMaintenance = [
i
for i in range(len(envLines))
if envLines[i] in linesPossiblyInMaintenance
]
idx_linesNotInMaintenance = [
i
for i in range(len(envLines))
if envLines[i] not in linesPossiblyInMaintenance
]
# maintenance dataFrame
maintenanceChronic = maintenances_df = pd.DataFrame(
env.chronics_handler.real_data.data.maintenance, columns=envLines
)
nb_timesteps = maintenanceChronic.shape[0]
# identify the timestamps of the chronics to find out the month and day of the week
freq = (
str(
int(
env.chronics_handler.real_data.data.time_interval.total_seconds()
)
)
+ "s"
) # should be in the timedelta frequency format in pandas
datelist = pd.date_range(
env.chronics_handler.real_data.data.start_datetime,
periods=nb_timesteps,
freq=freq,
)
maintenances_df.index = datelist
assert (
maintenanceChronic[envLines[idx_linesNotInMaintenance]].sum().sum()
== 0
)
assert maintenanceChronic[list(linesPossiblyInMaintenance)].sum().sum() >= 1
nb_mainteance_timestep = maintenanceChronic.sum(axis=1)
assert np.all(nb_mainteance_timestep <= maxMaintenancePerDay)
def test_maintenance_multiple_timesteps(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"),
test=True,
param=param,
) as env:
env.seed(0)
envLines = env.name_line
linesPossiblyInMaintenance = np.array(
[
"11_12_13",
"12_13_14",
"16_18_23",
"16_21_27",
"22_26_39",
"26_30_56",
"2_3_0",
"30_31_45",
"7_9_9",
"9_16_18",
]
)
idx_linesPossiblyInMaintenance = [
i
for i in range(len(envLines))
if envLines[i] in linesPossiblyInMaintenance
]
idx_linesNotInMaintenance = [
i
for i in range(len(envLines))
if envLines[i] not in linesPossiblyInMaintenance
]
maxMaintenancePerDay = 2
obs = env.reset()
####check that at least one line that can go in maintenance actuamlly goes in maintenance
assert (
np.sum(
obs.duration_next_maintenance[idx_linesPossiblyInMaintenance]
)
>= 1
)
####check that at no line that can not go in maintenance actually goes in maintenance
assert (
np.sum(obs.duration_next_maintenance[idx_linesNotInMaintenance])
== 0
)
done = False
max_it = 10
it_num = 0
while not done:
if np.any(obs.time_next_maintenance > 0):
timestep_nextMaintenance = np.min(
obs.time_next_maintenance[obs.time_next_maintenance != -1]
)
else:
break
env.fast_forward_chronics(timestep_nextMaintenance)
obs, reward, done, info = env.step(env.action_space())
assert (
np.sum(obs.time_next_maintenance == 0) <= maxMaintenancePerDay
)
assert np.all(
np.abs(obs.a_or[obs.time_next_maintenance == 0] - 0.0)
<= self.tol_one
)
assert np.all(~obs.line_status[obs.time_next_maintenance == 0])
it_num += 1
if it_num >= max_it:
break
def test_proba(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(
PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance_2"
),
test=True,
param=param,
) as env:
env.seed(0)
# input data
nb_scenario = (
30 # if too low then i don't have 1e-3 beteween theory and practice
)
nb_line_in_maintenance = 10
assert (
len(env.chronics_handler.real_data.data.line_to_maintenance)
== nb_line_in_maintenance
)
proba = 0.06
nb_th = proba * 5 / 7 # for day of week
nb_th *= 8 / 24 # maintenance only between 9 and 17
nb_maintenance = np.zeros(env.n_line, dtype=dt_float)
nb_ts_ = 0
for i in range(nb_scenario):
obs = env.reset()
nb_maintenance += np.sum(
env.chronics_handler.real_data.data.maintenance, axis=0
)
nb_ts_ += env.chronics_handler.real_data.data.maintenance.shape[0]
total_maintenance = np.sum(nb_maintenance)
total_maintenance /= nb_ts_ * nb_line_in_maintenance
assert np.abs(total_maintenance - nb_th) <= 1e-3
def test_load_fake_january(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(
PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance_3"
),
test=True,
param=param,
) as env:
env.seed(0)
# get input data, to check they were correctly applied in
linesPossiblyInMaintenance = (
env.chronics_handler.real_data.data.line_to_maintenance
)
assert np.all(
np.array(sorted(linesPossiblyInMaintenance))
== [
"11_12_13",
"12_13_14",
"16_18_23",
"16_21_27",
"22_26_39",
"26_30_56",
"2_3_0",
"30_31_45",
"7_9_9",
"9_16_18",
]
)
ChronicMonth = env.chronics_handler.real_data.data.start_datetime.month
assert ChronicMonth == 1
maxMaintenancePerDay = env.chronics_handler.real_data.data.max_daily_number_per_month_maintenance[
(ChronicMonth - 1)
]
assert maxMaintenancePerDay == 0
assert np.sum(env.chronics_handler.real_data.data.maintenance) == 0
def test_split_and_save(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"),
test=True,
param=param,
) as env:
env.seed(0)
env.set_id(0)
obs = env.reset()
start_d = {"Scenario_august_00": "2012-08-10 00:00"}
end_d = {"Scenario_august_00": "2012-08-19 00:00"}
ts_beg = 2591
ts_end = 5184
# generate some reference data
chronics_outdir = tempfile.mkdtemp()
env.chronics_handler.real_data.split_and_save(
start_d, end_d, chronics_outdir
)
maintenance_0_0 = pd.read_csv(
os.path.join(
chronics_outdir, "Scenario_august_00", "maintenance.csv.bz2"
),
sep=";",
).values
# test that i got a different result with a different seed
env.seed(1)
env.set_id(0)
obs = env.reset()
chronics_outdir2 = tempfile.mkdtemp()
env.chronics_handler.real_data.split_and_save(
start_d, end_d, chronics_outdir2
)
maintenance_1 = pd.read_csv(
os.path.join(
chronics_outdir2, "Scenario_august_00", "maintenance.csv.bz2"
),
sep=";",
).values
assert np.any(maintenance_0_0 != maintenance_1)
# and now test that i have the same results with the same seed
env.seed(0)
env.set_id(0)
obs = env.reset()
chronics_outdir3 = tempfile.mkdtemp()
env.chronics_handler.real_data.split_and_save(
start_d, end_d, chronics_outdir3
)
maintenance_0_1 = pd.read_csv(
os.path.join(
chronics_outdir3, "Scenario_august_00", "maintenance.csv.bz2"
),
sep=";",
).values
assert np.all(maintenance_0_0 == maintenance_0_1)
# make sure i can reload the environment
env2 = make(
os.path.join(
PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"
),
test=True,
param=param,
data_feeding_kwargs={
"gridvalueClass": GridStateFromFileWithForecasts
},
chronics_path=chronics_outdir3,
)
env2.set_id(0)
obs = env2.reset()
# and that it has the right chroncis
assert np.all(
env2.chronics_handler.real_data.data.maintenance.astype(dt_float)
== maintenance_0_0
)
def test_seed(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"),
test=True,
param=param,
) as env:
nb_scenario = 10
nb_maintenance = np.zeros((nb_scenario, env.n_line), dtype=dt_float)
nb_maintenance1 = np.zeros((nb_scenario, env.n_line), dtype=dt_float)
env.seed(0)
for i in range(nb_scenario):
obs = env.reset()
nb_maintenance[i, :] = np.sum(
env.chronics_handler.real_data.data.maintenance, axis=0
)
env.seed(0)
for i in range(nb_scenario):
obs = env.reset()
nb_maintenance1[i, :] = np.sum(
env.chronics_handler.real_data.data.maintenance, axis=0
)
assert np.all(nb_maintenance == nb_maintenance)
def test_chunk_size(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(
PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance_3"
),
test=True,
param=param,
) as env:
env.seed(0)
obs = env.reset()
maint = env.chronics_handler.real_data.data.maintenance
env.seed(0)
env.set_chunk_size(10)
obs = env.reset()
maint2 = env.chronics_handler.real_data.data.maintenance
assert np.all(maint == maint2)
class TestWithCache(HelperTests):
def test_load(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "5bus_example_some_missing"),
test=True,
param=param,
chronics_class=MultifolderWithCache,
) as env:
env.seed(123456) # for reproducible tests !
env.chronics_handler.reset()
nb_steps = 10
# I test that the reset ... reset also the date time and the chronics "state"
obs = env.reset()
assert obs.minute_of_hour == 5
assert env.chronics_handler.real_data.data.current_index == 0
assert env.chronics_handler.real_data.data.curr_iter == 1
for i in range(nb_steps):
obs, reward, done, info = env.step(env.action_space())
assert obs.minute_of_hour == 55
obs = env.reset()
assert obs.minute_of_hour == 5
assert env.chronics_handler.real_data.data.current_index == 0
assert env.chronics_handler.real_data.data.curr_iter == 1
class TestMaintenanceBehavingNormally(HelperTests):
def test_withrealistic(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
) as env:
l_id = 11
obs = env.reset()
assert np.all(obs.time_before_cooldown_line == 0)
obs, reward, done, info = env.step(env.action_space())
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(11, 1)]})
)
assert info["is_illegal"]
assert not obs.line_status[l_id]
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(11, 1)]}})
)
assert (
info["is_illegal"] is True
) # it is legal -> no more because of cooldown (and because now this action is counted as an action on a line)
assert not obs.line_status[
l_id
] # but has no effect (line is still disconnected)
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
arr_ = np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
arr_[l_id] = 9 - i
assert np.all(
obs.time_before_cooldown_line == arr_
), "error at time step {}".format(i)
# i have no more cooldown on line now
assert np.all(obs.time_before_cooldown_line == 0)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(11, 1)]}})
)
assert info["is_illegal"] is False # it is legal
assert obs.line_status[
l_id
] # reconnecting only one end has still no effect -> change of behaviour
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(11, 1)]})
)
assert info["is_illegal"] is False # it's legal
assert obs.line_status[l_id] # it has reconnected the powerline
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# nothing is in maintenance
for i in range(obs.time_next_maintenance[12] - 1):
obs, reward, done, info = env.step(env.action_space())
# no maintenance yet
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# a maintenance now
obs, reward, done, info = env.step(env.action_space())
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
def test_with_alwayslegal(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
gamerules_class=AlwaysLegal,
) as env:
l_id = 11
obs = env.reset()
assert np.all(obs.time_before_cooldown_line == 0)
obs, reward, done, info = env.step(env.action_space())
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(11, 1)]})
)
assert not info["is_illegal"] # it is legal
assert not obs.line_status[l_id] # yet maintenance should have stayed
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(11, 1)]}})
)
assert not info["is_illegal"] # it is legal
assert not obs.line_status[
l_id
] # but has no effect (line is still disconnected)
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
arr_ = np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
arr_[l_id] = 9 - i
assert np.all(
obs.time_before_cooldown_line == arr_
), "error at time step {}".format(i)
# i have no more cooldown on line now
assert np.all(obs.time_before_cooldown_line == 0)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(11, 1)]}})
)
assert not info[
"is_illegal"
] # it is legal -> no more because of cooldown
# assert not obs.line_status[11] # reconnecting only one end has still no effect -> change of behaviour now
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(11, 1)]})
)
assert not info["is_illegal"] # it is legal
assert obs.line_status[l_id] # it has reconnected the powerline
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# nothing is in maintenance
for i in range(obs.time_next_maintenance[12] - 1):
obs, reward, done, info = env.step(env.action_space())
# no maintenance yet
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# a maintenance now
obs, reward, done, info = env.step(env.action_space())
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
class TestMultiFolder(HelperTests):
def get_multifolder_class(self):
self.res_th = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0]
return Multifolder
def _reset_chron_handl(self, chronics_handler):
pass
def setUp(self) -> None:
chronics_class = self.get_multifolder_class()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case14_realistic", test=True, chronics_class=chronics_class
)
root_path = self.env.chronics_handler.real_data.path
self.chronics_paths = np.array(
[os.path.join(root_path, "000"), os.path.join(root_path, "001")]
)
self._reset_chron_handl(self.env.chronics_handler)
self.env.seed(0)
def test_real_data(self):
real_data = self.env.chronics_handler.real_data
def test_filter(self):
class MyFilterForTest:
def __init__(self):
self.i = -1
def __call__(self, path):
self.i += 1
return self.i == 0
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [0, 1])
my_filt = MyFilterForTest()
self.env.chronics_handler.set_filter(my_filt)
obs = self.env.chronics_handler.reset()
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [0])
def tearDown(self) -> None:
self.env.close()
def test_the_tests(self):
assert isinstance(self.env.chronics_handler.real_data, Multifolder)
def test_shuffler(self):
def shuffler(list):
return list[[1, 0]]
# without shuffling it's read this way
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [0, 1])
# i check that shuffling is done properly
self.env.chronics_handler.shuffle(shuffler)
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [1, 0])
# i check that the env is working
obs = self.env.reset()
# at first chronics is 0, now it's 1
# and i have put the subpaths 0 at the element 1 of the order
assert self.env.chronics_handler.real_data.data.path == self.chronics_paths[0]
def test_get_id(self):
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[1]
def test_set_id(self):
self.env.set_id(0)
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
def shuffler(list):
return list[[1, 0]]
self.env.chronics_handler.shuffle(shuffler)
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[1]
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
self.env.set_id(0)
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[1]
def test_set_id_str(self):
self.env.set_id(0)
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
self.env.set_id(self.chronics_paths[1])
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[1]
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
with self.assertRaises(ChronicsError):
self.env.set_id("toto")
def test_reset(self):
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
self.env.chronics_handler.real_data.reset()
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [0, 1])
def shuffler(list):
return list[[1, 0]]
self.env.chronics_handler.real_data.reset()
self.env.chronics_handler.shuffle(shuffler)
assert np.all(
self.env.chronics_handler.real_data.subpaths == self.chronics_paths
)
assert np.all(self.env.chronics_handler.real_data._order == [1, 0])
obs = self.env.reset()
assert self.env.chronics_handler.get_id() == self.chronics_paths[0]
def test_sample_next_chronics(self):
for i in range(20):
assert (
self.env.chronics_handler.sample_next_chronics([0.9, 0.1]) == self.res_th[i]
), "error for iteration {}" "".format(i)
# reseed to test it's working accordingly
self.env.seed(0)
for i in range(20):
assert (
self.env.chronics_handler.sample_next_chronics([0.9, 0.1]) == self.res_th[i]
), "error for iteration {}" "".format(i)
def test_sample_next_chronics_withfilter(self):
chronics_class = self.get_multifolder_class()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True, chronics_class=chronics_class)
self._reset_chron_handl(env.chronics_handler)
env.seed(0)
# test than the filtering
class MyFilterForTest:
def __init__(self):
self.i = -1
def __call__(self, path):
self.i += 1
return self.i % 2 == 0
root_path = env.chronics_handler.real_data.path
chronics_paths = np.array(
[os.path.join(root_path, "{:02d}".format(i)) for i in range(20)]
)
# if i don't do anything, then everything is normal
assert np.all(env.chronics_handler.real_data.subpaths == chronics_paths)
assert np.all(env.chronics_handler.real_data._order == [i for i in range(20)])
# now i will apply a filter and check it has the correct behaviour
my_filt = MyFilterForTest()
env.chronics_handler.set_filter(my_filt)
obs = env.chronics_handler.reset()
# check that reset do what need to be done
assert np.all(env.chronics_handler.real_data.subpaths == chronics_paths)
assert np.all(
env.chronics_handler.real_data._order == [2 * i for i in range(10)]
)
# now check the id is correct
id_ = self.env.chronics_handler.sample_next_chronics([0.9, 0.1])
assert id_ == 0
assert np.all(
env.chronics_handler.real_data._order == [2 * i for i in range(10)]
)
def test_set_id_int(self):
"""test the env.set_id method when used with int"""
chronics_class = self.get_multifolder_class()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True, chronics_class=chronics_class)
if issubclass(chronics_class, MultifolderWithCache):
env.chronics_handler.set_filter(
lambda x: re.match(".*(01|04|05|07|09).*", x) is not None
)
env.chronics_handler.reset()
env.set_id(1)
env.reset()
id_str = os.path.split(env.chronics_handler.get_id())[-1]
if not issubclass(chronics_class, MultifolderWithCache):
assert id_str == "01"
else:
assert id_str == "04"
env.set_id(4)
env.reset()
id_str = os.path.split(env.chronics_handler.get_id())[-1]
if not issubclass(chronics_class, MultifolderWithCache):
assert id_str == "04"
else:
assert id_str == "09"
def test_set_id_full_path(self):
"""test the env.set_id method when used with full path"""
chronics_class = self.get_multifolder_class()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True, chronics_class=chronics_class)
if issubclass(chronics_class, MultifolderWithCache):
env.chronics_handler.set_filter(
lambda x: re.match(".*(01|04|05).*", x) is not None
)
env.chronics_handler.reset()
base_path = os.path.split(env.chronics_handler.get_id())[0]
env.set_id(os.path.join(base_path, "01"))
env.reset()
assert env.chronics_handler.get_id() == os.path.join(base_path, "01")
env.set_id(os.path.join(base_path, "04"))
env.reset()
assert env.chronics_handler.get_id() == os.path.join(base_path, "04")
with self.assertRaises(ChronicsError):
env.set_id(os.path.join(base_path, "31"))
if issubclass(chronics_class, MultifolderWithCache):
with self.assertRaises(ChronicsError):
env.set_id(os.path.join(base_path, "00"))
def test_set_id_chron_dir(self):
"""test the env.set_id method when used with only folder name in the chronics"""
chronics_class = self.get_multifolder_class()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True, chronics_class=chronics_class)
if issubclass(chronics_class, MultifolderWithCache):
env.chronics_handler.set_filter(
lambda x: re.match(".*(01|04|05).*", x) is not None
)
env.chronics_handler.reset()
base_path = os.path.split(env.chronics_handler.get_id())[0]
env.set_id("01")
env.reset()
assert env.chronics_handler.get_id() == os.path.join(base_path, "01")
env.set_id("04")
env.reset()
assert env.chronics_handler.get_id() == os.path.join(base_path, "04")
with self.assertRaises(ChronicsError):
env.set_id("31")
if issubclass(chronics_class, MultifolderWithCache):
with self.assertRaises(ChronicsError):
env.set_id("00")
class TestMultiFolderWithCache(TestMultiFolder):
def get_multifolder_class(self):
self.res_th = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0]
return MultifolderWithCache
def test_the_tests(self):
assert isinstance(self.env.chronics_handler.real_data, MultifolderWithCache)
def _reset_chron_handl(self, chronics_handler):
# by default when using the cache, only the first data is kept...
# I make sure to keep everything
chronics_handler.set_filter(lambda x: True)
chronics_handler.reset()
class TestDeactivateMaintenance(HelperTests):
def test_maintenance_deactivated(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
) as env:
obs = env.reset()
# there is a maintenance by default for some powerlines
assert np.any(obs.time_next_maintenance != -1)
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
data_feeding_kwargs={
"gridvalueClass": GridStateFromFileWithForecastsWithoutMaintenance
},
) as env:
obs = env.reset()
# all maintenance are deactivated
assert np.all(obs.time_next_maintenance == -1)
class TestMaxIter(HelperTests):
def test_max_iter(self):
nb_episode = 2
max_iter = 288*2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True)
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=nb_episode,
pbar=False,
max_iter=max_iter,
env_seeds=[0] * nb_episode)
# it crashed above in the creation of the runner
# check that the episode has the correct length
assert res[0][-1] == 288
assert res[0][-2] == 288
assert res[1][-1] == 288
assert res[1][-2] == 288
if __name__ == "__main__":
unittest.main()
| 78,809 | 35.452359 | 127 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Converter.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import os
import json
from grid2op.Action.BaseAction import BaseAction
from grid2op.tests.helper_path_test import *
from grid2op.MakeEnv import make
from grid2op.Parameters import Parameters
from grid2op.Converter import ConnectivityConverter, IdToAct
from grid2op.Action import PlayableAction
import tempfile
import pdb
import warnings
warnings.simplefilter("error")
class TestConnectivityConverter(HelperTests):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"educ_case14_storage",
test=True,
param=param,
action_class=PlayableAction,
)
np.random.seed(0)
def tearDown(self):
self.env.close()
def test_ConnectivityConverter(self):
converter = ConnectivityConverter(self.env.action_space)
converter.seed(0)
converter.init_converter()
res = np.array(
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
4,
4,
4,
4,
4,
4,
4,
4,
4,
4,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
8,
8,
8,
8,
8,
8,
8,
8,
8,
8,
12,
12,
12,
12,
12,
12,
]
)
assert np.array_equal(converter.subs_ids, res)
assert len(converter.obj_type) == converter.n
assert len(set(converter.obj_type)) == converter.n
assert converter.pos_topo.shape[0] == converter.n
assert len(set([tuple(sorted(el)) for el in converter.pos_topo])) == converter.n
n_trial = 100
preds = np.zeros(n_trial)
for i in range(n_trial):
coded_act = np.random.rand(converter.n) * 2.0 - 1.0
preds[i] = converter._compute_disagreement(coded_act, np.ones(converter.n))
# check the formula is properly implemented in case of "everything connected together"
assert np.abs(preds[i] - 0.5 * (1 - np.mean(coded_act))) <= self.tol_one
# check that on average over "a lot" of stuff the distance to the "everything connected" is 0.5
assert np.abs(np.mean(preds) - 0.5) <= 1 / np.sqrt(n_trial)
# and not test i can produce an action that can be implemented
act = converter.convert_act(encoded_act=coded_act)
obs, reward, done, info = self.env.step(act)
# test sample
obs = self.env.reset()
act = converter.sample()
obs, reward, done, info = self.env.step(act)
def test_max_sub_changed(self):
for ms_sub in [1, 2, 3]:
converter = ConnectivityConverter(self.env.action_space)
converter.init_converter(max_sub_changed=ms_sub)
converter.seed(0)
coded_act = np.random.rand(converter.n)
# and not test i can produce an action that can be implemented
act = converter.convert_act(encoded_act=coded_act)
lines_impacted, subs_impacted = act.get_topological_impact()
assert (
np.sum(subs_impacted) == ms_sub
), "wrong number of substations affected. It should be {}".format(ms_sub)
obs, reward, done, info = self.env.step(act)
# test sample
obs = self.env.reset()
act = converter.sample()
lines_impacted, subs_impacted = act.get_topological_impact()
assert (
np.sum(subs_impacted) == ms_sub
), "wrong number of substations affected. It should be {}".format(ms_sub)
obs, reward, done, info = self.env.step(act)
def test_can_make_action(self):
converter = ConnectivityConverter(self.env.action_space)
converter.init_converter(max_sub_changed=self.env.parameters.MAX_SUB_CHANGED)
converter.seed(0)
with self.assertRaises(Exception):
# one too shot
tmp = np.zeros(converter.n - 1)
converter.convert_act(tmp)
with self.assertRaises(Exception):
# one too long
tmp = np.zeros(converter.n + 1)
converter.convert_act(tmp)
with self.assertRaises(Exception):
# one too low
tmp = np.zeros(converter.n)
tmp[3] = -1.1
converter.convert_act(tmp)
with self.assertRaises(Exception):
# one too high
tmp = np.zeros(converter.n)
tmp[3] = 1.1
converter.convert_act(tmp)
size_ = converter.n
# test do nothing gives do nothing indeed
dn_enc = converter.do_nothing_encoded_act()
glop_dn_act = converter.convert_act(dn_enc)
assert glop_dn_act == self.env.action_space()
# encode the topology [1,1 ,2,2] at sub 12, meaning: line_ex 9 / line_ex 13 together,
# and line or 14 / load 9 together
complex_act = 1.0 * dn_enc
complex_act[84] = 1.0 # line ex 9 and line ex 13 together
complex_act[85] = -1.0 # line ex 9 and line or 14 not together
complex_act[86] = -1.0 # line ex 9 and load 9 not together
glop_act = converter.convert_act(complex_act)
aff_line, aff_sub = glop_act.get_topological_impact()
assert np.sum(aff_line) == 0
assert np.sum(aff_sub) == 1
assert aff_sub[12]
assert glop_act.line_ex_set_bus[9] != 0
assert glop_act.line_ex_set_bus[13] != 0
assert glop_act.line_or_set_bus[14] != 0
assert glop_act.load_set_bus[9] != 0
assert glop_act.line_ex_set_bus[9] == glop_act.line_ex_set_bus[13]
assert glop_act.line_ex_set_bus[9] != glop_act.line_or_set_bus[14]
assert glop_act.line_ex_set_bus[9] != glop_act.load_set_bus[9]
assert glop_act.line_or_set_bus[14] == glop_act.load_set_bus[9]
# encode the topology [1,1 ,2,2] at sub 12, meaning: line_ex 9 / line_ex 13 together,
# and line or 14 / load 9 together but in a "soft" manner
complex_act = 1.0 * dn_enc
complex_act[84] = 0.8 # line ex 9 and line ex 13 together
complex_act[85] = -0.9 # line ex 9 and line or 14 not together
complex_act[86] = -0.9 # line ex 9 and load 9 not together
glop_act2 = converter.convert_act(complex_act)
assert (
abs(converter.last_disagreement - 0.5 * (0.2 + 0.1 + 0.1) / size_)
<= self.tol_one
)
assert glop_act == glop_act2
# now tricky stuff, such that the greedy do not work and i need to explore a bit
# line_ex 9 / line_ex 13 together and line or 14 / load 9 together
complex_act = 1.0 * dn_enc
complex_act[84] = 0.6 # line ex 9 and line ex 13 together
complex_act[85] = -0.9 # line ex 9 and line or 14 not together
complex_act[86] = -0.9 # line ex 9 and load 9 not together
complex_act[87] = 0.61 # "line_ex id 13" and the "line_or id 14" together
complex_act[88] = -0.2 # "line_ex id 13" and the "load id 9" together
complex_act[89] = 0.0 # "line_or id 14" and the "load id 9" no preferences
glop_act3 = converter.convert_act(complex_act)
# this gives : [ 1 2 2 2 ], which is sub optimal
# Lex9 Lex13 lor14 loa9
frst_disag = converter.last_disagreement
assert (
abs(frst_disag - 0.5 * (1.6 + 0.1 + 0.1 + 0.39 + 1.2) / size_)
<= self.tol_one
)
assert glop_act != glop_act3 # but glop_act should be better !
glop_act4 = converter.convert_act(complex_act, explore=3)
this_disag = converter.last_disagreement
assert this_disag < frst_disag, "this disagreement should always be lower !"
assert converter.indx_sel != 0, "the first has been selected, it should not !"
assert glop_act == glop_act4, "the same action first action should be optimal"
assert (
abs(this_disag - 0.5 * (0.4 + 0.1 + 0.1 + 1.61 + 0.8) / size_)
<= self.tol_one
)
def test_bug_in_doc(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_realistic", test=True)
converter = ConnectivityConverter(env.action_space)
# it's a good practice to seed the element that can be, for reproducibility
converter.seed(0)
# to avoid creating illegal actions affecting more than the allowed number of parameters
converter.init_converter(max_sub_changed=env.parameters.MAX_SUB_CHANGED)
encoded_act = np.zeros(converter.n)
encoded_act[0] = 1 # i want to connect "line_ex id 0" and the "line_or id 2"
encoded_act[
1
] = -1 # i don't want to connect "line_ex id 0" and the "line_or id 3"
encoded_act[
2
] = -1 # i don't want to connect "line_ex id 0" and the "line_or id 4"
encoded_act[3] = -1 # i don't want to connect "line_ex id 0" and the "gen id 0"
encoded_act[4] = 1 # i want to connect "line_ex id 0" and the "load id 0"
# and now retrieve the corresponding grid2op action:
grid2op_act = converter.convert_act(encoded_act)
assert converter.last_disagreement == 0.0
assert np.array_equal(grid2op_act.set_bus[3:9], [1, 1, 2, 2, 2, 1])
# second way to express the same action
encoded_act2 = np.zeros(converter.n)
encoded_act2[0] = 1 # i want to connect "line_ex id 0" and the "line_or id 2"
encoded_act2[4] = 1 # i want to connect "line_ex id 0" and the "load id 0"
encoded_act2[9] = 1 # i want to connect "line_or id 3" and the "line_or id 4"
encoded_act2[10] = 1 # i want to connect "line_or id 3" and the "gen id 0"
encoded_act2[14] = -1 # i don't want to connect "gen id 0" and the "load id 0"
# and now retrieve the corresponding grid2op action:
grid2op_act2 = converter.convert_act(encoded_act2)
assert converter.last_disagreement == 0.0
assert np.array_equal(grid2op_act2.set_bus[3:9], [1, 1, 2, 2, 2, 1])
# trick it: i don't specified enough constraints (used to be infinite loop)
encoded_act3 = np.zeros(converter.n)
encoded_act3[0] = 1 # i want to connect "line_ex id 0" and the "line_or id 2"
encoded_act3[4] = 1 # i want to connect "line_ex id 0" and the "load id 0"
encoded_act3[9] = 1 # i want to connect "line_or id 3" and the "line_or id 4"
encoded_act3[10] = 1 # i want to connect "line_or id 3" and the "gen id 0"
grid2op_act3 = converter.convert_act(encoded_act3)
assert converter.last_disagreement == 0.0
assert np.array_equal(grid2op_act3.set_bus[3:9], [1, 1, 1, 1, 1, 1])
size_ = converter.n
# trick (the compute_disagreement function) in another way: not all components are set
missing = np.ones(converter.n)
missing[3] = 0 # encodes for line_ex id O
disag0 = converter._compute_disagreement(encoded_act3, missing)
# 2 constraints not met because the line_ex id O is not set in the action
assert abs(disag0 - 2.0 / size_) <= self.tol_one
missing2 = np.ones(converter.n)
missing2[8] = 0 # encodes for load id 0
disag2 = converter._compute_disagreement(encoded_act3, missing2)
# 1 constraints not met because the load id 0 O is not set in the action
assert abs(disag2 - 1.0 / size_) <= self.tol_one
missing3 = np.ones(converter.n)
missing3[3:9] = 0 # all constraints not met
disag3 = converter._compute_disagreement(encoded_act3, missing3)
# one component not set in the "action candidate" among 4 constraints
assert abs(disag3 - 4.0 / size_) <= self.tol_one
class TestIdToAct(HelperTests):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
param = Parameters()
param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True})
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"educ_case14_storage",
test=True,
param=param,
action_class=PlayableAction,
)
np.random.seed(0)
self.filenamedict = "test_action_json_educ_case14_storage.json"
def tearDown(self):
self.env.close()
def test_save_reload(self):
path_ = tempfile.mkdtemp()
converter = IdToAct(self.env.action_space)
converter.init_converter(set_line_status=False, change_bus_vect=False)
converter.save(path_, "tmp_convert.npy")
init_size = converter.size()
array = np.load(os.path.join(path_, "tmp_convert.npy"))
act = converter.convert_act(27)
act_ = converter.convert_act(-1)
assert array.shape[1] == self.env.action_space.size()
converter2 = IdToAct(self.env.action_space)
converter2.init_converter(all_actions=os.path.join(path_, "tmp_convert.npy"))
assert init_size == converter2.size()
act2 = converter2.convert_act(27)
act2_ = converter2.convert_act(-1)
assert act == act2
assert act_ == act2_
def test_specific_attr(self):
dict_orig = {
"set_line_status": False,
"change_line_status": False,
"set_topo_vect": False,
"change_bus_vect": False,
"redispatch": False,
"curtail": False,
"storage": False,
}
dims = {
"set_line_status": 101,
"change_line_status": 21,
"set_topo_vect": 235,
"change_bus_vect": 255,
"redispatch": 25,
"curtail": 31,
"storage": 17,
}
for attr in dict_orig.keys():
kwargs = dict_orig.copy()
kwargs[attr] = True
converter = IdToAct(self.env.action_space)
converter.init_converter(**kwargs)
assert converter.n == dims[attr], (
f'dim for "{attr}" should be {dims[attr]} but is ' f"{converter.n}"
)
def test_init_from_list_of_dict(self):
path_input = os.path.join(PATH_DATA_TEST, self.filenamedict)
with open(path_input, "r") as f:
list_act = json.load(f)
converter = IdToAct(self.env.action_space)
converter.init_converter(all_actions=list_act)
assert converter.n == 255
assert isinstance(converter.all_actions[-1], BaseAction)
assert isinstance(converter.all_actions[0], BaseAction)
if __name__ == "__main__":
unittest.main()
| 16,882 | 36.685268 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Curtailment.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import pdb
import time
import warnings
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.Parameters import Parameters
from grid2op.dtypes import dt_float
from grid2op.Action import PlayableAction, CompleteAction
import warnings
# TODO check when there is also redispatching
class TestCurtailmentEnv(HelperTests):
"""test the env part of the storage functionality"""
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
self.env1 = grid2op.make(
"educ_case14_storage",
test=True,
action_class=PlayableAction,
param=param,
)
self.env2 = self.env1.copy()
def tearDown(self) -> None:
self.env1.close()
self.env2.close()
def test_reset(self):
"""test curtailment is ok when env is reset"""
obs = self.env1.reset()
assert np.all(obs.curtailment >= 0.0)
assert np.all(obs.curtailment <= 1.0)
assert np.all(obs.curtailment[~obs.gen_renewable] == 0.0)
def test_action_ok(self):
"""test a storage action is supported (basic test)"""
act = self.env1.action_space({"curtail": [(2, 0.5)]})
str_ = act.__str__()
real_str = (
"This action will:\n"
"\t - NOT change anything to the injections\n"
"\t - NOT perform any redispatching action\n"
"\t - NOT modify any storage capacity\n"
"\t - Perform the following curtailment:\n"
'\t \t - Limit unit "gen_5_2" to 50.0% of its Pmax (setpoint: 0.500)\n'
"\t - NOT force any line status\n"
"\t - NOT switch any line status\n\t - NOT switch anything in the topology\n"
"\t - NOT force any particular bus configuration"
)
assert str_ == real_str
def test_curtailment_no_effect(self):
act = self.env1.action_space({"curtail": [(2, 5)]})
obs1, *_ = self.env1.step(act)
obs2, *_ = self.env2.step(self.env2.action_space())
assert obs1 == obs2
def test_curtailment_effect(self):
"""
test different kind of equations when curtailment has been applied
in this example the 23% of curtailment is just the right amount so that, during the
"""
gen_id = 2
ratio_max = 0.23
act = self.env1.action_space({"curtail": [(gen_id, ratio_max)]})
self.env1.step(act)
self.env2.step(self.env2.action_space())
tested = False
for step in range(100):
obs1_3, reward1_3, done1_3, info1_3 = self.env1.step(
self.env1.action_space()
)
obs2_3, reward2_3, done2_3, info2_3 = self.env2.step(
self.env2.action_space()
)
if done1_3 or done2_3:
raise RuntimeError("Environment did game over, this is not normal")
if info1_3["exception"]:
raise RuntimeError("Exception for info1_3")
if info2_3["exception"]:
raise RuntimeError("Exception for info2_3")
assert (
abs(
np.sum(obs1_3.actual_dispatch)
+ (obs1_3.gen_p[gen_id] - obs2_3.gen_p[gen_id])
)
<= 1e-4
), f"for step {step}"
this_prod_th = obs1_3.gen_p_before_curtail[self.env1.gen_renewable]
th_prod = obs2_3.gen_p[self.env1.gen_renewable]
assert np.max(np.abs(this_prod_th - th_prod)) <= 1e-4, f"for step {step}"
assert (
obs1_3.gen_p[gen_id] <= ratio_max * obs1_3.gen_pmax[gen_id] + 1e-5
), f"for step {step}"
amount_curtailed = np.sum(
this_prod_th - obs1_3.gen_p[self.env1.gen_renewable]
)
assert (
abs(np.sum(obs1_3.actual_dispatch) - amount_curtailed) <= 1e-4
), f"for step {step}"
if amount_curtailed == 0.0:
# test that redispatch goes back to all O when no curtailment is done
assert (
np.max(np.abs(obs1_3.actual_dispatch)) <= 1e-4
), f"for step {step}"
tested = True
assert np.all(obs1_3.curtailment[~obs1_3.gen_renewable] == 0.0)
if not tested:
raise RuntimeError(
"the case where no curtailment have been used could not be tested. Please consider "
"making another test"
)
def test_change_curtailment(self):
"""test that i can change the curtailment, cancel it, redo it etc."""
gen_id = 2
ratios_max = [
0.25,
0.24,
0.23,
0.18,
0.29,
0.19,
0.05,
0.2,
0.3,
1.0,
] # don't change it
n_steps = 100 # don't change it
acts = []
for ratio in ratios_max:
acts.append(self.env1.action_space({"curtail": [(gen_id, ratio)]}))
self.env1.step(self.env2.action_space())
self.env2.step(self.env2.action_space())
tested = False
for step in range(n_steps):
li_id = step // 10
ratio_max = ratios_max[li_id]
obs1_3, reward1_3, done1_3, info1_3 = self.env1.step(acts[li_id])
obs2_3, reward2_3, done2_3, info2_3 = self.env2.step(
self.env2.action_space()
)
if done1_3 or done2_3:
raise RuntimeError("Environment did game over, this is not normal")
if info1_3["exception"]:
raise RuntimeError("Exception for info1_3")
if info2_3["exception"]:
raise RuntimeError("Exception for info2_3")
assert (
abs(
np.sum(obs1_3.actual_dispatch)
+ (obs1_3.gen_p[gen_id] - obs2_3.gen_p[gen_id])
)
<= 1e-4
), f"for step {step}"
this_prod_th = obs1_3.gen_p_before_curtail[self.env1.gen_renewable]
th_prod = obs2_3.gen_p[self.env1.gen_renewable]
assert np.max(np.abs(this_prod_th - th_prod)) <= 1e-4, f"for step {step}"
assert (
obs1_3.gen_p[gen_id] <= ratio_max * obs1_3.gen_pmax[gen_id] + 1e-5
), f"for step {step}"
amount_curtailed = np.sum(
this_prod_th - obs1_3.gen_p[self.env1.gen_renewable]
)
assert (
abs(np.sum(obs1_3.actual_dispatch) - amount_curtailed) <= 1e-4
), f"for step {step}"
if amount_curtailed == 0.0:
# test that redispatch goes back to all O when no curtailment is done
assert (
np.max(np.abs(obs1_3.actual_dispatch)) <= 1e-4
), f"for step {step}"
tested = True
assert np.all(obs1_3.curtailment[~obs1_3.gen_renewable] == 0.0)
if not tested:
raise RuntimeError(
"the case where no curtailment have been used could not be tested. Please consider "
"making another test"
)
def test_curtailment_mw_to_ratio(self):
act = self.env1.action_space()
gen_id = 2
gen_id2 = 3
amount_max_mw = 20.0
# normal test
act.curtail = act.curtailment_mw_to_ratio([(gen_id, amount_max_mw)])
assert np.array_equal(
act.curtail,
np.array([-1.0, -1.0, 0.2857143, -1.0, -1.0, -1.0], dtype=dt_float),
)
# test i can modify the feature a second time
act.curtail = act.curtailment_mw_to_ratio([(gen_id, 2.0 * amount_max_mw)])
assert np.array_equal(
act.curtail,
np.array([-1.0, -1.0, 2.0 * 0.2857143, -1.0, -1.0, -1.0], dtype=dt_float),
)
# test i modify another gen, it does not erase the first one
act.curtail = act.curtailment_mw_to_ratio([(gen_id2, 0.5 * amount_max_mw)])
assert np.array_equal(
act.curtail,
np.array(
[-1.0, -1.0, 2.0 * 0.2857143, 0.14285715, -1.0, -1.0], dtype=dt_float
),
)
# test i cannot end up with results above 1
act.curtail = act.curtailment_mw_to_ratio(
[(gen_id2, act.gen_pmax[gen_id2] + 10.0)]
)
assert np.array_equal(
act.curtail,
np.array([-1.0, -1.0, 2.0 * 0.2857143, 1.0, -1.0, -1.0], dtype=dt_float),
)
# test the property "curtail_mw"
act2 = self.env1.action_space()
act2.curtail_mw = [(gen_id, amount_max_mw)]
assert np.array_equal(
act2.curtail,
np.array([-1.0, -1.0, 0.2857143, -1.0, -1.0, -1.0], dtype=dt_float),
)
assert np.array_equal(
act2.curtail_mw,
np.array([-1.0, -1.0, amount_max_mw, -1.0, -1.0, -1.0], dtype=dt_float),
)
# test i can modify the feature a second time
act2.curtail_mw = [(gen_id, 2.0 * amount_max_mw)]
assert np.array_equal(
act2.curtail,
np.array([-1.0, -1.0, 2.0 * 0.2857143, -1.0, -1.0, -1.0], dtype=dt_float),
)
assert np.array_equal(
act2.curtail_mw,
np.array(
[-1.0, -1.0, 2.0 * amount_max_mw, -1.0, -1.0, -1.0], dtype=dt_float
),
)
# test i modify another gen, it does not erase the first one
act2.curtail_mw = [(gen_id2, 0.5 * amount_max_mw)]
assert np.array_equal(
act2.curtail,
np.array(
[-1.0, -1.0, 2.0 * 0.2857143, 0.14285715, -1.0, -1.0], dtype=dt_float
),
)
assert np.array_equal(
act2.curtail_mw,
np.array(
[-1.0, -1.0, 2.0 * amount_max_mw, 0.5 * amount_max_mw, -1.0, -1.0],
dtype=dt_float,
),
)
# test i cannot end up with results above 1
act2.curtail_mw = [(gen_id2, act2.gen_pmax[gen_id2] + 10.0)]
assert np.array_equal(
act2.curtail,
np.array([-1.0, -1.0, 2.0 * 0.2857143, 1.0, -1.0, -1.0], dtype=dt_float),
)
assert np.array_equal(
act2.curtail_mw,
np.array(
[-1.0, -1.0, 2.0 * amount_max_mw, act2.gen_pmax[gen_id2], -1.0, -1.0],
dtype=dt_float,
),
)
if __name__ == "__main__":
unittest.main()
| 11,188 | 37.582759 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Environment.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import pdb
import time
import warnings
from grid2op.tests.helper_path_test import *
from grid2op.Exceptions import *
from grid2op.Environment import Environment
from grid2op.Backend import PandaPowerBackend
from grid2op.Parameters import Parameters
from grid2op.Chronics import ChronicsHandler, GridStateFromFile, ChangeNothing
from grid2op.Reward import L2RPNReward
from grid2op.MakeEnv import make
from grid2op.Rules import RulesChecker, DefaultRules
from grid2op.dtypes import dt_float
DEBUG = False
PROFILE_CODE = False
if PROFILE_CODE:
import cProfile
class TestLoadingBackendPandaPower(unittest.TestCase):
def get_backend(self, detailed_infos_for_cascading_failures=True):
return PandaPowerBackend(detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures)
def setUp(self):
# powergrid
self.backend = self.get_backend(True)
self.path_matpower = PATH_DATA_TEST_PP
self.case_file = "test_case14.json"
# chronics
self.path_chron = os.path.join(PATH_CHRONICS, "chronics")
self.chronics_handler = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path_chron
)
self.tolvect = dt_float(1e-2)
self.tol_one = dt_float(1e-5)
self.id_chron_to_back_load = np.array([0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9])
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
# _parameters for the environment
self.env_params = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = Environment(
init_grid_path=os.path.join(self.path_matpower, self.case_file),
init_env_path=os.path.join(self.path_matpower, self.case_file),
backend=self.backend,
chronics_handler=self.chronics_handler,
parameters=self.env_params,
names_chronics_to_backend=self.names_chronics_to_backend,
name="test_env_env1",
)
def tearDown(self):
self.env.close()
def compare_vect(self, pred, true):
return dt_float(np.max(np.abs(pred - true))) <= self.tolvect
def test_copy_env(self):
# first copying method
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
cpy = Environment(**self.env.get_kwargs())
obs1 = cpy.reset()
obs2 = self.env.reset()
assert obs1 == obs2
# test both coppy and not copy behave the same if we do the same
obs1, reward1, done1, info1 = cpy.step(self.env.action_space())
obs2, reward2, done2, info2 = self.env.step(self.env.action_space())
assert abs(reward1 - reward2) <= self.tol_one
assert done1 == done2
assert info1.keys() == info2.keys()
for kk in info1.keys():
assert np.all(info1[kk] == info2[kk])
assert obs1 == obs2
# test they are different if we do different stuff
obs2, reward2, done2, info2 = self.env.step(
self.env.action_space({"set_line_status": [(0, -1)]})
)
obs1, reward1, done1, info1 = cpy.step(self.env.action_space())
assert obs1.line_status[0]
assert not obs2.line_status[0]
assert obs1 != obs2
# second copying method
self.env.reset()
env2 = self.env.copy()
# test both coppy and not copy behave the same if we do the same
obs1, reward1, done1, info1 = env2.step(self.env.action_space())
obs2, reward2, done2, info2 = self.env.step(self.env.action_space())
assert abs(reward1 - reward2) <= self.tol_one
assert done1 == done2
assert info1.keys() == info2.keys()
for kk in info1.keys():
assert np.all(info1[kk] == info2[kk])
assert obs1 == obs2
# test they are different if we do different stuff
obs2, reward2, done2, info2 = self.env.step(
self.env.action_space({"set_line_status": [(0, -1)]})
)
obs1, reward1, done1, info1 = env2.step(self.env.action_space())
assert obs1.line_status[0]
assert not obs2.line_status[0]
assert obs1 != obs2
# new "same obs" again after reset
obs1 = self.env.reset()
obs2 = env2.reset()
assert obs1 == obs2
def test_assign_action_space(self):
"""test that i cannot change the action_space"""
with self.assertRaises(EnvError):
self.env.action_space = self.env._action_space
def test_assign_obs_space(self):
"""test that i cannot change the observation_space"""
with self.assertRaises(EnvError):
self.env.observation_space = self.env._observation_space
def test_step_doesnt_change_action(self):
act = self.env.action_space()
act_init = copy.deepcopy(act)
res = self.env.step(act)
assert act == act_init
def test_load_env(self):
"""
Just executes the SetUp and tearDown functions.
:return:
"""
if DEBUG:
if PROFILE_CODE:
cp = cProfile.Profile()
cp.enable()
import pandapower as pp
nb_powerflow = 5000
beg_ = time.perf_counter()
for i in range(nb_powerflow):
pp.runpp(self.backend._grid)
end_ = time.perf_counter()
print(
"Time to compute {} powerflows: {:.2f}".format(
nb_powerflow, end_ - beg_
)
)
if PROFILE_CODE:
cp.disable()
cp.print_stats(sort="tottime")
pass
def test_proper_injection_at_first(self):
injs_act, *_ = self.env.backend.loads_info()
# below: row as found in the file
vect = np.array([18.8, 86.5, 44.5, 7.1, 10.4, 27.6, 8.1, 3.2, 5.6, 11.9, 13.6])
# now it's in the "backend" order (ie properly reordered)
vect = vect[self.id_chron_to_back_load]
# and now i make sure everything is working as intentended
assert self.compare_vect(injs_act, vect)
def test_proper_voltage_modification(self):
do_nothing = self.env.action_space({})
obs, reward, done, info = self.env.step(
do_nothing
) # should load the first time stamp
vect = np.array([143.9, 139.1, 0.2, 13.3, 146.0])
assert self.compare_vect(
obs.prod_v, vect
), "Production voltages setpoint have not changed at first time step"
obs, reward, done, info = self.env.step(
do_nothing
) # should load the first time stamp
vect = np.array([145.3, 140.4, 0.2, 13.5, 147.4])
assert self.compare_vect(
obs.prod_v, vect
), "Production voltages setpoint have not changed at second time step"
def test_number_of_timesteps(self):
for i in range(287):
do_nothing = self.env.action_space({})
obs, reward, done, info = self.env.step(
do_nothing
) # should load the first time stamp
injs_act, *_ = self.env.backend.loads_info()
vect = np.array([19.0, 87.9, 44.4, 7.2, 10.4, 27.5, 8.4, 3.2, 5.7, 12.2, 13.6])
vect = vect[self.id_chron_to_back_load]
assert self.compare_vect(injs_act, vect)
def test_stop_right_time(self):
done = False
i = 0
while not done:
do_nothing = self.env.action_space({})
obs, reward, done, info = self.env.step(
do_nothing
) # should load the first time stamp
i += 1
assert i == 287
def test_reward(self):
done = False
i = 0
self.chronics_handler.next_chronics()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = Environment(
init_grid_path=os.path.join(self.path_matpower, self.case_file),
backend=self.get_backend(),
init_env_path=os.path.join(self.path_matpower, self.case_file),
chronics_handler=self.chronics_handler,
parameters=self.env_params,
rewardClass=L2RPNReward,
names_chronics_to_backend=self.names_chronics_to_backend,
name="test_env_env2",
)
if PROFILE_CODE:
cp = cProfile.Profile()
cp.enable()
beg_ = time.perf_counter()
cum_reward = dt_float(0.0)
do_nothing = self.env.action_space({})
while not done:
obs, reward, done, info = self.env.step(
do_nothing
) # should load the first time stamp
cum_reward += reward
i += 1
end_ = time.perf_counter()
if DEBUG:
msg_ = (
"\nEnv: {:.2f}s\n\t - apply act {:.2f}s\n\t - run pf: {:.2f}s\n"
"\t - env update + observation: {:.2f}s\nTotal time: {:.2f}\nCumulative reward: {:1f}"
)
print(
msg_.format(
self.env._time_apply_act
+ self.env._time_powerflow
+ self.env._time_extract_obs,
self.env._time_apply_act,
self.env._time_powerflow,
self.env._time_extract_obs,
end_ - beg_,
cum_reward,
)
)
if PROFILE_CODE:
cp.disable()
cp.print_stats(sort="tottime")
assert i == 287, "Wrong number of timesteps"
expected_reward = dt_float(5719.9336)
assert (
dt_float(np.abs(cum_reward - expected_reward)) <= self.tol_one
), "Wrong reward"
class TestIllegalAmbiguous(unittest.TestCase):
"""
This function test that the behaviour of "step" is the one we want: it does nothing if an action if ambiguous
or illegal
"""
def setUp(self):
# powergrid
self.tolvect = 1e-2
self.tol_one = 1e-4
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case5_example", test=True)
def tearDown(self):
self.env.close()
def compare_vect(self, pred, true):
return np.max(np.abs(pred - true)) <= self.tolvect
def test_ambiguous_detected(self):
self.skipTest(
"deprecated test as the reconnection is handled by backend action"
)
act = self.env.action_space({"set_line_status": [(1, 1)]})
obs, reward, done, info = self.env.step(act)
assert info["is_ambiguous"]
assert not info["is_illegal"]
def test_notambiguous_correct(self):
act = self.env.action_space({"set_line_status": [(1, -1)]})
obs, reward, done, info = self.env.step(act)
assert not info["is_ambiguous"]
assert not info["is_illegal"]
assert np.sum(obs.line_status) == 7
def test_illegal_detected(self):
act = self.env.action_space({"set_line_status": [(1, -1)]})
self.env.game_rules = RulesChecker(legalActClass=DefaultRules)
self.env._times_before_line_status_actionable[1] = 1
obs, reward, done, info = self.env.step(act)
# the action is illegal and it has not been implemented on the powergrid
assert not info["is_ambiguous"]
assert info["is_illegal"]
assert np.sum(obs.line_status) == 8
class TestOtherReward(unittest.TestCase):
"""
This function test that the behaviour of "step" is the one we want: it does nothing if an action if ambiguous
or illegal
"""
def setUp(self):
# powergrid
self.tolvect = 1e-2
self.tol_one = 1e-4
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case5_example",
test=True,
reward_class=L2RPNReward,
other_rewards={"test": L2RPNReward},
)
def tearDown(self):
self.env.close()
def test_make(self):
_ = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
assert "rewards" in info
assert "test" in info["rewards"]
assert np.abs(info["rewards"]["test"] - reward) <= self.tol_one
def test_simulate(self):
obs = self.env.reset()
obs_simu, reward_simu, done_simu, info_simu = obs.simulate(
self.env.action_space()
)
assert "rewards" in info_simu
assert "test" in info_simu["rewards"]
assert np.abs(info_simu["rewards"]["test"] - reward_simu) <= self.tol_one
def test_copy(self):
# https://github.com/BDonnot/lightsim2grid/issues/10
for i in range(5):
obs, reward, done, info = self.env.step(self.env.action_space())
env2 = self.env.copy()
obsnew = env2.get_obs()
assert obsnew == obs
# after the same action, the original env and its copy are the same
obs0, reward0, done0, info0 = self.env.step(self.env.action_space())
obs1, reward1, done1, info1 = env2.step(env2.action_space())
assert obs0 == obs1
assert reward0 == reward1
assert done1 == done0
# reset has the correct behaviour
obs_after = env2.reset()
obs00, reward00, done00, info00 = self.env.step(self.env.action_space())
# i did not affect the other environment
assert (
obs00.minute_of_hour
== obs0.minute_of_hour
+ self.env.chronics_handler.time_interval.seconds // 60
)
# reset read the right chronics
assert obs_after.minute_of_hour == 0
class TestResetOk(unittest.TestCase):
"""
This function test that the behaviour of "step" is the one we want: it does nothing if an action if ambiguous
or illegal
"""
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def setUp(self):
# powergrid
self.tolvect = 1e-2
self.tol_one = 1e-4
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case5_example",
test=True,
reward_class=L2RPNReward,
backend=self.make_backend(),
other_rewards={"test": L2RPNReward},
)
def tearDown(self):
self.env.close()
def test_reset_after_blackout(self):
# make the grid in bad shape
act = self.env.action_space(
{"set_bus": {"substations_id": [(2, [1, 2, 1, 2])]}}
)
obs, reward, done, info = self.env.step(act)
act = self.env.action_space(
{"set_bus": {"substations_id": [(0, [1, 1, 2, 2, 1, 2])]}}
)
obs, reward, done, info = self.env.step(act)
act = self.env.action_space(
{"set_bus": {"substations_id": [(3, [1, 1, 2, 2, 1])]}}
)
obs, reward, done, info = self.env.step(act)
act = self.env.action_space.disconnect_powerline(3)
obs, reward, done, info = self.env.step(act)
act = self.env.action_space.disconnect_powerline(4)
obs, reward, done, info = self.env.step(act)
# at this stage there is a cascading failure
assert len(info["exception"])
assert isinstance(info["exception"][0], DivergingPowerFlow)
# reset the grid
obs = self.env.reset()
assert np.all(obs.topo_vect == 1)
# check that i can simulate
simobs, simr, simdone, siminfo = obs.simulate(self.env.action_space())
assert np.all(simobs.topo_vect == 1)
def test_reset_after_blackout_withdetailed_info(self, env=None):
backend = self.make_backend(detailed_infos_for_cascading_failures=True)
if env is None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"rte_case5_example",
test=True,
reward_class=L2RPNReward,
other_rewards={"test": L2RPNReward},
backend=backend,
)
# make the grid in bad shape
act = env.action_space({"set_bus": {"substations_id": [(2, [1, 2, 1, 2])]}})
obs, reward, done, info = env.step(act)
act = env.action_space(
{"set_bus": {"substations_id": [(0, [1, 1, 2, 2, 1, 2])]}}
)
obs, reward, done, info = env.step(act)
act = env.action_space({"set_bus": {"substations_id": [(3, [1, 1, 2, 2, 1])]}})
obs, reward, done, info = env.step(act)
act = env.action_space.disconnect_powerline(3)
obs, reward, done, info = env.step(act)
obs, reward, done, info = env.step(env.action_space())
obs, reward, done, info = env.step(env.action_space())
# at this stage there is a cascading failure
assert len(info["exception"])
assert isinstance(info["exception"][0], DivergingPowerFlow)
assert "detailed_infos_for_cascading_failures" in info
assert len(info["detailed_infos_for_cascading_failures"])
# reset the grid
obs = self.env.reset()
assert np.all(obs.topo_vect == 1)
# check that i can simulate
simobs, simr, simdone, siminfo = obs.simulate(self.env.action_space())
assert np.all(simobs.topo_vect == 1)
class TestAttachLayout(unittest.TestCase):
def test_attach(self):
my_layout = [(0, 0), (0, 400), (200, 400), (400, 400), (400, 0)]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example",
test=True,
reward_class=L2RPNReward,
other_rewards={"test": L2RPNReward},
) as env:
env.attach_layout(my_layout)
act = env.action_space()
dict_act = act.cls_to_dict()
assert "grid_layout" in dict_act
assert dict_act["grid_layout"] == {
k: [x, y] for k, (x, y) in zip(env.name_sub, my_layout)
}
dict_ = env.action_space.cls_to_dict()
assert "grid_layout" in dict_
assert dict_["grid_layout"] == {
k: [x, y] for k, (x, y) in zip(env.name_sub, my_layout)
}
dict_ = env._helper_action_env.cls_to_dict()
assert "grid_layout" in dict_
assert dict_["grid_layout"] == {
k: [x, y] for k, (x, y) in zip(env.name_sub, my_layout)
}
dict_ = env.observation_space.cls_to_dict()
assert "grid_layout" in dict_
assert dict_["grid_layout"] == {
k: [x, y] for k, (x, y) in zip(env.name_sub, my_layout)
}
dict_ = env._opponent_action_space.cls_to_dict()
assert "grid_layout" in dict_
assert dict_["grid_layout"] == {
k: [x, y] for k, (x, y) in zip(env.name_sub, my_layout)
}
class TestLineChangeLastBus(unittest.TestCase):
"""
This function test that the behaviour of "step": it updates the action with the last known bus when reconnecting
"""
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.params = Parameters()
self.params.MAX_SUB_CHANGED = 1
self.params.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case14_test",
test=True,
chronics_class=ChangeNothing,
param=self.params,
)
def tearDown(self):
self.env.close()
def test_set_reconnect(self):
LINE_ID = 4
line_ex_topo = self.env.line_ex_pos_topo_vect[LINE_ID]
line_or_topo = self.env.line_or_pos_topo_vect[LINE_ID]
bus_action = self.env.action_space({"set_bus": {"lines_ex_id": [(LINE_ID, 2)]}})
set_status = self.env.action_space.get_set_line_status_vect()
set_status[LINE_ID] = -1
disconnect_action = self.env.action_space({"set_line_status": set_status})
set_status[LINE_ID] = 1
reconnect_action = self.env.action_space({"set_line_status": set_status})
obs, r, d, info = self.env.step(bus_action)
assert d is False
assert obs.topo_vect[line_ex_topo] == 2
assert obs.line_status[LINE_ID] == True
obs, r, d, _ = self.env.step(disconnect_action)
assert d is False
assert obs.line_status[LINE_ID] == False
obs, r, d, info = self.env.step(reconnect_action)
assert d is False, "Diverged powerflow on reconnection"
assert info["is_illegal"] == False, "Reconnecting should be legal"
assert obs.line_status[LINE_ID] == True, "Line is not reconnected"
# Its reconnected to bus 2, without specifying it
assert obs.topo_vect[line_ex_topo] == 2, "Line ex should be on bus 2"
def test_change_reconnect(self):
LINE_ID = 4
line_ex_topo = self.env.line_ex_pos_topo_vect[LINE_ID]
line_or_topo = self.env.line_or_pos_topo_vect[LINE_ID]
bus_action = self.env.action_space({"set_bus": {"lines_ex_id": [(LINE_ID, 2)]}})
switch_status = self.env.action_space.get_change_line_status_vect()
switch_status[LINE_ID] = True
switch_action = self.env.action_space({"change_line_status": switch_status})
obs, r, d, _ = self.env.step(bus_action)
assert d is False
assert obs.topo_vect[line_ex_topo] == 2
assert obs.line_status[LINE_ID] == True
obs, r, d, info = self.env.step(switch_action)
assert d is False
assert obs.line_status[LINE_ID] == False
obs, r, d, info = self.env.step(switch_action)
assert d is False, "Diverged powerflow on reconnection"
assert info["is_illegal"] == False, "Reconnecting should be legal"
assert obs.line_status[LINE_ID] == True, "Line is not reconnected"
# Its reconnected to bus 2, without specifying it
assert obs.topo_vect[line_ex_topo] == 2, "Line ex should be on bus 2"
class TestResetAfterCascadingFailure(unittest.TestCase):
"""
Fake a cascading failure, do a reset of an env, check that it can be loaded
"""
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
params = Parameters()
params.MAX_SUB_CHANGED = 2
self.env = make(
"rte_case14_test",
test=True,
chronics_class=ChangeNothing,
param=params,
backend=self.make_backend(),
)
def tearDown(self):
self.env.close()
def test_reset_after_cascading(self):
LINE_ID = 4
bus_action = self.env.action_space(
{"set_bus": {"lines_ex_id": [(LINE_ID, 2)], "lines_or_id": [(LINE_ID, 2)]}}
)
nothing_action = self.env.action_space({})
for i in range(3):
obs, r, d, i = self.env.step(bus_action)
# Ensure cascading happened
assert d is True
# Reset env, this shouldn't raise
self.env.reset()
# Step once
obs, r, d, i = self.env.step(nothing_action)
# Ensure stepping has been successful
assert d is False
class TestCascadingFailure(unittest.TestCase):
"""
There has been a bug preventing to reload an environment if the previous one ended with a cascading failure.
It check that here.
"""
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
params = Parameters()
params.MAX_SUB_CHANGED = 0
params.NB_TIMESTEP_POWERFLOW_ALLOWED = 2
rules = DefaultRules
self.env = make(
"rte_case14_test",
test=True,
chronics_class=ChangeNothing,
param=params,
gamerules_class=rules,
backend=self.make_backend(),
)
def tearDown(self):
self.env.close()
def test_simulate_cf(self):
thermal_limit = np.array(
[
638.28966637,
305.05042301,
17658.9674809,
26534.04334098,
10869.23856329,
4686.71726729,
15612.65903298,
300.07915572,
229.8060832,
169.97292682,
100.40192958,
265.47505664,
21193.86923911,
21216.44452327,
49701.1565287,
124.79684388,
67.59759985,
192.19424706,
666.76961936,
1113.52773632,
]
)
thermal_limit *= 2
thermal_limit[[0, 1]] /= 2.1
self.env.set_thermal_limit(thermal_limit)
obs0 = self.env.reset()
obs1, reward, done, info = self.env.step(self.env.action_space())
assert not done
obs2, reward, done, info = self.env.step(self.env.action_space())
assert not done
obs3, reward, done, info = self.env.step(self.env.action_space())
assert done
obs_new = self.env.reset()
obs1, reward, done, info = self.env.step(self.env.action_space())
assert not done
class TestLoading2envDontCrash(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env1 = make("rte_case14_test", test=True)
self.env2 = make("rte_case5_example", test=True)
def tearDown(self) -> None:
self.env1.close()
self.env2.close()
def test_loading(self):
donotghing1 = self.env1.action_space()
donotghing2 = self.env2.action_space()
assert donotghing1.n_sub == 14
assert donotghing2.n_sub == 5
obs1, *_ = self.env1.step(donotghing1)
obs2, *_ = self.env2.step(donotghing2)
assert obs1.n_sub == 14
assert obs2.n_sub == 5
class TestDeactivateForecast(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env1 = make("rte_case14_test", test=True)
def tearDown(self) -> None:
self.env1.close()
def test_deactivate_reactivate(self):
self.env1.deactivate_forecast()
obs = self.env1.reset()
# it should not be possible to use forecast
with self.assertRaises(NoForecastAvailable):
sim_obs, *_ = obs.simulate(self.env1.action_space())
# i reactivate the forecast
self.env1.reactivate_forecast()
obs, reward, done, info = self.env1.step(self.env1.action_space())
# i check i can use it again
sim_obs, *_ = obs.simulate(self.env1.action_space())
def _check_env_param(self, env, param):
assert env._ignore_min_up_down_times == param.IGNORE_MIN_UP_DOWN_TIME
assert env._forbid_dispatch_off == (not param.ALLOW_DISPATCH_GEN_SWITCH_OFF)
# type of power flow to play
# if True, then it will not disconnect lines above their thermal limits
assert env._no_overflow_disconnection == param.NO_OVERFLOW_DISCONNECTION
assert env._hard_overflow_threshold == param.HARD_OVERFLOW_THRESHOLD
# store actions "cooldown"
assert (
env._max_timestep_line_status_deactivated == param.NB_TIMESTEP_COOLDOWN_LINE
)
assert env._max_timestep_topology_deactivated == param.NB_TIMESTEP_COOLDOWN_SUB
assert env._nb_ts_reco == param.NB_TIMESTEP_RECONNECTION
assert np.all(
env._nb_timestep_overflow_allowed == param.NB_TIMESTEP_OVERFLOW_ALLOWED
)
# hard overflow part
assert env._env_dc == param.ENV_DC
assert np.all(
env._nb_timestep_overflow_allowed == param.NB_TIMESTEP_OVERFLOW_ALLOWED
)
assert (
env._max_timestep_line_status_deactivated == param.NB_TIMESTEP_COOLDOWN_LINE
)
def test_change_parameters_basic(self):
"""
this is basic test of the env.change_parameters() function
It only checks the right parameters are used for the environment but it do not currently
check the observation (with the cooldown for example)
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.MAX_SUB_CHANGED = 5
param.MAX_LINE_STATUS_CHANGED = 5
param.NB_TIMESTEP_COOLDOWN_LINE = 5
param.NB_TIMESTEP_COOLDOWN_SUB = 5
real_orig_param = copy.deepcopy(self.env1.parameters)
self.env1.change_parameters(param)
# parameters have not changed yet
_ = self.env1.step(self.env1.action_space())
self._check_env_param(self.env1, real_orig_param)
# reset triggers the change of parameters
self.env1.reset()
self._check_env_param(self.env1, param)
def test_change_parameters_forecast(self):
"""
this is basic test of the env.change_forecast_parameters() function
It only checks the right parameters are used for the environment (or obs_env) but it do not currently
check the observation (with the cooldown for example)
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.MAX_SUB_CHANGED = 5
param.MAX_LINE_STATUS_CHANGED = 5
param.NB_TIMESTEP_COOLDOWN_LINE = 5
param.NB_TIMESTEP_COOLDOWN_SUB = 5
param.ENV_DC = True
real_orig_param = copy.deepcopy(self.env1.parameters)
self.env1.change_forecast_parameters(param)
# in these first checks, parameters are not modified
self._check_env_param(self.env1, real_orig_param)
self._check_env_param(self.env1._observation_space.obs_env, real_orig_param)
obs, *_ = self.env1.step(self.env1.action_space())
_ = obs.simulate(self.env1.action_space())
self._check_env_param(self.env1, real_orig_param)
self._check_env_param(self.env1._observation_space.obs_env, real_orig_param)
# reset triggers the modification
obs = self.env1.reset()
_ = obs.simulate(self.env1.action_space())
self._check_env_param(self.env1, real_orig_param)
self._check_env_param(self.env1._observation_space.obs_env, param)
def test_change_parameters_forecast_fromissue_128(self):
"""
this is basic test of the env.change_forecast_parameters() function
It only checks the right parameters are used for the environment (or obs_env) but it do not currently
check the observation (with the cooldown for example)
This is the example taken from https://github.com/rte-france/Grid2Op/issues/128 (first remak)
"""
# modify the parmeters for simulate
param = Parameters()
param.MAX_SUB_CHANGED = 9999
param.MAX_LINE_STATUS_CHANGED = 9999
self.env1.change_forecast_parameters(param)
self.env1.reset()
obs, *_ = self.env1.step(self.env1.action_space())
# and you can simulate the impact of action modifying as many substation as you want, for example
act = self.env1.action_space({"set_bus": {"lines_or_id": [(0, 2), (10, 2)]}})
# this action modfies both substation 0 and substation 8
sim_o, sim_r, sim_d, sim_info = obs.simulate(act)
assert sim_info["is_illegal"] is False
class TestMaxIter(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("l2rpn_case14_sandbox", test=True)
def tearDown(self) -> None:
self.env.close()
def test_can_use_max_iter(self):
assert self.env.max_episode_duration() == 575
def test_can_change_max_iter(self):
# restrict the maximum number of iteration
self.env.set_max_iter(20)
assert self.env.max_episode_duration() == 20
# increase it again, above the maximum number of steps in the chronics
self.env.set_max_iter(580)
assert self.env.max_episode_duration() == 575
# decrease it again
self.env.set_max_iter(30)
assert self.env.max_episode_duration() == 30
# set it to infinity
self.env.set_max_iter(-1)
assert self.env.max_episode_duration() == 575
# check that it raises an error when used with wrong number
with self.assertRaises(Grid2OpException):
self.env.set_max_iter(-2)
with self.assertRaises(Grid2OpException):
self.env.set_max_iter(0)
if __name__ == "__main__":
unittest.main()
| 35,847 | 36.537173 | 116 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_EnvironmentCpy.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
# This module will test that the environment, when copied, works as expected (ie with making some basic tests
# for the results of "env.copy()"
import copy
import pdb
import time
import warnings
from grid2op.tests.helper_path_test import *
from grid2op.Reward import L2RPNReward
from grid2op.MakeEnv import make
from grid2op.tests.test_Environment import (
TestLoadingBackendPandaPower as Aux_TestLoadingBackendPandaPower,
TestIllegalAmbiguous as Aux_TestIllegalAmbiguous,
TestOtherReward as Aux_TestOtherReward,
TestResetOk as Aux_TestResetOk,
TestLineChangeLastBus as Aux_TestLineChangeLastBus,
TestResetAfterCascadingFailure as Aux_TestResetAfterCascadingFailure,
TestCascadingFailure as Aux_TestCascadingFailure,
TestLoading2envDontCrash as Aux_TestLoading2envDontCrash,
TestDeactivateForecast as Aux_TestDeactivateForecast,
TestMaxIter as Aux_TestMaxIter,
)
from grid2op.tests.test_Agent import TestAgent as Aux_TestAgent
DEBUG = False
PROFILE_CODE = False
if PROFILE_CODE:
import cProfile
class TestLoadingBackendPandaPowerCopy(Aux_TestLoadingBackendPandaPower):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestIllegalAmbiguousCopy(Aux_TestIllegalAmbiguous):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestOtherRewardCopy(Aux_TestOtherReward):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestResetOkCopy(Aux_TestResetOk):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
def test_reset_after_blackout_withdetailed_info(self, env=None):
backend = self.make_backend(detailed_infos_for_cascading_failures=True)
if env is None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"rte_case5_example",
test=True,
reward_class=L2RPNReward,
other_rewards={"test": L2RPNReward},
backend=backend,
)
super().test_reset_after_blackout_withdetailed_info(env=env.copy())
class TestLineChangeLastBusCopy(Aux_TestLineChangeLastBus):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestResetAfterCascadingFailureCopy(Aux_TestResetAfterCascadingFailure):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestCascadingFailureCopy(Aux_TestCascadingFailure):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestLoading2envDontCrashCopy(Aux_TestLoading2envDontCrash):
def setUp(self):
super().setUp()
self.env1_orig = self.env1
self.env1 = self.env1.copy()
self.env2_orig = self.env2
self.env2 = self.env2.copy()
class TestDeactivateForecastCopy(Aux_TestDeactivateForecast):
def setUp(self):
super().setUp()
self.env1_orig = self.env1
self.env1 = self.env1.copy()
class TestMaxIterCopy(Aux_TestMaxIter):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
class TestAgentCopy(Aux_TestAgent):
def setUp(self):
super().setUp()
self.env_orig = self.env
self.env = self.env.copy()
if __name__ == "__main__":
unittest.main()
| 4,123 | 29.10219 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_EpisodeData.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import tempfile
import warnings
import pdb
import grid2op
from grid2op.Agent import OneChangeThenNothing, RandomAgent
from grid2op.tests.helper_path_test import *
from grid2op.Chronics import Multifolder
from grid2op.Reward import L2RPNReward
from grid2op.Backend import PandaPowerBackend
from grid2op.Runner import Runner
from grid2op.Episode import EpisodeData
from grid2op.dtypes import dt_float
from grid2op.Agent import BaseAgent
from grid2op.Action import TopologyAction
from grid2op.Parameters import Parameters
from grid2op.MakeEnv import make
from grid2op.Opponent.BaseActionBudget import BaseActionBudget
from grid2op.Opponent import RandomLineOpponent
DEBUG = True
PATH_ADN_CHRONICS_FOLDER = os.path.abspath(
os.path.join(PATH_CHRONICS, "test_multi_chronics")
)
import warnings
warnings.simplefilter("error")
class TestEpisodeData(unittest.TestCase):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = dt_float(1e-2)
self.tol_one = dt_float(1e-5)
self.max_iter = 10
# self.real_reward = dt_float(199.99800)
self.real_reward = dt_float(179.99818)
self.init_grid_path = os.path.join(PATH_DATA_TEST_PP, "test_case14.json")
self.path_chron = PATH_ADN_CHRONICS_FOLDER
self.parameters_path = None
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
self.gridStateclass = Multifolder
self.backendClass = PandaPowerBackend
self.runner = Runner(
init_grid_path=self.init_grid_path,
init_env_path=self.init_grid_path,
path_chron=self.path_chron,
parameters_path=self.parameters_path,
names_chronics_to_backend=self.names_chronics_to_backend,
gridStateclass=self.gridStateclass,
backendClass=self.backendClass,
rewardClass=L2RPNReward,
other_rewards={"test": L2RPNReward},
max_iter=self.max_iter,
name_env="test_episodedata_env",
)
def test_load_ambiguous(self):
f = tempfile.mkdtemp()
class TestSuitAgent(BaseAgent):
def __init__(self, *args, **kwargs):
BaseAgent.__init__(self, *args, **kwargs)
def act(self, observation, reward, done=False):
# do a ambiguous action
return self.action_space(
{"set_line_status": [(0, 1)], "change_line_status": [0]}
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make("rte_case14_test", test=True) as env:
my_agent = TestSuitAgent(env.action_space)
runner = Runner(
**env.get_params_for_runner(),
agentClass=None,
agentInstance=my_agent
)
# test that the right seeds are assigned to the agent
res = runner.run(nb_episode=1, max_iter=self.max_iter, path_save=f)
episode_data = EpisodeData.from_disk(agent_path=f, name=res[0][1])
assert int(episode_data.meta["chronics_max_timestep"]) == self.max_iter
assert len(episode_data.actions) == self.max_iter
assert len(episode_data.observations) == self.max_iter + 1
assert len(episode_data.env_actions) == self.max_iter
assert len(episode_data.attacks) == self.max_iter
def test_one_episode_with_saving(self):
f = tempfile.mkdtemp()
(
episode_name,
cum_reward,
timestep,
max_ts
) = self.runner.run_one_episode(path_save=f)
episode_data = EpisodeData.from_disk(agent_path=f, name=episode_name)
assert int(episode_data.meta["chronics_max_timestep"]) == self.max_iter
assert len(episode_data.other_rewards) == self.max_iter
for other, real in zip(episode_data.other_rewards, episode_data.rewards):
assert dt_float(np.abs(other["test"] - real)) <= self.tol_one
assert (
np.abs(dt_float(episode_data.meta["cumulative_reward"]) - self.real_reward)
<= self.tol_one
)
def test_collection_wrapper_after_run(self):
OneChange = OneChangeThenNothing.gen_next(
{"set_bus": {"lines_or_id": [(1, -1)]}}
)
runner = Runner(
init_grid_path=self.init_grid_path,
init_env_path=self.init_grid_path,
path_chron=self.path_chron,
parameters_path=self.parameters_path,
names_chronics_to_backend=self.names_chronics_to_backend,
gridStateclass=self.gridStateclass,
backendClass=self.backendClass,
rewardClass=L2RPNReward,
other_rewards={"test": L2RPNReward},
max_iter=self.max_iter,
name_env="test_episodedata_env",
agentClass=OneChange,
)
_, cum_reward, timestep, max_ts, episode_data = runner.run_one_episode(
max_iter=self.max_iter, detailed_output=True
)
# Check that the type of first action is set bus
assert episode_data.actions[0].get_types()[2]
def test_len(self):
"""test i can use the function "len" of the episode data"""
f = tempfile.mkdtemp()
(
episode_name,
cum_reward,
timestep,
max_ts
) = self.runner.run_one_episode(path_save=f)
episode_data = EpisodeData.from_disk(agent_path=f, name=episode_name)
len(episode_data)
def test_3_episode_with_saving(self):
f = tempfile.mkdtemp()
res = self.runner._run_sequential(nb_episode=3, path_save=f)
for i, episode_name, cum_reward, timestep, total_ts in res:
episode_data = EpisodeData.from_disk(agent_path=f, name=episode_name)
assert int(episode_data.meta["chronics_max_timestep"]) == self.max_iter
assert (
np.abs(
dt_float(episode_data.meta["cumulative_reward"]) - self.real_reward
)
<= self.tol_one
)
def test_3_episode_3process_with_saving(self):
f = tempfile.mkdtemp()
nb_episode = 2
res = self.runner._run_parrallel(
nb_episode=nb_episode, nb_process=2, path_save=f
)
assert len(res) == nb_episode
for i, episode_name, cum_reward, timestep, total_ts in res:
episode_data = EpisodeData.from_disk(agent_path=f, name=episode_name)
assert int(episode_data.meta["chronics_max_timestep"]) == self.max_iter
assert (
np.abs(
dt_float(episode_data.meta["cumulative_reward"]) - self.real_reward
)
<= self.tol_one
)
def test_with_opponent(self):
init_budget = 1000
opponent_attack_duration = 15
opponent_attack_cooldown = 30
opponent_budget_per_ts = 0.0
opponent_action_class = TopologyAction
LINES_ATTACKED = ["1_3_3", "1_4_4", "3_6_15", "9_10_12", "11_12_13", "12_13_14"]
p = Parameters()
p.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"rte_case14_realistic",
test=True,
param=p,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_action_class=opponent_action_class,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
)
env.seed(0)
runner = Runner(**env.get_params_for_runner())
f = tempfile.mkdtemp()
res = runner.run(
nb_episode=1,
env_seeds=[4],
agent_seeds=[0],
max_iter=opponent_attack_cooldown - 1,
path_save=f,
)
episode_data = EpisodeData.from_disk(agent_path=f, name=res[0][1])
lines_impacted, subs_impacted = episode_data.attacks[0].get_topological_impact()
assert lines_impacted[3]
if __name__ == "__main__":
unittest.main()
| 10,476 | 36.960145 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_GridGraphObs.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
import networkx
import grid2op
import pdb
class TestNetworkXGraph(unittest.TestCase):
"""this class test the networkx representation of an observation."""
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_neurips_2020_track1", test=True)
self.tol = 1e-5
def test_kirchhoff(self):
"""
test kirchhoff law
in case of parallel lines
"""
obs = self.env.reset()
graph = obs.get_energy_graph()
assert isinstance(graph, networkx.Graph), "graph should be a networkx object"
ps = np.array([graph.nodes[el]["p"] for el in graph.nodes])
qs = np.array([graph.nodes[el]["q"] for el in graph.nodes])
p_out = np.zeros(ps.shape[0])
q_out = np.zeros(ps.shape[0])
for or_, ex_ in graph.edges:
me = graph.edges[(or_, ex_)]
p_out[or_] += me["p_or"]
q_out[or_] += me["q_or"]
p_out[ex_] += me["p_ex"]
q_out[ex_] += me["q_ex"]
assert np.max(np.abs(ps - p_out)) <= self.tol, "error for active flow"
assert np.max(np.abs(qs - q_out)) <= self.tol, "error for reactive flow"
def test_global_bus(self):
obs = self.env.reset()
act = self.env.action_space({"set_bus": {"substations_id": [(1, (1, 2, 1, 2, 1, 2))]}})
obs, reward, done, info = self.env.step(act)
assert not done
graph = obs.get_energy_graph()
assert len(graph.nodes) == self.env.n_sub + 1
assert (4, 36) in graph.edges
assert graph.edges[(4, 36)]["bus_or"] == 2
assert graph.edges[(4, 36)]["sub_id_or"] == 1
assert graph.edges[(4, 36)]["sub_id_ex"] == 4
assert graph.edges[(4, 36)]["node_id_or"] == 36
def test_bus_cooldown(self):
obs = self.env.reset()
act = self.env.action_space({"set_bus": {"substations_id": [(1, (1, 2, 1, 2, 1, 2))]}})
obs, reward, done, info = self.env.step(act)
assert not done
graph = obs.get_energy_graph()
assert graph.nodes[1]["cooldown"] == 3
assert graph.nodes[36]["cooldown"] == 3
def test_parrallel_lines(self):
obs = self.env.reset()
graph_init = obs.get_energy_graph()
assert (9, 16) in graph_init.edges
assert graph_init.edges[(9, 16)]["p_or"] == obs.p_or[18] + obs.p_or[19]
assert graph_init.edges[(9, 16)]["p_ex"] == obs.p_ex[18] + obs.p_ex[19]
assert graph_init.edges[(9, 16)]["v_or"] == obs.v_or[18]
assert graph_init.edges[(9, 16)]["v_ex"] == obs.v_ex[18]
assert graph_init.edges[(9, 16)]["nb_connected"] == 2
act = self.env.action_space({"set_line_status": [(19, -1)]}) # parrallel to line 18
obs, reward, done, info = self.env.step(act)
assert not done
graph = obs.get_energy_graph()
assert len(graph.edges) == len(graph_init.edges)
assert (9, 16) in graph.edges
assert graph.edges[(9, 16)]["p_or"] == obs.p_or[18]
assert graph.edges[(9, 16)]["p_ex"] == obs.p_ex[18]
assert graph.edges[(9, 16)]["v_or"] == obs.v_or[18]
assert graph.edges[(9, 16)]["v_ex"] == obs.v_ex[18]
assert graph.edges[(9, 16)]["nb_connected"] == 1, f'{graph.edges[(9, 16)]["nb_connected"]}'
def test_disconnected_line(self):
obs = self.env.reset()
graph_init = obs.get_energy_graph()
assert (2, 3) in graph_init.edges
act = self.env.action_space({"set_line_status": [(0, -1)]}) # parrallel to line 18
obs, reward, done, info = self.env.step(act)
assert not done
graph = obs.get_energy_graph()
assert (2, 3) not in graph.edges
if __name__ == "__main__":
unittest.main()
| 4,362 | 39.027523 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_GridObjects.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
# do some generic tests that can be implemented directly to test if a backend implementation can work out of the box
# with grid2op.
# see an example of test_Pandapower for how to use this suit.
import unittest
import numpy as np
import warnings
import grid2op
from grid2op.Backend.EducPandaPowerBackend import EducPandaPowerBackend
from grid2op.Exceptions import EnvError
class TestAuxFunctions(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.envref = grid2op.make(
"rte_case14_realistic",
test=True,
_add_to_name="test_gridobjects_testauxfunctions",
)
seed = 0
self.nb_test = 10
self.max_iter = 30
self.envref.seed(seed)
self.seeds = [
i for i in range(self.nb_test)
] # used for seeding environment and agent
def tearDown(self) -> None:
self.envref.close()
def test_auxilliary_func(self):
"""
test the methods _compute_sub_pos works
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
MyClass = EducPandaPowerBackend.init_grid(self.envref.backend)
backend = MyClass()
backend.n_sub = self.envref.backend.n_sub
backend.n_load = self.envref.backend.n_load
backend.n_gen = self.envref.backend.n_gen
backend.n_line = self.envref.backend.n_line
backend.gen_to_subid = self.envref.backend.gen_to_subid
backend.load_to_subid = self.envref.backend.load_to_subid
backend.line_or_to_subid = self.envref.backend.line_or_to_subid
backend.line_ex_to_subid = self.envref.backend.line_ex_to_subid
# now "hack" the class to check that the correct element are correctly implemented
bk_cls = type(backend)
# delete the attributes we want to test
bk_cls.sub_info = None
bk_cls.load_to_sub_pos = None
bk_cls.gen_to_sub_pos = None
bk_cls.line_or_to_sub_pos = None
bk_cls.line_ex_to_sub_pos = None
bk_cls.line_ex_to_sub_pos = None
bk_cls.load_pos_topo_vect = None
bk_cls.gen_pos_topo_vect = None
bk_cls.line_or_pos_topo_vect = None
bk_cls.line_ex_pos_topo_vect = None
# test that the grid is not correct now
with self.assertRaises(EnvError):
bk_cls.assert_grid_correct_cls()
# fill the _compute_sub_elements
bk_cls._compute_sub_elements()
assert np.sum(bk_cls.sub_info) == 56
assert np.all(bk_cls.sub_info == [3, 6, 4, 6, 5, 6, 3, 2, 5, 3, 3, 3, 4, 3])
# fill the *sub_pos
bk_cls._compute_sub_pos()
assert np.all(bk_cls.load_to_sub_pos == 0)
assert np.all(bk_cls.gen_to_sub_pos == [1, 1, 1, 0, 0])
assert np.all(
bk_cls.line_or_to_sub_pos
== [1, 2, 2, 3, 4, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 2, 3, 1, 0, 3]
)
assert np.all(
bk_cls.line_ex_to_sub_pos
== [5, 2, 3, 4, 3, 5, 4, 1, 2, 2, 2, 1, 2, 3, 2, 1, 4, 5, 1, 2]
)
# fill the *pos_topo_vect
backend._compute_pos_big_topo() # i test the object class here
assert np.all(
bk_cls.load_pos_topo_vect == [3, 9, 13, 19, 24, 35, 40, 43, 46, 49, 53]
)
assert np.all(bk_cls.gen_pos_topo_vect == [4, 10, 25, 33, 0])
assert np.all(
bk_cls.line_or_pos_topo_vect
== [
1,
2,
5,
6,
7,
11,
14,
26,
27,
28,
36,
37,
41,
47,
50,
15,
16,
20,
30,
38,
]
)
assert np.all(
bk_cls.line_ex_pos_topo_vect
== [
8,
21,
12,
17,
22,
18,
23,
44,
48,
51,
42,
54,
45,
52,
55,
31,
39,
29,
34,
32,
]
)
# this should pass
bk_cls.assert_grid_correct_cls()
if __name__ == "__main__":
unittest.main()
| 5,050 | 30.767296 | 116 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_GymConverter.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
# TODO test the json part but... https://github.com/openai/gym-http-api/issues/62 or https://github.com/openai/gym/issues/1841
import tempfile
import json
from grid2op.gym_compat.discrete_gym_actspace import DiscreteActSpace
from grid2op.tests.helper_path_test import *
from grid2op.Action import PlayableAction
from grid2op.dtypes import dt_float, dt_bool, dt_int
from grid2op.tests.helper_path_test import *
from grid2op.MakeEnv import make
from grid2op.Converter import IdToAct, ToVect
from grid2op.gym_compat import GymActionSpace, GymObservationSpace
from grid2op.gym_compat import GymEnv
from grid2op.gym_compat import ContinuousToDiscreteConverter
import pdb
import warnings
class BaseTestGymConverter:
def __init__(self):
self.tol = 1e-6
def _aux_test_json(self, space, obj=None):
if obj is None:
obj = space.sample()
obj_json = space.to_jsonable([obj])
# test save to json
with tempfile.TemporaryFile(mode="w") as f:
json.dump(obj_json, fp=f)
# test read from json
obj2 = space.from_jsonable(obj_json)[0]
# test they are equal
for k, v in obj2.items():
assert k in obj
tmp = obj[k]
if isinstance(tmp, (int, float, dt_float, dt_int, dt_bool, np.int64, np.int32)):
assert np.all(np.abs(float(obj[k]) - float(obj2[k])) <= self.tol)
elif len(tmp) == 1:
assert np.all(np.abs(float(obj[k]) - float(obj2[k])) <= self.tol)
else:
assert np.all(
np.abs(obj[k].astype(dt_float) - obj2[k].astype(dt_float))
<= self.tol
)
for k, v in obj.items():
assert k in obj2 # make sure every keys of obj are in obj2
class TestWithoutConverterWCCI(unittest.TestCase, BaseTestGymConverter):
def setUp(self) -> None:
BaseTestGymConverter.__init__(self)
def get_env_name(self):
return "l2rpn_wcci_2020"
def get_env_path(self):
return None
def test_creation(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
if self.get_env_path() is not None:
env_path_or_name = os.path.join(
self.get_env_path(), self.get_env_name()
)
else:
env_path_or_name = self.get_env_name()
with make(env_path_or_name, test=True) as env:
# test i can create
obs_space = GymObservationSpace(env)
act_space = GymActionSpace(env)
def test_json(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(self.get_env_name(), test=True) as env:
# test i can create
obs_space = GymObservationSpace(env)
act_space = GymActionSpace(env)
obs_space.seed(0)
act_space.seed(0)
self._aux_test_json(obs_space)
self._aux_test_json(act_space)
def test_to_from_gym_obs(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(self.get_env_name(), test=True) as env:
obs_space = GymObservationSpace(env)
obs = env.reset()
gym_obs = obs_space.to_gym(obs)
self._aux_test_json(obs_space, gym_obs)
assert obs_space.contains(gym_obs)
obs2 = obs_space.from_gym(gym_obs)
# TODO there is not reason that these 2 are equal: reset, will erase everything
# TODO whereas creating the observation
# assert obs == obs2
obs_diff, attr_diff = obs.where_different(obs2)
for el in attr_diff:
if el not in env.observation_space.attr_list_set:
# it's normal attribute are different if they are not in the original observation space
continue
assert (
el in obs.attr_list_json
), f'attribute "{el}" should be equal in obs and obs2'
for i in range(10):
obs, *_ = env.step(env.action_space())
gym_obs = obs_space.to_gym(obs)
self._aux_test_json(obs_space, gym_obs)
assert obs_space.contains(
gym_obs
), "gym space does not contain the observation for ts {}".format(i)
obs2 = obs_space.from_gym(gym_obs)
# TODO there is not reason that these 2 are equal: reset, will erase everything
# TODO whereas creating the observation
# assert obs == obs2, "obs and converted obs are not equal for ts {}".format(i)
obs_diff, attr_diff = obs.where_different(obs2)
for el in attr_diff:
if el not in env.observation_space.attr_list_set:
# it's normal attribute are different if they are not in the original observation space
continue
assert (
el in obs.attr_list_json
), f"{el} should be equal in obs and obs2 for ts {i}"
def test_to_from_gym_act(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(self.get_env_name(), test=True) as env:
act_space = GymActionSpace(env)
act = env.action_space()
gym_act = act_space.to_gym(act)
self._aux_test_json(act_space, gym_act)
assert act_space.contains(gym_act)
act2 = act_space.from_gym(gym_act)
assert act == act2
act_space.seed(0)
for i in range(10):
gym_act = act_space.sample()
act = act_space.from_gym(gym_act)
self._aux_test_json(act_space, gym_act)
gym_act2 = act_space.to_gym(act)
act2 = act_space.from_gym(gym_act2)
assert act == act2
class BaseTestConverter(BaseTestGymConverter):
def init_converter(self, env):
raise NotImplementedError()
def test_creation(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("l2rpn_wcci_2020", test=True) as env:
# test i can create
converter = self.init_converter(env)
act_space = GymActionSpace(env=env, converter=converter)
act_space.sample()
def test_json(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("l2rpn_wcci_2020", test=True) as env:
# test i can create
converter = self.init_converter(env)
act_space = GymActionSpace(env=env, converter=converter)
act_space.seed(0)
self._aux_test_json(act_space)
def test_to_from_gym_act(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("l2rpn_wcci_2020", test=True) as env:
converter = self.init_converter(env)
act_space = GymActionSpace(env=env, converter=converter)
act_space.seed(0)
converter.seed(0)
gym_act = act_space.sample()
act = act_space.from_gym(gym_act)
self._aux_test_json(act_space, gym_act)
gym_act2 = act_space.to_gym(act)
act2 = act_space.from_gym(gym_act2)
g2op_act = converter.convert_act(act)
g2op_act2 = converter.convert_act(act2)
assert g2op_act == g2op_act2
act_space.seed(0)
for i in range(10):
gym_act = act_space.sample()
act = act_space.from_gym(gym_act)
self._aux_test_json(act_space, gym_act)
gym_act2 = act_space.to_gym(act)
act2 = act_space.from_gym(gym_act2)
g2op_act = converter.convert_act(act)
g2op_act2 = converter.convert_act(act2)
assert g2op_act == g2op_act2
class TestIdToAct(unittest.TestCase, BaseTestConverter):
def init_converter(self, env):
return IdToAct(env.action_space)
def setUp(self) -> None:
BaseTestGymConverter.__init__(self)
class TestToVect(unittest.TestCase, BaseTestConverter):
def init_converter(self, env):
return ToVect(env.action_space)
def setUp(self) -> None:
BaseTestGymConverter.__init__(self)
class TestDropAttr(unittest.TestCase):
"""test the method to remove part of the attribute of the action / observation space"""
def test_keep_only_attr(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("educ_case14_redisp", test=True)
gym_env = GymEnv(env)
attr_kept = sorted(
("rho", "line_status", "actual_dispatch", "target_dispatch")
)
ob_space = gym_env.observation_space
ob_space = ob_space.keep_only_attr(attr_kept)
assert np.all(sorted(ob_space.spaces.keys()) == attr_kept)
def test_ignore_attr(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("educ_case14_redisp", test=True)
gym_env = GymEnv(env)
attr_deleted = sorted(
("rho", "line_status", "actual_dispatch", "target_dispatch")
)
ob_space = gym_env.observation_space
ob_space = ob_space.ignore_attr(attr_deleted)
for el in attr_deleted:
assert not el in ob_space.spaces
class TestContinuousToDiscrete(unittest.TestCase):
"""test the ContinuousToDiscreteConverter converter"""
def setUp(self) -> None:
self.tol = 1e-4
def test_split_in_3(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("educ_case14_redisp", test=True)
gym_env = GymEnv(env)
act_space = gym_env.action_space
act_space = act_space.reencode_space(
"redispatch",
ContinuousToDiscreteConverter(
nb_bins=3, init_space=act_space["redispatch"]
),
)
# with 3 interval like [-10, 10] (the second generator)
# should be split => 0 -> [-10, -3.33), 1 => [-3.33, 3.33), [3.33, 10.]
# test the "all 0" action (all 0 => encoded to 1, because i have 3 bins)
g2op_object = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [1, 1, 0, 0, 0, 1])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(res2 == 0.0)
# test the all 0 action, but one is not 0 (negative)
g2op_object = np.array([0.0, -3.2, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [1, 1, 0, 0, 0, 1])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(res2 == 0.0)
# test the all 0 action, but one is not 0 (positive)
g2op_object = np.array([0.0, 3.2, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [1, 1, 0, 0, 0, 1])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(res2 == 0.0)
# test one is 2
g2op_object = np.array([0.0, 3.4, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [1, 2, 0, 0, 0, 1])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(np.abs(res2 - [0.0, 5.0, 0.0, 0.0, 0.0, 0.0]) <= self.tol)
# test one is 0
g2op_object = np.array([0.0, -3.4, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [1, 0, 0, 0, 0, 1])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(np.abs(res2 - [0.0, -5.0, 0.0, 0.0, 0.0, 0.0]) <= self.tol)
def test_split_in_5(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("educ_case14_redisp", test=True)
gym_env = GymEnv(env)
act_space = gym_env.action_space
act_space = act_space.reencode_space(
"redispatch",
ContinuousToDiscreteConverter(
nb_bins=5, init_space=act_space["redispatch"]
),
)
# with 5
g2op_object = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 2, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(res2 == 0.0)
# test the all 0 action, but one is not 0 (negative)
g2op_object = np.array([0.0, -1.9, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 2, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(res2 == 0.0)
# positive side
g2op_object = np.array([0.0, 2.1, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 3, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(np.abs(res2 - [0.0, 3.33333, 0.0, 0.0, 0.0, 0.0]) <= self.tol)
g2op_object = np.array([0.0, 5.9, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 3, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(np.abs(res2 - [0.0, 3.33333, 0.0, 0.0, 0.0, 0.0]) <= self.tol)
g2op_object = np.array([0.0, 6.1, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 4, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(
np.abs(res2 - [0.0, 6.666666, 0.0, 0.0, 0.0, 0.0]) <= self.tol
)
# negative side
g2op_object = np.array([0.0, -2.1, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 1, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(np.abs(res2 - [0.0, -3.3333, 0.0, 0.0, 0.0, 0.0]) <= self.tol)
g2op_object = np.array([0.0, -5.9, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 1, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(
np.abs(res2 - [0.0, -3.33333, 0.0, 0.0, 0.0, 0.0]) <= self.tol
)
g2op_object = np.array([0.0, -6.1, 0.0, 0.0, 0.0, 0.0])
res = act_space._keys_encoding["_redispatch"].g2op_to_gym(g2op_object)
assert np.all(res == [2, 0, 0, 0, 0, 2])
res2 = act_space._keys_encoding["_redispatch"].gym_to_g2op(res)
assert np.all(
np.abs(res2 - [0.0, -6.666666, 0.0, 0.0, 0.0, 0.0]) <= self.tol
)
class TestWithoutConverterStorage(TestWithoutConverterWCCI):
def get_env_name(self):
return "educ_case14_storage"
class TestDiscreteActSpace(unittest.TestCase):
def setUp(self) -> None:
self.filenamedict = "test_action_json_educ_case14_storage.json"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.glop_env = make(
"educ_case14_storage", test=True, action_class=PlayableAction
)
def tearDown(self) -> None:
self.glop_env.close()
def test_create(self):
gym_env = GymEnv(self.glop_env)
act_space = gym_env.action_space
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
act_space = DiscreteActSpace(self.glop_env.action_space)
assert act_space.n == 690, f"{act_space.n = } instead of {690}"
def test_create_from_list(self):
path_input = os.path.join(PATH_DATA_TEST, self.filenamedict)
with open(path_input, "r") as f:
action_list = json.load(f)
gym_env = GymEnv(self.glop_env)
act_space = gym_env.action_space
act_space = DiscreteActSpace(
self.glop_env.action_space, action_list=action_list
)
assert act_space.n == 255, f"{act_space.n = } instead of {255}"
if __name__ == "__main__":
unittest.main()
| 18,294 | 41.447796 | 126 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_MakeEnv.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import os
import unittest
import warnings
import numpy as np
import pdb
from grid2op.tests.helper_path_test import PATH_CHRONICS_Make2, PATH_DATA_TEST
from grid2op.tests.helper_path_test import EXAMPLE_CHRONICSPATH, EXAMPLE_CASEFILE
from grid2op.tests.helper_data_test import (
case14_redisp_TH_LIM,
case14_test_TH_LIM,
case14_real_TH_LIM,
)
from grid2op.tests.helper_path_test import PATH_DATA_MULTIMIX
from grid2op.Exceptions import *
from grid2op.MakeEnv import make_from_dataset_path
from grid2op.MakeEnv.get_default_aux import _get_default_aux
from grid2op.MakeEnv import make
from grid2op.Backend import PandaPowerBackend
from grid2op.Parameters import Parameters
from grid2op.Chronics import Multifolder, ChangeNothing
from grid2op.Chronics import GridStateFromFile, GridStateFromFileWithForecasts
from grid2op.Action import (
BaseAction,
TopologyAction,
TopologyAndDispatchAction,
VoltageOnlyAction,
)
from grid2op.Observation import CompleteObservation
from grid2op.Reward import FlatReward, L2RPNReward, RedispReward
from grid2op.Rules import AlwaysLegal, DefaultRules
from grid2op.VoltageControler import ControlVoltageFromFile
from grid2op.Opponent import BaseOpponent
from grid2op.Environment import MultiMixEnvironment, Environment
import warnings
warnings.simplefilter("error")
class TestLoadingPredefinedEnv(unittest.TestCase):
def test_blank(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"blank",
test=True,
grid_path=EXAMPLE_CASEFILE,
chronics_class=ChangeNothing,
action_class=TopologyAndDispatchAction,
)
# test that it raises a warning because there is not layout
with self.assertRaises(UserWarning):
with warnings.catch_warnings():
warnings.filterwarnings("error")
env = make(
"blank",
test=True,
grid_path=EXAMPLE_CASEFILE,
chronics_class=ChangeNothing,
action_class=TopologyAndDispatchAction,
)
def test_case14_fromfile(self):
self.skipTest("deprecated test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_fromfile", test=True)
obs = env.reset()
def test_l2rpn_case14_sandbox_fromfile(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_case14_sandbox", test=True)
obs = env.reset()
assert env.grid_layout, "env.grid_layout is empty but should not be"
def test_case5_example(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True)
obs = env.reset()
def test_case5_redispatch_available(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
obs = env.reset()
assert env.redispatching_unit_commitment_availble == True
def test_case5_can_simulate(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
def test_case14_redisp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_redisp", test=True)
obs = env.reset()
def test_case14redisp_redispatch_available(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_redisp", test=True) as env:
obs = env.reset()
assert env.redispatching_unit_commitment_availble == True
def test_case14redisp_can_simulate(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_redisp", test=True) as env:
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
def test_case14redisp_test_thermals(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_redisp", test=True) as env:
obs = env.reset()
assert np.all(env._thermal_limit_a == case14_redisp_TH_LIM)
env.set_thermal_limit({k: 200000.0 for k in env.name_line})
assert np.all(env.get_thermal_limit() == 200000.0)
def test_init_thlim_from_dict(self):
"""
This tests that:
- can create an environment with thermal limit given as dictionary
- i can create an environment without chronics folder
- can create an environment without layout
So lots of tests here !
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
os.path.join(PATH_DATA_TEST, "5bus_example_th_lim_dict"), test=True
) as env:
obs = env.reset()
assert np.all(
env._thermal_limit_a
== [200.0, 300.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0]
)
def test_case14_realistic(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_realistic", test=True)
obs = env.reset()
def test_case14realistic_redispatch_available(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_realistic", test=True) as env:
obs = env.reset()
assert env.redispatching_unit_commitment_availble == True
def test_case14realistic_can_simulate(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_realistic", test=True) as env:
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
def test_case14realistic_test_thermals(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_realistic", test=True) as env:
obs = env.reset()
assert np.all(env._thermal_limit_a == case14_real_TH_LIM)
def test_case14_test(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_test", test=True)
obs = env.reset()
def test_case14test_redispatch_available(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
obs = env.reset()
assert env.redispatching_unit_commitment_availble == True
def test_case14test_can_simulate(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
def test_case14test_thermals(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
obs = env.reset()
assert np.all(env._thermal_limit_a == case14_test_TH_LIM)
class TestGetDefault(unittest.TestCase):
def test_give_instance_default(self):
kwargs = {}
param = _get_default_aux(
"param",
kwargs,
defaultClass=str,
defaultClassApp=str,
msg_error="bad stuff",
isclass=False,
)
assert param == str(), "This should have returned the empty string"
def test_give_instance_nodefault(self):
kwargs = {"param": "toto"}
param = _get_default_aux(
"param",
kwargs,
defaultClass=str,
defaultClassApp=str,
msg_error="bad stuff",
isclass=False,
)
assert param == "toto", 'This should have returned "toto"'
def test_give_class_default(self):
kwargs = {}
param = _get_default_aux(
"param",
kwargs,
defaultClass=str,
defaultClassApp=str,
msg_error="bad stuff",
isclass=True,
)
assert param == str, "This should have returned the empty string"
def test_give_class_nodefault(self):
kwargs = {"param": str}
param = _get_default_aux(
"param",
kwargs,
defaultClass=str,
defaultClassApp=str,
msg_error="bad stuff",
isclass=True,
)
assert param == str, 'This should have returned "toto"'
def test_use_sentinel_arg_raises(self):
with self.assertRaises(RuntimeError):
_get_default_aux("param", {}, str, _sentinel=True)
def test_class_not_instance_of_defaultClassApp_raises(self):
with self.assertRaises(EnvError):
kwargs = {"param": int}
_get_default_aux("param", kwargs, defaultClassApp=str, isclass=False)
def test_type_is_instance_raises(self):
with self.assertRaises(EnvError):
kwargs = {"param": 0}
_get_default_aux("param", kwargs, defaultClassApp=int, isclass=True)
def test_type_not_subtype_of_defaultClassApp_raises(self):
with self.assertRaises(EnvError):
kwargs = {"param": str}
_get_default_aux("param", kwargs, defaultClassApp=int, isclass=True)
def test_default_instance_and_class_raises(self):
with self.assertRaises(EnvError):
_get_default_aux(
"param",
{},
str,
defaultClass=str,
defaultinstance="strinstance",
isclass=False,
)
def test_default_instance_with_build_kwargs_raises(self):
with self.assertRaises(EnvError):
_get_default_aux(
"param",
{},
str,
defaultinstance="strinstance",
isclass=False,
build_kwargs=["s", "t", "r"],
)
def test_no_default_provided_raises(self):
with self.assertRaises(EnvError):
_get_default_aux(
"param", {}, str, defaultinstance=None, defaultClass=None, isclass=False
)
def test_class_with_provided_build_kwargs_raises(self):
with self.assertRaises(EnvError):
_get_default_aux(
"param",
{},
str,
defaultClass=str,
isclass=True,
build_kwargs=["s", "t", "r"],
)
def test_class_with_provided_instance_raises(self):
with self.assertRaises(EnvError):
_get_default_aux(
"param",
{},
str,
defaultClass=str,
defaultinstance="strinstance",
isclass=True,
)
class TestkwargsName(unittest.TestCase):
def test_param(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True, param=Parameters()) as env:
obs = env.reset()
def test_backend(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, backend=PandaPowerBackend()
) as env:
obs = env.reset()
def test_obsclass(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, observation_class=CompleteObservation
) as env:
obs = env.reset()
def test_gamerules(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, gamerules_class=AlwaysLegal
) as env:
obs = env.reset()
def test_chronics_path(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, chronics_path=EXAMPLE_CHRONICSPATH
) as env:
obs = env.reset()
def test_reward_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True, reward_class=FlatReward) as env:
obs = env.reset()
def test_action_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True, action_class=BaseAction) as env:
obs = env.reset()
def test_grid_path(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, grid_path=EXAMPLE_CASEFILE
) as env:
obs = env.reset()
def test_names_chronics_to_backend(self):
self.skipTest("deprecated test for now")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, names_chronics_to_backend={}
) as env:
obs = env.reset()
def test_data_feeding_kwargs(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
dict_ = {
"chronicsClass": Multifolder,
"path": EXAMPLE_CHRONICSPATH,
"gridvalueClass": GridStateFromFileWithForecasts,
}
with make("rte_case5_example", test=True, data_feeding_kwargs=dict_) as env:
obs = env.reset()
def test_chronics_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, chronics_class=Multifolder
) as env:
pass
def test_voltagecontroler_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example",
test=True,
voltagecontroler_class=ControlVoltageFromFile,
) as env:
obs = env.reset()
def test_other_rewards(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, other_rewards={"test": L2RPNReward}
) as env:
obs = env.reset()
def test_opponent_action_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, opponent_action_class=BaseAction
) as env:
obs = env.reset()
def test_opponent_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, opponent_class=BaseOpponent
) as env:
obs = env.reset()
def test_opponent_init_budget(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True, opponent_init_budget=10) as env:
obs = env.reset()
class TestMakeFromPathConfig(unittest.TestCase):
def test_case5_config(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
# Check config is loaded from config.py
assert env._rewardClass == L2RPNReward
assert issubclass(env._actionClass, TopologyAction)
assert issubclass(env._observationClass, CompleteObservation)
assert isinstance(env.backend, PandaPowerBackend)
assert env._legalActClass == DefaultRules
assert isinstance(env._voltage_controler, ControlVoltageFromFile)
assert isinstance(env.chronics_handler.real_data, Multifolder)
assert env.action_space.grid_layout != None
def test_case5_runs(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
assert env.redispatching_unit_commitment_availble == True
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
def test_case14_test_config(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
# Check config is loaded from config.py
assert env._rewardClass == RedispReward
assert issubclass(env._actionClass, TopologyAndDispatchAction)
assert issubclass(env._observationClass, CompleteObservation)
assert isinstance(env.backend, PandaPowerBackend)
assert env._legalActClass == DefaultRules
assert isinstance(env._voltage_controler, ControlVoltageFromFile)
assert isinstance(env.chronics_handler.real_data, Multifolder)
assert env.action_space.grid_layout != None
def test_case14_test_runs(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
assert env.redispatching_unit_commitment_availble == True
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
assert np.all(env._thermal_limit_a == case14_test_TH_LIM)
def test_case14_redisp_config(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_redisp")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
# Check config is loaded from config.py
assert env._rewardClass == RedispReward
assert issubclass(env._actionClass, TopologyAndDispatchAction)
assert issubclass(env._observationClass, CompleteObservation)
assert isinstance(env.backend, PandaPowerBackend)
assert env._legalActClass == DefaultRules
assert isinstance(env._voltage_controler, ControlVoltageFromFile)
assert isinstance(env.chronics_handler.real_data, Multifolder)
def test_case14_redisp_runs(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_redisp")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
assert env.redispatching_unit_commitment_availble == True
obs = env.reset()
sim_obs, reward, done, info = obs.simulate(env.action_space())
assert sim_obs != obs
assert np.all(env._thermal_limit_a == case14_redisp_TH_LIM)
def test_l2rpn19_test_config(self):
self.skipTest("l2rpn has been removed")
dataset_path = os.path.join(PATH_CHRONICS_Make2, "l2rpn_2019")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
# Check config is loaded from config.py
assert env._rewardClass == L2RPNReward
assert env._actionClass == TopologyAction
assert env._observationClass == CompleteObservation
assert isinstance(env.backend, PandaPowerBackend)
assert env._legalActClass == DefaultRules
assert isinstance(env._voltage_controler, ControlVoltageFromFile)
assert isinstance(env.chronics_handler.real_data, Multifolder)
assert env.action_space.grid_layout != None
class TestMakeFromPathConfigOverride(unittest.TestCase):
def test_case5_override_reward(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, reward_class=FlatReward) as env:
assert env._rewardClass == FlatReward
def test_case14_test_override_reward(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, reward_class=FlatReward) as env:
assert env._rewardClass == FlatReward
def test_l2rpn19_override_reward(self):
self.skipTest("l2rpn has been removed")
dataset_path = os.path.join(PATH_CHRONICS_Make2, "l2rpn_2019")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, reward_class=FlatReward) as env:
assert env._rewardClass == FlatReward
def test_case5_override_action(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, action_class=VoltageOnlyAction
) as env:
assert issubclass(env._actionClass, VoltageOnlyAction)
def test_case14_test_override_action(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, action_class=VoltageOnlyAction
) as env:
assert issubclass(env._actionClass, VoltageOnlyAction)
def test_l2rpn19_override_action(self):
self.skipTest("l2rpn has been removed")
dataset_path = os.path.join(PATH_CHRONICS_Make2, "l2rpn_2019")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, action_class=VoltageOnlyAction
) as env:
assert issubclass(env._actionClass, VoltageOnlyAction)
def test_case5_override_chronics(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, chronics_class=ChangeNothing
) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
def test_case14_test_override_chronics(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, chronics_class=ChangeNothing
) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
def test_l2rpn19_override_chronics(self):
self.skipTest("l2rpn has been removed")
dataset_path = os.path.join(PATH_CHRONICS_Make2, "l2rpn_2019")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(
dataset_path, chronics_class=ChangeNothing
) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
def test_case5_override_feed_kwargs(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case5_example")
chronics_path = os.path.join(dataset_path, "chronics", "0")
dfk = {
"chronicsClass": ChangeNothing,
"path": chronics_path,
"gridvalueClass": GridStateFromFile,
}
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, data_feeding_kwargs=dfk) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
def test_case14_test_override_feed_kwargs(self):
dataset_path = os.path.join(PATH_CHRONICS_Make2, "rte_case14_test")
chronics_path = os.path.join(dataset_path, "chronics", "0")
dfk = {
"chronicsClass": ChangeNothing,
"path": chronics_path,
"gridvalueClass": GridStateFromFile,
}
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, data_feeding_kwargs=dfk) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
def test_l2rpn19_override_feed_kwargs(self):
self.skipTest("l2rpn has been removed")
dataset_path = os.path.join(PATH_CHRONICS_Make2, "l2rpn_2019")
chronics_path = os.path.join(dataset_path, "chronics", "0000")
dfk = {
"chronicsClass": ChangeNothing,
"path": chronics_path,
"gridvalueClass": GridStateFromFile,
}
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, data_feeding_kwargs=dfk) as env:
assert isinstance(env.chronics_handler.real_data, ChangeNothing)
class TestMakeFromPathParameters(unittest.TestCase):
def test_case5_some_missing(self):
dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_some_missing")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
assert env.parameters.NB_TIMESTEP_COOLDOWN_SUB == 19
def test_case5_parameters_loading_competition(self):
dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_with_params")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path) as env:
assert env.parameters.NB_TIMESTEP_RECONNECTION == 12
def test_case5_changedparameters(self):
param = Parameters()
param.NB_TIMESTEP_RECONNECTION = 128
dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_with_params")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, param=param) as env:
assert env.parameters.NB_TIMESTEP_RECONNECTION == 128
def test_case5_changedifficulty(self):
dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_with_params")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make_from_dataset_path(dataset_path, difficulty="2") as env:
assert env.parameters.NB_TIMESTEP_RECONNECTION == 6
def test_case5_changedifficulty_raiseerror(self):
dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_with_params")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with self.assertRaises(EnvError):
with make_from_dataset_path(dataset_path, difficulty="3") as env:
assert False, "this should have raised an exception"
class TestMakeMultiMix(unittest.TestCase):
def test_create_dev(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_neurips_2020_track2", test=True)
assert env != None
assert isinstance(env, MultiMixEnvironment)
def test_create_dev_iterable(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_neurips_2020_track2", test=True)
assert env != None
assert isinstance(env, MultiMixEnvironment)
for mix in env:
assert isinstance(mix, Environment)
def test_create_from_path(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(PATH_DATA_MULTIMIX, test=True)
assert env != None
assert isinstance(env, MultiMixEnvironment)
class TestHashEnv(unittest.TestCase):
def aux_test_hash_l2rpn_case14_sandbox(self, env_name, hash_str):
from grid2op.MakeEnv.UpdateEnv import _hash_env
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(env_name, test=True)
path_ = env.get_path_env()
hash_this_env = _hash_env(path_)
assert (
hash_this_env.hexdigest()
== f"{hash_str}"
), f"wrong hash digest. It's \n\t{hash_this_env.hexdigest()}"
def test_hash_l2rpn_case14_sandbox(self):
self.aux_test_hash_l2rpn_case14_sandbox("l2rpn_case14_sandbox",
"6ebc5cd1bd8044364aab34ad21bec0533083662ad3090bdb9e88af289438eacbd7a9c22264541a7cbffac360278300f44fbb9f6874d488da26bff8e1ea4881f3")
def test_hash_educ_case14_storage(self):
# the file "storage_units_charac" was not used when hashing the environment, which was a bug
self.aux_test_hash_l2rpn_case14_sandbox("educ_case14_storage",
"c5192c21b778129ae4201ff5c992c1d7605fda26280c7267858d3e87cf03adbc15a15913355908b39a7c0839811eec399bed82714d4cd78e5fcae7d984bd641b")
if __name__ == "__main__":
unittest.main()
| 31,628 | 40.076623 | 179 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_MultiMix.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import tempfile
from grid2op.tests.helper_path_test import *
from grid2op.Environment import MultiMixEnvironment
from grid2op.Environment import BaseEnv
from grid2op.Observation import CompleteObservation
from grid2op.Parameters import Parameters
from grid2op.Reward import GameplayReward, L2RPNReward
from grid2op.Exceptions import EnvError, NoForecastAvailable
from grid2op.Backend import PandaPowerBackend
from grid2op.Opponent import BaseOpponent
from grid2op.dtypes import dt_float
import warnings
warnings.simplefilter("error")
class TestMultiMixEnvironment(unittest.TestCase):
def test_creation(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
assert mme.current_obs is not None
assert mme.current_env is not None
def test_get_path_env(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
path_mme = mme.get_path_env()
for mix in mme:
path_mix = mix.get_path_env()
assert path_mme != path_mix
assert os.path.split(path_mix)[0] == path_mme
def test_create_fail(self):
with self.assertRaises(EnvError):
mme = MultiMixEnvironment("/tmp/error")
with tempfile.TemporaryDirectory() as tmpdir:
with self.assertRaises(EnvError):
mme = MultiMixEnvironment(tmpdir)
def test_creation_with_params(self):
p = Parameters()
p.MAX_SUB_CHANGED = 666
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, param=p, _test=True)
assert mme.current_obs is not None
assert mme.current_env is not None
assert mme.parameters.MAX_SUB_CHANGED == 666
def test_creation_with_other_rewards(self):
p = Parameters()
p.NO_OVERFLOW_DISCONNECTION = True
oth_r = {
"game": GameplayReward,
"l2rpn": L2RPNReward,
}
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, param=p,
other_rewards=oth_r, _test=True)
assert mme.current_obs is not None
assert mme.current_env is not None
o, r, d, i = mme.step(mme.action_space({}))
assert i is not None
assert "rewards" in i
assert "game" in i["rewards"]
assert "l2rpn" in i["rewards"]
def test_creation_with_backend(self):
class DummyBackend1(PandaPowerBackend):
def dummy(self):
return True
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX,
backend=DummyBackend1(),
_test=True)
assert mme.current_obs is not None
assert mme.current_env is not None
for env in mme:
assert env.backend.dummy() == True
def test_creation_with_backend_are_not_shared(self):
class DummyBackend2(PandaPowerBackend):
def __init__(self, detailed_infos_for_cascading_failures=False,
can_be_copied=True,
lightsim2grid=False,
dist_slack=False,
max_iter=10,
with_numba=False):
super().__init__(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
can_be_copied=can_be_copied,
lightsim2grid=lightsim2grid,
dist_slack=dist_slack,
max_iter=max_iter,
with_numba=with_numba
)
self.calls = 0
def dummy(self):
r = self.calls
self.calls += 1
return r
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX,
backend=DummyBackend2(),
_test=True)
assert mme.current_obs is not None
assert mme.current_env is not None
for t in range(3):
for env in mme:
dummy = env.backend.dummy()
assert dummy == t
def test_creation_with_opponent(self):
mme = MultiMixEnvironment(
PATH_DATA_MULTIMIX,
opponent_class=BaseOpponent,
opponent_init_budget=42.0,
opponent_budget_per_ts=0.42,
_test=True
)
assert mme.current_obs is not None
assert mme.current_env is not None
for env in mme:
assert env._opponent_class == BaseOpponent
assert env._opponent_init_budget == dt_float(42.0)
assert env._opponent_budget_per_ts == dt_float(0.42)
def test_reset(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
mme.reset()
assert mme.current_obs is not None
assert mme.current_env is not None
def test_reset_with_params(self):
p = Parameters()
p.MAX_SUB_CHANGED = 666
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, param=p, _test=True)
mme.reset()
assert mme.current_obs is not None
assert mme.current_env is not None
assert mme.parameters.MAX_SUB_CHANGED == 666
def test_reset_with_other_rewards(self):
p = Parameters()
p.NO_OVERFLOW_DISCONNECTION = True
oth_r = {
"game": GameplayReward,
"l2rpn": L2RPNReward,
}
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, param=p,
other_rewards=oth_r, _test=True)
mme.reset()
assert mme.current_obs is not None
assert mme.current_env is not None
o, r, d, i = mme.step(mme.action_space({}))
assert i is not None
assert "rewards" in i
assert "game" in i["rewards"]
assert "l2rpn" in i["rewards"]
def test_reset_with_backend(self):
class DummyBackend3(PandaPowerBackend):
def __init__(self,
detailed_infos_for_cascading_failures=False,
can_be_copied=True,
lightsim2grid=False,
dist_slack=False,
max_iter=10,
with_numba=False
):
super().__init__(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
can_be_copied=can_be_copied,
lightsim2grid=lightsim2grid,
dist_slack=dist_slack,
max_iter=max_iter,
with_numba=with_numba
)
self._dummy = -1
def reset(self, grid_path=None, grid_filename=None):
self._dummy = 1
def dummy(self):
return self._dummy
with warnings.catch_warnings():
warnings.filterwarnings("error")
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX,
backend=DummyBackend3(),
_test=True)
mme.reset()
assert mme.current_env.backend.dummy() == 1
def test_reset_with_opponent(self):
mme = MultiMixEnvironment(
PATH_DATA_MULTIMIX,
opponent_class=BaseOpponent,
opponent_init_budget=42.0,
opponent_budget_per_ts=0.42,
_test=True,
)
mme.reset()
assert mme.current_obs is not None
assert mme.current_env is not None
assert mme._opponent_class == BaseOpponent
assert mme._opponent_init_budget == dt_float(42.0)
assert mme._opponent_budget_per_ts == dt_float(0.42)
def test_reset_seq(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for i in range(2):
assert i == mme.current_index
mme.reset()
assert mme.current_obs is not None
assert mme.current_env is not None
def test_reset_random(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for i in range(2):
mme.reset(random=True)
assert mme.current_obs is not None
assert mme.current_env is not None
def test_seeding(self):
mme1 = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
seeds_1 = mme1.seed(2)
mme1.close()
mme2 = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
seeds_2 = mme2.seed(42)
mme2.close()
mme3 = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
seeds_3 = mme3.seed(2)
mme3.close()
assert np.all(seeds_1 == seeds_3)
assert np.any(seeds_1 != seeds_2)
def test_step_dn(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
dn = mme.action_space({})
obs, r, done, info = mme.step(dn)
assert obs is not None
assert r is not None
assert isinstance(info, dict)
assert done is not True
def test_step_switch_line(self):
LINE_ID = 4
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
line_ex_topo = mme.line_ex_pos_topo_vect[LINE_ID]
line_or_topo = mme.line_or_pos_topo_vect[LINE_ID]
switch_status = mme.action_space.get_change_line_status_vect()
switch_status[LINE_ID] = True
switch_action = mme.action_space({"change_line_status": switch_status})
obs, r, d, info = mme.step(switch_action)
assert d is False
assert obs.line_status[LINE_ID] == False
obs, r, d, info = mme.step(switch_action)
assert d is False, "Diverged powerflow on reconnection"
assert info["is_illegal"] == False, "Reconnecting should be legal"
assert obs.line_status[LINE_ID] == True, "Line is not reconnected"
def test_forecast_toggle(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
dn = mme.action_space({})
# Forecast off
mme.deactivate_forecast()
# Step once
obs, _, _, _ = mme.step(dn)
# Cant simulate
with self.assertRaises(NoForecastAvailable):
obs.simulate(dn)
# Forecast ON
mme.reactivate_forecast()
# Reset, step once
mme.reset()
obs, _, _, _ = mme.step(dn)
# Can simulate
obs, r, done, info = obs.simulate(dn)
assert obs is not None
assert r is not None
assert isinstance(info, dict)
assert done is not True
def test_bracket_access_by_name(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
mix1_env = mme["case14_001"]
assert mix1_env.name == "case14_001"
mix2_env = mme["case14_002"]
assert mix2_env.name == "case14_002"
with self.assertRaises(KeyError):
unknown_env = mme["unknown_raise"]
def test_keys_access(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for k in mme.keys():
mix = mme[k]
assert mix is not None
assert isinstance(mix, BaseEnv)
assert mix.name == k
def test_values_access(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for v in mme.values():
assert v is not None
assert isinstance(v, BaseEnv)
assert v == mme[v.name]
def test_values_unique(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
vals = list(mme.values())
vals_unique = list(set(vals))
assert len(vals) == len(vals_unique)
def test_items_acces(self):
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for k, v in mme.items():
assert k is not None
assert v is not None
assert isinstance(v, BaseEnv)
assert v == mme[k]
def test_copy(self):
# https://github.com/BDonnot/lightsim2grid/issues/10
mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, _test=True)
for i in range(5):
obs, reward, done, info = mme.step(mme.action_space())
env2 = mme.copy()
obsnew = env2.get_obs()
assert obsnew == obs
# after the same action, the original env and its copy are the same
obs0, reward0, done0, info0 = mme.step(mme.action_space())
obs1, reward1, done1, info1 = env2.step(env2.action_space())
assert obs0 == obs1
assert reward0 == reward1
assert done1 == done0
# reset has the correct behaviour
obs_after = env2.reset()
obs00, reward00, done00, info00 = mme.step(mme.action_space())
# i did not affect the other environment
assert (
obs00.minute_of_hour
== obs0.minute_of_hour + mme.chronics_handler.time_interval.seconds // 60
)
# reset read the right chronics
assert obs_after.minute_of_hour == 0
if __name__ == "__main__":
unittest.main()
| 13,413 | 35.05914 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_MultiProcess.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.Environment import BaseMultiProcessEnvironment
from grid2op.Environment import SingleEnvMultiProcess
from grid2op.Environment import MultiEnvMultiProcess
from grid2op.MakeEnv import make
from grid2op.Observation import CompleteObservation
import pdb
class TestBaseMultiProcessEnvironment(unittest.TestCase):
def test_creation_multienv(self):
nb_env = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
envs = [env for _ in range(nb_env)]
multi_envs = BaseMultiProcessEnvironment(envs)
obss, rewards, dones, infos = multi_envs.step(
[env.action_space() for _ in range(multi_envs.nb_env)]
)
for ob in obss:
assert isinstance(ob, CompleteObservation)
obss = multi_envs.reset()
for ob in obss:
assert isinstance(ob, CompleteObservation)
# test some actions will not throw errors
multi_envs.set_ff(7 * 288)
multi_envs.set_chunk_size(128)
obss = multi_envs.reset()
seeds = multi_envs.get_seeds()
multi_envs.close()
def test_seeding(self):
nb_env = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
envs = [env for _ in range(nb_env)]
env.seed(2)
multi_envs1 = BaseMultiProcessEnvironment(envs)
seeds_1 = multi_envs1.get_seeds()
multi_envs1.close()
multi_envs2 = BaseMultiProcessEnvironment(envs)
seeds_2 = multi_envs2.get_seeds()
multi_envs2.close()
env.seed(2)
multi_envs3 = BaseMultiProcessEnvironment(envs)
seeds_3 = multi_envs3.get_seeds()
multi_envs3.close()
assert np.all(seeds_1 == seeds_3)
assert np.any(seeds_1 != seeds_2)
def test_simulate(self):
env_name = "l2rpn_case14_sandbox"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env1 = grid2op.make(env_name, test=True)
env2 = grid2op.make(env_name, test=True)
multi_env = BaseMultiProcessEnvironment([env1, env2])
obss = multi_env.reset()
# simulate
actions = [env1.action_space(), env2.action_space()]
sim_obss, sim_rs, sim_ds, sim_is = multi_env.simulate(actions)
multi_env.close()
env1.close()
env2.close()
class TestSingleEnvMultiProcess(unittest.TestCase):
def test_creation_multienv(self):
nb_env = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
multi_envs = SingleEnvMultiProcess(env=env, nb_env=nb_env)
obss, rewards, dones, infos = multi_envs.step(
[env.action_space() for _ in range(multi_envs.nb_env)]
)
for ob in obss:
assert isinstance(ob, CompleteObservation)
obss = multi_envs.reset()
for ob in obss:
assert isinstance(ob, CompleteObservation)
# test some actions will not throw errors
multi_envs.set_ff(7 * 288)
multi_envs.set_chunk_size(128)
obss = multi_envs.reset()
seeds = multi_envs.get_seeds()
multi_envs.close()
def test_seeding(self):
nb_env = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
env.seed(2)
multi_envs1 = SingleEnvMultiProcess(env=env, nb_env=nb_env)
seeds_1 = multi_envs1.get_seeds()
multi_envs1.close()
multi_envs2 = SingleEnvMultiProcess(env=env, nb_env=nb_env)
seeds_2 = multi_envs2.get_seeds()
multi_envs2.close()
env.seed(2)
multi_envs3 = SingleEnvMultiProcess(env=env, nb_env=nb_env)
seeds_3 = multi_envs3.get_seeds()
multi_envs3.close()
assert np.all(seeds_1 == seeds_3)
assert np.any(seeds_1 != seeds_2)
class TestMultiEnvMultiProcess(unittest.TestCase):
def test_creation_multienv(self):
nb_envs = [1, 1]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
envs = [env for _ in range(len(nb_envs))]
multi_envs = MultiEnvMultiProcess(envs, nb_envs)
obss, rewards, dones, infos = multi_envs.step(
[env.action_space() for _ in range(multi_envs.nb_env)]
)
for ob in obss:
assert isinstance(ob, CompleteObservation)
obss = multi_envs.reset()
for ob in obss:
assert isinstance(ob, CompleteObservation)
# test some actions will not throw errors
multi_envs.set_ff(7 * 288)
multi_envs.set_chunk_size(128)
obss = multi_envs.reset()
seeds = multi_envs.get_seeds()
multi_envs.close()
def test_seeding(self):
nb_envs = [1, 1]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
envs = [env for _ in range(len(nb_envs))]
env.seed(2)
multi_envs1 = MultiEnvMultiProcess(envs, nb_envs)
seeds_1 = multi_envs1.get_seeds()
multi_envs1.close()
multi_envs2 = MultiEnvMultiProcess(envs, nb_envs)
seeds_2 = multi_envs2.get_seeds()
multi_envs2.close()
env.seed(2)
multi_envs3 = MultiEnvMultiProcess(envs, nb_envs)
seeds_3 = multi_envs3.get_seeds()
multi_envs3.close()
assert np.all(seeds_1 == seeds_3)
assert np.any(seeds_1 != seeds_2)
if __name__ == "__main__":
unittest.main()
| 7,086 | 38.592179 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_ObsPlusAct.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.dtypes import dt_int, dt_float, dt_bool
from grid2op.Exceptions import *
from grid2op.Action import *
from grid2op.Parameters import Parameters
from grid2op.Rules import AlwaysLegal
import pdb
class BaseHelper:
"""Base class to test the method __add__ of an observation that is able to emulate the "adding" of
an action from an observation"""
def reset_without_pp_futurewarnings(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.obs = self.env.reset()
def setUp(self) -> None:
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_storage",
test=True,
action_class=self.get_act_cls(),
param=param,
gamerules_class=AlwaysLegal,
)
self.reset_without_pp_futurewarnings()
self.act = self.env.action_space()
def tearDown(self) -> None:
self.env.close()
def get_act_cls(self):
raise NotImplementedError()
def check_all_other_as_if_game_over(self, tested_obs):
obs = type(self.obs)()
obs.set_game_over()
obs.set_game_over()
for el in obs._attr_eq:
if el == "line_status":
continue
if el == "topo_vect":
continue
if getattr(obs, el).dtype == dt_float:
# TODO equal_nan throw an error now !
assert np.array_equal(
getattr(obs, el), getattr(tested_obs, el)
), f"error for {el}"
else:
assert np.array_equal(
getattr(obs, el), getattr(tested_obs, el)
), f"error for {el}"
def aux_test_action(
self,
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
):
self.reset_without_pp_futurewarnings()
res = self.obs + self.act
assert np.all(res.topo_vect == res_topo_vect_1)
assert np.all(res.line_status == res_ls_1)
self.check_all_other_as_if_game_over(res)
self.reset_without_pp_futurewarnings()
# try to deconnect a powerline
if "set_line_status" in self.act.authorized_keys:
obs, reward, done, info = self.env.step(
self.env.action_space({"set_line_status": [(1, -1)]})
)
assert not done
res2 = obs + self.act
assert np.all(res2.topo_vect == res_topo_vect_2)
assert np.all(res2.line_status == res_ls_2)
self.check_all_other_as_if_game_over(res2)
elif "change_line_status" in self.act.authorized_keys:
obs, reward, done, info = self.env.step(
self.env.action_space({"change_line_status": [1]})
)
assert not done
res2 = obs + self.act
assert np.all(res2.topo_vect == res_topo_vect_2)
assert np.all(res2.line_status == res_ls_2)
self.check_all_other_as_if_game_over(res2)
self.reset_without_pp_futurewarnings()
# try to change a substation configuration
if "set_bus" in self.act.authorized_keys:
act_step = self.env.action_space(
{"set_bus": {"substations_id": [(5, (1, 2, 1, 2, 1, 2, 1, 0))]}}
)
obs, reward, done, info = self.env.step(act_step)
assert not done
res3 = obs + self.act
assert np.all(res3.topo_vect == res_topo_vect_3)
assert np.all(res3.line_status == res_ls_3)
self.check_all_other_as_if_game_over(res3)
elif "change_bus" in self.act.authorized_keys:
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"change_bus": {
"substations_id": [
(
5,
(
False,
True,
False,
True,
False,
True,
False,
False,
),
)
]
}
}
)
)
assert not done
res3 = obs + self.act
assert np.all(res3.topo_vect == res_topo_vect_3)
assert np.all(res3.line_status == res_ls_3)
self.check_all_other_as_if_game_over(res3)
def test_dn_action(self):
"""test add do nothing action is properly implemented"""
# nothing is done, just a step
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def _aux_normal_impact(self):
# nothing is done, just a step
res_topo_vect_1 = self.obs.topo_vect
res_ls_1 = self.obs.line_status
# the action "disconnect powerline 1" is perfomed to get the obs
res_topo_vect_2 = np.ones(59, dtype=dt_int)
res_topo_vect_2[1] = -1
res_topo_vect_2[19] = -1
res_ls_2 = np.ones(20, dtype=dt_bool)
res_ls_2[1] = False
# the action "change topo of sub 5 with (1, 2, 1, 2, 1, 2, 1, 2)" is performed to get the obs
res_topo_vect_3 = np.ones(59, dtype=dt_int)
res_topo_vect_3[24:32] = (1, 2, 1, 2, 1, 2, 1, 1)
res_ls_3 = np.ones(20, dtype=dt_bool)
return (
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
)
def test_topo_set_action(self):
"""test i can add an action that do not impact the modification of the observation"""
if "set_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.set_bus = [(4, 2), (6, 2)]
# modification implied by the action
res_topo_vect_1[4] = 2
res_topo_vect_1[6] = 2
res_topo_vect_2[4] = 2
res_topo_vect_2[6] = 2
res_topo_vect_3[4] = 2
res_topo_vect_3[6] = 2
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_topo_set_action2(self):
"""test i can add an action that not impact the modification of the observation (set bus should...
set the bus)"""
if "set_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.set_bus = [(24, 2), (25, 2)]
# modification implied by the action
res_topo_vect_1[24] = 2
res_topo_vect_1[25] = 2
res_topo_vect_2[24] = 2
res_topo_vect_2[25] = 2
res_topo_vect_3[24] = 2
res_topo_vect_3[25] = 2
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_topo_set_action3(self):
"""test i can add an action that not impact the modification of the observation (set line status should
reconnect)
"""
if "set_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.line_or_set_bus = [(1, 2)]
self.act.line_ex_set_bus = [(1, 2)]
# modification implied by the action
res_topo_vect_1[1] = 2
res_topo_vect_1[19] = 2
res_topo_vect_2[1] = 2
res_topo_vect_2[19] = 2
res_topo_vect_3[1] = 2
res_topo_vect_3[19] = 2
res_ls_2[1] = True
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_topo_change_action(self):
"""test i can add an action that do not impact the modification in the observation"""
if "change_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.change_bus = [4, 6]
# modification implied by the action
res_topo_vect_1[4] = 2
res_topo_vect_1[6] = 2
res_topo_vect_2[4] = 2
res_topo_vect_2[6] = 2
res_topo_vect_3[4] = 2
res_topo_vect_3[6] = 2
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_topo_change_action2(self):
"""
test i can add an action that do impact the modification in the observation
(change substation reconfiguration)
"""
if "change_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.change_bus = [24, 25]
# modification implied by the action
res_topo_vect_1[24] = 2
res_topo_vect_1[25] = 2
res_topo_vect_2[24] = 2
res_topo_vect_2[25] = 2
res_topo_vect_3[24] = 2
res_topo_vect_3[25] = 1
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_topo_change_action3(self):
"""
test i can add an action that do impact the modification in the observation
(change a line status)
"""
if "change_bus" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
self.act.line_or_change_bus = [1]
self.act.line_ex_change_bus = [1]
# should have not impact on disconnected lines (this is why i don't modify the res_ls*)
# modification implied by the action
res_topo_vect_1[1] = 2
res_topo_vect_1[19] = 2
# for res_topo_vect2 the powerline is disconnected, changing its bus has no effect.
res_topo_vect_3[1] = 2
res_topo_vect_3[19] = 2
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_status_set_action_disco(self):
"""
test i can properly add an action were i set a powerline status
by disconnecting it
"""
if "set_line_status" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
# disconnection
l_id = 2
self.act.line_set_status = [(l_id, -1)]
# modification implied by the action
id_topo_or = self.env.line_or_pos_topo_vect[l_id]
id_topo_ex = self.env.line_ex_pos_topo_vect[l_id]
res_topo_vect_1[id_topo_or] = -1
res_topo_vect_1[id_topo_ex] = -1
res_topo_vect_2[id_topo_or] = -1
res_topo_vect_2[id_topo_ex] = -1
res_topo_vect_3[id_topo_or] = -1
res_topo_vect_3[id_topo_ex] = -1
res_ls_1[l_id] = False
res_ls_2[l_id] = False
res_ls_3[l_id] = False
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_status_set_action_reco(self):
"""
test i can properly add an action were i set a powerline status
I try to add a "reconnect" status of a disconnected powerline without specifying the bus to
which i reconnect it
"""
if "set_line_status" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
# disconnection
l_id = 1
self.act.line_set_status = [(l_id, +1)]
# modification implied by the action
id_topo_or = self.env.line_or_pos_topo_vect[l_id]
id_topo_ex = self.env.line_ex_pos_topo_vect[l_id]
# res_topo_vect_1[id_topo_or] = 1 # has no effect, line already connected
# res_topo_vect_1[id_topo_ex] = 1 # has no effect, line already connected
res_topo_vect_2[id_topo_or] = 1
res_topo_vect_2[id_topo_ex] = 1
# res_topo_vect_3[id_topo_or] = -1 # has no effect, line already connected
# res_topo_vect_3[id_topo_ex] = -1 # has no effect, line already connected
res_ls_2[l_id] = True # it has reconnected it
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# warning because i reconnect a powerline without specifying the bus
# i test here the test goes till the end
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
# now i test it properly sends the warning
with self.assertRaises(UserWarning):
with warnings.catch_warnings():
warnings.filterwarnings("error")
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_status_set_action_reco2(self):
"""
test i can properly add an action were i set a powerline status
I try to add a "reconnect" status of a disconnected powerline by specifying the bus to
which i reconnect it
"""
if "set_line_status" not in self.act.authorized_keys:
# i need to be able to change the status of powerlines
return
if "set_bus" not in self.act.authorized_keys:
# i need to be able to reconnect something to bus 2
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
# disconnection
l_id = 1
self.act.line_set_status = [(l_id, +1)]
self.act.line_or_set_bus = [(l_id, +1)]
self.act.line_ex_set_bus = [(l_id, 2)]
# modification implied by the action
id_topo_or = self.env.line_or_pos_topo_vect[l_id]
id_topo_ex = self.env.line_ex_pos_topo_vect[l_id]
res_topo_vect_1[id_topo_or] = 1
res_topo_vect_1[id_topo_ex] = 2
res_topo_vect_2[id_topo_or] = 1
res_topo_vect_2[id_topo_ex] = 2
res_topo_vect_3[id_topo_or] = 1
res_topo_vect_3[id_topo_ex] = 2
res_ls_2[l_id] = True # it has reconnected it
with warnings.catch_warnings():
warnings.filterwarnings("error")
# it should not raise because i specified the bus to which i reconnect it
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
def test_status_change_status_action(self):
"""test i can properly add an action were i change a powerline status"""
# TODO change the "no warning issued when set_bus is available"
# TODO change regular powerline (eg not powerline with id 1)
if "change_line_status" not in self.act.authorized_keys:
return
(
res_topo_vect_1,
res_topo_vect_2,
res_topo_vect_3,
res_ls_1,
res_ls_2,
res_ls_3,
) = self._aux_normal_impact()
# disconnection
l_id = 1
self.act.line_change_status = [l_id]
# modification implied by the action
id_topo_or = self.env.line_or_pos_topo_vect[l_id]
id_topo_ex = self.env.line_ex_pos_topo_vect[l_id]
res_topo_vect_1[id_topo_or] = -1 # has no effect, line already connected
res_topo_vect_1[id_topo_ex] = -1 # has no effect, line already connected
res_topo_vect_2[id_topo_or] = 1
res_topo_vect_2[id_topo_ex] = 1
res_topo_vect_3[id_topo_or] = -1 # has no effect, line already connected
res_topo_vect_3[id_topo_ex] = -1 # has no effect, line already connected
res_ls_1[l_id] = False
res_ls_2[l_id] = True # it has reconnected it
res_ls_3[l_id] = False
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# warning because i reconnect a powerline without specifying the bus
# i test here the test goes till the end
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
# now i test it properly sends the warning
with self.assertRaises(UserWarning):
with warnings.catch_warnings():
warnings.filterwarnings("error")
self.aux_test_action(
res_topo_vect_1=res_topo_vect_1,
res_ls_1=res_ls_1,
res_topo_vect_2=res_topo_vect_2,
res_ls_2=res_ls_2,
res_topo_vect_3=res_topo_vect_3,
res_ls_3=res_ls_3,
)
class TestCompleteAction(BaseHelper, HelperTests):
def get_act_cls(self):
return CompleteAction
class TestDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return DispatchAction
class TestDontAct(BaseHelper, HelperTests):
def get_act_cls(self):
return DontAct
class TestPlayableAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PlayableAction
class TestPowerlineChangeAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PowerlineChangeAction
class TestPowerlineChangeAndDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PowerlineChangeAndDispatchAction
class TestPowerlineChangeDispatchAndStorageAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PowerlineChangeDispatchAndStorageAction
class TestPowerlineSetAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PowerlineSetAction
class TestPowerlineSetAndDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return PowerlineSetAndDispatchAction
class TestTopologyAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologyAction
class TestTopologyAndDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologyAndDispatchAction
class TestTopologyChangeAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologyChangeAction
class TestTopologyChangeAndDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologyChangeAndDispatchAction
class TestTopologySetAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologySetAction
class TestTopologySetAndDispatchAction(BaseHelper, HelperTests):
def get_act_cls(self):
return TopologySetAndDispatchAction
if __name__ == "__main__":
unittest.main()
| 22,968 | 32.096542 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Observation.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import json
import tempfile
import warnings
import copy
import pdb
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.dtypes import dt_int, dt_float, dt_bool
from grid2op.Exceptions import *
from grid2op.Observation import ObservationSpace
from grid2op.Reward import (
L2RPNReward,
CloseToOverflowReward,
RedispReward,
RewardHelper,
)
from grid2op.MakeEnv import make
from grid2op.Action import CompleteAction, PlayableAction
# TODO add unit test for the proper update the backend in the observation [for now there is a "data leakage" as
# the real backend is copied when the observation is built, but i need to make a test to check that's it's properly
# copied]
# temporary deactivation of all the failing test until simulate is fixed
DEACTIVATE_FAILING_TEST = False
import warnings
warnings.simplefilter("error")
class TestBasisObsBehaviour(unittest.TestCase):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_test", test=True)
self.dict_ = {
"name_gen": ["gen_1_0", "gen_2_1", "gen_5_2", "gen_7_3", "gen_0_4"],
"name_load": [
"load_1_0",
"load_2_1",
"load_13_2",
"load_3_3",
"load_4_4",
"load_5_5",
"load_8_6",
"load_9_7",
"load_10_8",
"load_11_9",
"load_12_10",
],
"name_line": [
"0_1_0",
"0_4_1",
"8_9_2",
"8_13_3",
"9_10_4",
"11_12_5",
"12_13_6",
"1_2_7",
"1_3_8",
"1_4_9",
"2_3_10",
"3_4_11",
"5_10_12",
"5_11_13",
"5_12_14",
"3_6_15",
"3_8_16",
"4_5_17",
"6_7_18",
"6_8_19",
],
"name_sub": [
"sub_0",
"sub_1",
"sub_10",
"sub_11",
"sub_12",
"sub_13",
"sub_2",
"sub_3",
"sub_4",
"sub_5",
"sub_6",
"sub_7",
"sub_8",
"sub_9",
],
"name_storage": [],
"glop_version": grid2op.__version__,
"env_name": "rte_case14_test",
"sub_info": [3, 6, 4, 6, 5, 6, 3, 2, 5, 3, 3, 3, 4, 3],
"load_to_subid": [1, 2, 13, 3, 4, 5, 8, 9, 10, 11, 12],
"gen_to_subid": [1, 2, 5, 7, 0],
"line_or_to_subid": [
0,
0,
8,
8,
9,
11,
12,
1,
1,
1,
2,
3,
5,
5,
5,
3,
3,
4,
6,
6,
],
"line_ex_to_subid": [
1,
4,
9,
13,
10,
12,
13,
2,
3,
4,
3,
4,
10,
11,
12,
6,
8,
5,
7,
8,
],
"storage_to_subid": [],
"load_to_sub_pos": [5, 3, 2, 5, 4, 5, 4, 2, 2, 2, 3],
"gen_to_sub_pos": [4, 2, 4, 1, 2],
"line_or_to_sub_pos": [
0,
1,
0,
1,
1,
0,
1,
1,
2,
3,
1,
2,
0,
1,
2,
3,
4,
3,
1,
2,
],
"line_ex_to_sub_pos": [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1,
1,
2,
1,
1,
2,
0,
2,
3,
0,
3,
],
"storage_to_sub_pos": [],
"load_pos_topo_vect": [8, 12, 55, 18, 23, 29, 39, 42, 45, 48, 52],
"gen_pos_topo_vect": [7, 11, 28, 34, 2],
"line_or_pos_topo_vect": [
0,
1,
35,
36,
41,
46,
50,
4,
5,
6,
10,
15,
24,
25,
26,
16,
17,
22,
31,
32,
],
"line_ex_pos_topo_vect": [
3,
19,
40,
53,
43,
49,
54,
9,
13,
20,
14,
21,
44,
47,
51,
30,
37,
27,
33,
38,
],
"storage_pos_topo_vect": [],
"gen_type": ["nuclear", "thermal", "solar", "wind", "thermal"],
"gen_pmin": [0.0, 0.0, 0.0, 0.0, 0.0],
"gen_pmax": [200.0, 200.0, 40.0, 70.0, 400.0],
"gen_redispatchable": [True, True, False, False, True],
"gen_renewable": [False, False, True, True, False],
"gen_max_ramp_up": [5.0, 10.0, 0.0, 0.0, 10.0],
"gen_max_ramp_down": [5.0, 10.0, 0.0, 0.0, 10.0],
"gen_min_uptime": [96, 4, 0, 0, 4],
"gen_min_downtime": [96, 4, 0, 0, 4],
"gen_cost_per_MW": [5.0, 10.0, 0.0, 0.0, 10.0],
"gen_startup_cost": [20.0, 2.0, 0.0, 0.0, 2.0],
"gen_shutdown_cost": [10.0, 1.0, 0.0, 0.0, 1.0],
"grid_layout": {
"sub_0": [-280.0, -81.0],
"sub_1": [-100.0, -270.0],
"sub_10": [366.0, -270.0],
"sub_11": [366.0, -54.0],
"sub_12": [-64.0, -54.0],
"sub_13": [-64.0, 54.0],
"sub_2": [450.0, 0.0],
"sub_3": [550.0, 0.0],
"sub_4": [326.0, 54.0],
"sub_5": [222.0, 108.0],
"sub_6": [79.0, 162.0],
"sub_7": [-170.0, 270.0],
"sub_8": [-64.0, 270.0],
"sub_9": [222.0, 216.0],
},
"name_shunt": ["shunt_8_0"],
"shunt_to_subid": [8],
"storage_type": [],
"storage_Emax": [],
"storage_Emin": [],
"storage_max_p_prod": [],
"storage_max_p_absorb": [],
"storage_marginal_cost": [],
"storage_loss": [],
"storage_charging_efficiency": [],
"storage_discharging_efficiency": [],
"_init_subtype": "grid2op.Observation.completeObservation.CompleteObservation",
"dim_alarms": 0,
"dim_alerts": 0,
"alarms_area_names": [],
"alarms_lines_area": {},
"alarms_area_lines": [],
"alertable_line_names": [],
"alertable_line_ids": [],
"assistant_warning_type": None,
"_PATH_ENV": None,
}
self.json_ref = {
"year": [2019],
"month": [1],
"day": [6],
"hour_of_day": [0],
"minute_of_hour": [0],
"day_of_week": [6],
"gen_p": [93.5999984741211, 75.0, 0.0, 7.599999904632568, 77.9990234375],
"gen_q": [
65.4969711303711,
98.51886749267578,
-12.746061325073242,
6.789371013641357,
3.801255941390991,
],
"gen_v": [
142.10000610351562,
142.10000610351562,
0.20000000298023224,
12.0,
142.10000610351562,
],
"load_p": [
21.200000762939453,
86.9000015258789,
15.199999809265137,
45.5,
7.300000190734863,
11.699999809265137,
29.399999618530273,
8.600000381469727,
3.5,
5.599999904632568,
13.399999618530273,
],
"load_q": [
14.899999618530273,
60.099998474121094,
10.800000190734863,
31.5,
5.099999904632568,
8.300000190734863,
20.600000381469727,
6.0,
2.4000000953674316,
3.9000000953674316,
9.399999618530273,
],
"load_v": [
142.10000610351562,
142.10000610351562,
0.19267192482948303,
133.21652221679688,
133.5172882080078,
0.20000000298023224,
0.20202238857746124,
0.1999506950378418,
0.1990993618965149,
0.19563813507556915,
0.19479265809059143,
],
"p_or": [
39.331451416015625,
38.667572021484375,
8.023938179016113,
11.87976360321045,
-0.621783435344696,
1.323334813117981,
3.6911065578460693,
29.264848709106445,
44.41638946533203,
37.75281524658203,
16.985824584960938,
-28.051433563232422,
4.144556999206543,
7.01623010635376,
16.03428840637207,
25.47538185119629,
16.228321075439453,
38.895076751708984,
-7.599999904632568,
33.075382232666016,
],
"q_or": [
-15.30455207824707,
19.10580825805664,
8.4382963180542,
10.634726524353027,
2.3168439865112305,
0.45094606280326843,
0.9515853524208069,
-8.529295921325684,
23.858327865600586,
24.905370712280273,
33.14556884765625,
3.8572652339935303,
0.13210760056972504,
4.54428768157959,
10.420299530029297,
10.74376106262207,
9.365352630615234,
43.827266693115234,
-6.606429576873779,
15.779977798461914,
],
"v_or": [
142.10000610351562,
142.10000610351562,
0.20202238857746124,
0.20202238857746124,
0.1999506950378418,
0.19563813507556915,
0.19479265809059143,
142.10000610351562,
142.10000610351562,
142.10000610351562,
142.10000610351562,
133.21652221679688,
0.20000000298023224,
0.20000000298023224,
0.20000000298023224,
133.21652221679688,
133.21652221679688,
133.5172882080078,
13.833837509155273,
13.833837509155273,
],
"a_or": [
171.47496032714844,
175.23731994628906,
33277.5390625,
45566.9609375,
6926.5302734375,
4125.82861328125,
11297.8642578125,
123.84978485107422,
204.8500518798828,
183.7598419189453,
151.32354736328125,
122.71674346923828,
11970.3818359375,
24131.24609375,
55202.73828125,
119.82522583007812,
81.20392608642578,
253.38462829589844,
420.26788330078125,
1529.4415283203125,
],
"p_ex": [
-39.034053802490234,
-37.70601272583008,
-7.978217124938965,
-11.537211418151855,
0.6268926858901978,
-1.3184539079666138,
-3.6627886295318604,
-28.885826110839844,
-43.03413772583008,
-36.650413513183594,
-16.11812973022461,
28.161354064941406,
-4.126892566680908,
-6.92333459854126,
-15.772652626037598,
-25.47538185119629,
-16.228321075439453,
-38.895076751708984,
7.599999904632568,
-33.075382232666016,
],
"q_ex": [
10.362568855285645,
-20.268247604370117,
-8.31684398651123,
-9.906070709228516,
-2.3048837184906006,
-0.44652995467185974,
-0.8939293026924133,
5.273301124572754,
-23.203140258789062,
-25.148475646972656,
-32.26323699951172,
-3.510542869567871,
-0.09511636942625046,
-4.350945949554443,
-9.905055046081543,
-9.173547744750977,
-7.482545852661133,
-36.142757415771484,
6.789371013641357,
-14.266851425170898,
],
"v_ex": [
142.10000610351562,
133.5172882080078,
0.1999506950378418,
0.19267192482948303,
0.1990993618965149,
0.19479265809059143,
0.19267192482948303,
142.10000610351562,
133.21652221679688,
133.5172882080078,
133.21652221679688,
133.5172882080078,
0.1990993618965149,
0.19563813507556915,
0.19479265809059143,
13.833837509155273,
0.20202238857746124,
0.20000000298023224,
12.0,
0.20202238857746124,
],
"a_ex": [
164.0883026123047,
185.10972595214844,
33277.5390625,
45566.9609375,
6926.5302734375,
4125.82861328125,
11297.8642578125,
119.30233764648438,
211.88955688476562,
192.20391845703125,
156.30455017089844,
122.71674346923828,
11970.3818359375,
24131.24609375,
55202.73828125,
1130.0374755859375,
51070.6328125,
153273.34375,
490.3125305175781,
102943.1796875,
],
"rho": [
0.4860054850578308,
0.4966689944267273,
0.18164825439453125,
0.2487310916185379,
0.03780904784798622,
0.3378177583217621,
0.061670344322919846,
0.3510231077671051,
0.580599308013916,
0.5208240747451782,
0.42889103293418884,
0.347811758518219,
0.06534133851528168,
0.13172243535518646,
0.3013288080692291,
0.33961644768714905,
0.23015344142913818,
0.7181591987609863,
0.15440839529037476,
0.5619240403175354,
],
"line_status": [
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
],
"timestep_overflow": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
"topo_vect": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
],
"time_before_cooldown_line": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
"time_before_cooldown_sub": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"time_next_maintenance": [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
],
"duration_next_maintenance": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
"target_dispatch": [0.0, 0.0, 0.0, 0.0, 0.0],
"actual_dispatch": [0.0, 0.0, 0.0, 0.0, 0.0],
"_shunt_p": [0.0],
"_shunt_q": [-17.923625946044922],
"_shunt_v": [0.20202238857746124],
"_shunt_bus": [1],
"storage_charge": [],
"storage_power_target": [],
"storage_power": [],
"gen_p_before_curtail": [0.0, 0.0, 0.0, 7.599999904632568, 0.0],
"curtailment": [0.0, 0.0, 0.0, 0.0, 0.0],
"curtailment_limit": [1.0, 1.0, 1.0, 1.0, 1.0],
"curtailment_limit_effective": [1.0, 1.0, 1.0, 1.0, 1.0],
"theta_ex": [
-1.3276801109313965,
-4.100967884063721,
-10.311812400817871,
-11.245238304138184,
-10.119081497192383,
-10.50421142578125,
-11.245238304138184,
-4.473601341247559,
-4.824699401855469,
-4.100967884063721,
-4.824699401855469,
-4.100967884063721,
-10.119081497192383,
-10.39695930480957,
-10.50421142578125,
-7.88769006729126,
-10.060456275939941,
-9.613715171813965,
-7.1114115715026855,
-10.060456275939941,
],
"theta_or": [
0.0,
0.0,
-10.060456275939941,
-10.060456275939941,
-10.311812400817871,
-10.39695930480957,
-10.50421142578125,
-1.3276801109313965,
-1.3276801109313965,
-1.3276801109313965,
-4.473601341247559,
-4.824699401855469,
-9.613715171813965,
-9.613715171813965,
-9.613715171813965,
-4.824699401855469,
-4.824699401855469,
-4.100967884063721,
-7.88769006729126,
-7.88769006729126,
],
"gen_theta": [
-1.3276801109313965,
-4.473601341247559,
-9.613715171813965,
-7.1114115715026855,
0.0,
],
"load_theta": [
-1.3276801109313965,
-4.473601341247559,
-11.245238304138184,
-4.824699401855469,
-4.100967884063721,
-9.613715171813965,
-10.060456275939941,
-10.311812400817871,
-10.119081497192383,
-10.39695930480957,
-10.50421142578125,
],
"storage_theta": [],
"_thermal_limit": [
352.8251647949219,
352.8251647949219,
183197.6875,
183197.6875,
183197.6875,
12213.1787109375,
183197.6875,
352.8251647949219,
352.8251647949219,
352.8251647949219,
352.8251647949219,
352.8251647949219,
183197.6875,
183197.6875,
183197.6875,
352.8251647949219,
352.8251647949219,
352.8251647949219,
2721.794189453125,
2721.794189453125,
],
"support_theta": [True],
"gen_margin_up": [5.0, 10.0, 0.0, 0.0, 10.0],
"gen_margin_down": [5.0, 10.0, 0.0, 0.0, 10.0],
"is_alarm_illegal": [False],
"time_since_last_alarm": [-1],
"last_alarm": [],
"attention_budget": [0.0],
"was_alarm_used_after_game_over": [False],
"current_step": [0],
"max_step": [8064],
"delta_time": [5.0],
"time_since_last_alert": [],
"active_alert": [],
"alert_duration": [],
"total_number_of_alert": [],
"time_since_last_attack": [],
"was_alert_used_after_attack": [],
"attack_under_alert": [],
}
self.dtypes = np.array(
[
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
dt_bool,
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
dt_float,
dt_float,
dt_float,
dt_float,
dt_float,
# curtailment
dt_float,
dt_float,
dt_float,
dt_float,
# alarm feature
dt_bool,
dt_int,
dt_int,
dt_float,
dt_bool,
# shunts
dt_float,
dt_float,
dt_float,
dt_int,
# steps
dt_int,
dt_int,
# delta_time
dt_float,
# gen margins
dt_float,
dt_float,
# alert feature
dt_bool,
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
dt_int,
],
dtype=object,
)
self.dtypes = np.array([np.dtype(el) for el in self.dtypes])
self.shapes = np.array(
[
1,
1,
1,
1,
1,
1,
5,
5,
5,
11,
11,
11,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
56,
20,
14,
20,
20,
5,
5,
0,
0,
0,
# curtailment
5,
5,
5,
5,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
5,
5,
# alert
0,
0,
0,
0,
0,
0,
0
]
)
self.size_obs = 429 + 4 + 4 + 2 + 1 + 10 + 5 + 0
def tearDown(self):
self.env.close()
def test_sum_shape_equal_size(self):
obs = self.env.observation_space(self.env)
assert obs.size() == np.sum(obs.shape())
def test_sub_topology(self):
"""test the sub_topology function"""
obs = self.env.observation_space(self.env)
# test in normal conditions
topo = obs.sub_topology(sub_id=1)
assert np.all(topo == 1)
# test if i fake a change in the topology
obs.topo_vect[2] = 2
topo = obs.sub_topology(sub_id=0)
assert np.array_equal(topo, [1, 1, 2])
topo = obs.sub_topology(sub_id=1)
assert np.all(topo == 1)
def test_size(self):
obs = self.env.observation_space(self.env)
obs.size()
def test_copy_space(self):
obs_space2 = self.env.observation_space.copy()
assert isinstance(obs_space2, ObservationSpace)
def test_proper_size(self):
obs = self.env.observation_space(self.env)
assert obs.size() == self.size_obs, f"{obs.size()} vs {self.size_obs}"
def test_size_observation_space(self):
assert self.env.observation_space.size() == self.size_obs, f"{self.env.observation_space.size()} vs {self.size_obs}"
def aux_test_bus_conn_mat(self, as_csr=False):
obs = self.env.observation_space(self.env)
mat1 = obs.bus_connectivity_matrix(as_csr_matrix=as_csr)
ref_mat = np.array(
[
[1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
]
)
assert np.all(mat1 == ref_mat)
def test_bus_conn_mat(self):
self.aux_test_bus_conn_mat()
def test_bus_conn_mat_twice(self):
"""test i can call twice the bus_connectivity_matrix"""
obs = self.env.observation_space(self.env)
mat1 = obs.bus_connectivity_matrix(as_csr_matrix=False)
mat2 = obs.bus_connectivity_matrix(as_csr_matrix=True)
mat3 = obs.bus_connectivity_matrix(as_csr_matrix=False)
mat4 = obs.bus_connectivity_matrix(as_csr_matrix=True)
assert np.all(mat1 == mat3)
assert np.all(mat2.todense() == mat4.todense())
assert np.all(mat1 == mat2.todense())
def test_conn_mat_twice(self):
"""test i can call twice the connectivity_matrix"""
obs = self.env.observation_space(self.env)
mat1 = obs.connectivity_matrix(as_csr_matrix=False)
mat2 = obs.connectivity_matrix(as_csr_matrix=True)
mat3 = obs.connectivity_matrix(as_csr_matrix=False)
mat4 = obs.connectivity_matrix(as_csr_matrix=True)
assert np.all(mat1 == mat3)
assert np.all(mat2.todense() == mat4.todense())
assert np.all(mat1 == mat2.todense())
def test_flow_bus_mat_twice(self):
"""test i can call twice the flow_bus_matrix (it crashed before due to a bug of a copy of an array)"""
obs = self.env.observation_space(self.env)
mat1, *_ = obs.flow_bus_matrix(as_csr_matrix=False)
mat2, *_ = obs.flow_bus_matrix(as_csr_matrix=True)
mat3, *_ = obs.flow_bus_matrix(as_csr_matrix=False)
mat4, *_ = obs.flow_bus_matrix(as_csr_matrix=True)
assert np.all(mat1 == mat3)
assert np.all(mat2.todense() == mat4.todense())
assert np.all(mat1 == mat2.todense())
def test_networkx_graph(self):
obs = self.env.observation_space(self.env)
graph = obs.get_energy_graph()
for node_id in graph.nodes:
# retrieve power (active and reactive) produced at this node
p_ = graph.nodes[node_id]["p"]
q_ = graph.nodes[node_id]["q"]
# get the edges
edges = graph.edges(node_id)
p_line = 0
q_line = 0
for (k1, k2) in edges:
if k1 < k2:
p_line += graph.edges[(k1, k2)]["p_or"]
q_line += graph.edges[(k1, k2)]["q_or"]
else:
p_line += graph.edges[(k1, k2)]["p_ex"]
q_line += graph.edges[(k1, k2)]["q_ex"]
assert abs(p_line - p_) <= 1e-5, "error for kirchoff's law for graph for P"
assert abs(q_line - q_) <= 1e-5, "error for kirchoff's law for graph for Q"
def test_bus_conn_mat_csr(self):
self.aux_test_bus_conn_mat(as_csr=True)
def test_conn_mat(self):
obs = self.env.observation_space(self.env)
mat = obs.connectivity_matrix()
ref_mat = np.array(
[
[
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
1.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
[
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
]
)
assert np.all(mat[:10, :] == ref_mat)
ind_conn = obs.topo_vect > 0
assert np.all(mat[ind_conn, ind_conn] == 1)
mat2 = obs.connectivity_matrix(as_csr_matrix=True)
assert np.all(mat2[:10, :] == ref_mat)
assert np.all(mat2[ind_conn, ind_conn] == 1)
# test disconnected element (1 disconnect)
disco_powerline = self.env.action_space()
line_id = 0
disco_powerline.line_set_status = [(line_id, -1)]
obs, reward, done, info = self.env.step(disco_powerline)
assert not done
mat3 = obs.connectivity_matrix()
lor_id = self.env.line_or_pos_topo_vect[line_id]
lex_id = self.env.line_ex_pos_topo_vect[line_id]
assert np.all(mat3[lor_id, :] == 0)
assert np.all(mat3[:, lor_id] == 0)
assert np.all(mat3[lex_id, :] == 0)
assert np.all(mat3[:, lex_id] == 0)
ind_conn = obs.topo_vect > 0
assert np.all(mat3[ind_conn, ind_conn] == 1)
mat4 = obs.connectivity_matrix(as_csr_matrix=True)
assert mat4[lor_id, :].nnz == 0
assert mat4[:, lor_id].nnz == 0
assert mat4[lex_id, :].nnz == 0
assert mat4[:, lor_id].nnz == 0
# test 2 disconnected element (check they are not connected together)
disco_powerline2 = self.env.action_space()
line_id2 = 7
disco_powerline2.line_set_status = [(line_id2, -1)]
lor_id2 = self.env.line_or_pos_topo_vect[line_id2]
lex_id2 = self.env.line_ex_pos_topo_vect[line_id2]
obs, reward, done, info = self.env.step(disco_powerline2)
assert not done
assert np.array_equal(obs.line_status[[0, 7]], [False, False])
mat5 = obs.connectivity_matrix()
assert np.all(mat5[lor_id, :] == 0)
assert np.all(mat5[:, lor_id] == 0)
assert np.all(mat5[lex_id, :] == 0)
assert np.all(mat5[:, lex_id] == 0)
assert np.all(mat5[lor_id2, :] == 0)
assert np.all(mat5[:, lor_id2] == 0)
assert np.all(mat5[lex_id2, :] == 0)
assert np.all(mat5[:, lex_id2] == 0)
mat6 = obs.connectivity_matrix(as_csr_matrix=True)
assert mat6[lor_id, :].nnz == 0
assert mat6[:, lor_id].nnz == 0
assert mat6[lex_id, :].nnz == 0
assert mat6[:, lor_id].nnz == 0
assert mat6[lor_id2, :].nnz == 0
assert mat6[:, lor_id2].nnz == 0
assert mat6[lex_id2, :].nnz == 0
assert mat6[:, lor_id2].nnz == 0
def test_copy_is_done(self):
"""make sure the attribute obs._is_done is properly copied"""
obs = self.env.observation_space(self.env)
obs._is_done = True
obs_cpy = obs.copy()
assert obs_cpy._is_done == obs._is_done
obs._is_done = False
obs_cpy = obs.copy()
assert obs_cpy._is_done == obs._is_done
def aux_test_conn_mat2(self, as_csr=False):
l_id = 0
# check line is connected, and matrix is the right size
ob0 = self.env.get_obs()
mat0 = ob0.bus_connectivity_matrix(as_csr)
assert mat0.shape == (14, 14)
assert mat0[ob0.line_or_to_subid[l_id], ob0.line_ex_to_subid[l_id]] == 1.0
assert mat0[ob0.line_ex_to_subid[l_id], ob0.line_or_to_subid[l_id]] == 1.0
# when a powerline is disconnected, check it is disconnected
obs, reward, done, info = self.env.step(
self.env.action_space({"set_line_status": [(l_id, -1)]})
)
assert not done
mat = obs.bus_connectivity_matrix(as_csr)
assert mat.shape == (14, 14)
assert mat[obs.line_or_to_subid[l_id], obs.line_ex_to_subid[l_id]] == 0.0
assert mat[obs.line_ex_to_subid[l_id], obs.line_or_to_subid[l_id]] == 0.0
# when there is a substation counts 2 buses
obs, reward, done, info = self.env.step(
self.env.action_space({"set_bus": {"lines_or_id": [(13, 2), (14, 2)]}})
)
assert not done
assert obs.bus_connectivity_matrix(as_csr).shape == (15, 15)
assert (
obs.bus_connectivity_matrix(as_csr)[14, 11] == 1.0
) # first powerline I modified
assert (
obs.bus_connectivity_matrix(as_csr)[14, 12] == 1.0
) # second powerline I modified
assert (
obs.bus_connectivity_matrix(as_csr)[5, 11] == 0.0
) # first powerline modified
assert (
obs.bus_connectivity_matrix(as_csr)[5, 12] == 0.0
) # second powerline modified
def test_conn_mat2(self):
self.aux_test_conn_mat2(as_csr=False)
def test_conn_mat2_csr(self):
self.aux_test_conn_mat2(as_csr=True)
def aux_test_conn_mat3(self, as_csr=False):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_realistic", test=True)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(7, 2), (8, 2)]}})
)
mat, (ind_lor, ind_lex) = obs.bus_connectivity_matrix(
as_csr, return_lines_index=True
)
assert mat.shape == (15, 15)
assert ind_lor[7] == 14
assert ind_lor[8] == 14
obs, reward, done, info = env.step(
env.action_space(
{"set_bus": {"lines_or_id": [(2, 2)], "lines_ex_id": [(0, 2)]}}
)
)
mat, (ind_lor, ind_lex) = obs.bus_connectivity_matrix(
as_csr, return_lines_index=True
)
assert mat.shape == (16, 16)
assert ind_lor[7] == 15
assert ind_lor[8] == 15
assert ind_lor[2] == 14
assert ind_lex[0] == 14
def test_conn_mat3(self):
self.aux_test_conn_mat3(False)
def test_conn_mat3_csr(self):
self.aux_test_conn_mat3(True)
def test_active_flow_bus_matrix(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.aux_flow_bus_matrix(active_flow=True)
def test_reactive_flow_bus_matrix(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.aux_flow_bus_matrix(active_flow=False)
def aux_flow_bus_matrix(self, active_flow):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_realistic", test=True)
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"lines_or_id": [(7, 2), (8, 2)]}})
)
mat, (load, prod, stor, ind_lor, ind_lex) = obs.flow_bus_matrix(
active_flow=active_flow, as_csr_matrix=True
)
assert mat.shape == (15, 15)
assert ind_lor[7] == 14
assert ind_lor[8] == 14
# check that kirchoff law is met
if active_flow:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_p[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.p_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
else:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_q[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.q_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
obs, reward, done, info = env.step(
env.action_space(
{"set_bus": {"lines_or_id": [(2, 2)], "lines_ex_id": [(0, 2)]}}
)
)
mat, (load, prod, stor, ind_lor, ind_lex) = obs.flow_bus_matrix(
active_flow=active_flow, as_csr_matrix=True
)
assert mat.shape == (16, 16)
assert ind_lor[7] == 15
assert ind_lor[8] == 15
assert ind_lor[2] == 14
assert ind_lex[0] == 14
# check that kirchoff law is met
if active_flow:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_p[-1]) <= self.tol_one
assert (
np.abs(mat[0, 1] - 0) <= self.tol_one
) # no powerline connect bus 0 to bus 1 now (because i changed the bus)
assert (
np.abs(mat[0, 14] + obs.p_or[0]) <= self.tol_one
) # powerline 0 now connects bus 0 and bus 14
assert (
np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
) # powerline 1 has not moved
else:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_q[-1]) <= self.tol_one
assert (
np.abs(mat[0, 1] - 0) <= self.tol_one
) # no powerline connect bus 0 to bus 1 now (because i changed the bus)
assert (
np.abs(mat[0, 14] + obs.q_or[0]) <= self.tol_one
) # powerline 0 now connects bus 0 and bus 14
assert (
np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
) # powerline 1 has not moved
env.close()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("educ_case14_storage", test=True, action_class=CompleteAction)
obs = env.reset()
mat, (load, prod, stor, ind_lor, ind_lex) = obs.flow_bus_matrix(
active_flow=active_flow, as_csr_matrix=True
)
assert mat.shape == (14, 14)
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
if active_flow:
assert np.abs(mat[0, 0] - obs.prod_p[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.p_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
else:
assert np.abs(mat[0, 0] - obs.prod_q[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.q_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
array_modif = np.array([1.5, 5.0], dtype=dt_float) * 0.0
obs, reward, done, info = env.step(
env.action_space(
{
"set_storage": array_modif,
"set_bus": {"lines_or_id": [(7, 2), (8, 2)]},
}
)
)
assert not info["exception"]
mat, (load, prod, stor, ind_lor, ind_lex) = obs.flow_bus_matrix(
active_flow=active_flow, as_csr_matrix=True
)
assert mat.shape == (15, 15)
assert ind_lor[7] == 14
assert ind_lor[8] == 14
# check that kirchoff law is met
if active_flow:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_p[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.p_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
else:
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
assert np.abs(mat[0, 0] - obs.prod_q[-1]) <= self.tol_one
assert np.abs(mat[0, 1] + obs.q_or[0]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
assert np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
obs, reward, done, info = env.step(
env.action_space(
{
"set_storage": array_modif,
"set_bus": {"lines_or_id": [(2, 2)], "lines_ex_id": [(0, 2)]},
}
)
)
mat, (load, prod, stor, ind_lor, ind_lex) = obs.flow_bus_matrix(
active_flow=active_flow, as_csr_matrix=True
)
assert mat.shape == (16, 16)
assert ind_lor[7] == 15
assert ind_lor[8] == 15
assert ind_lor[2] == 14
assert ind_lex[0] == 14
# check that kirchoff law is met
assert np.max(np.abs(mat.sum(axis=1))) <= self.tol_one
if active_flow:
assert np.abs(mat[0, 0] - obs.prod_p[-1]) <= self.tol_one
assert (
np.abs(mat[0, 1] - 0) <= self.tol_one
) # no powerline connect bus 0 to bus 1 now (because i changed the bus)
assert (
np.abs(mat[0, 14] + obs.p_or[0]) <= self.tol_one
) # powerline 0 now connects bus 0 and bus 14
assert (
np.abs(mat[0, 4] + obs.p_or[1]) <= self.tol_one
) # powerline 1 has not moved
else:
assert np.abs(mat[0, 0] - obs.prod_q[-1]) <= self.tol_one
assert (
np.abs(mat[0, 1] - 0) <= self.tol_one
) # no powerline connect bus 0 to bus 1 now (because i changed the bus)
assert (
np.abs(mat[0, 14] + obs.q_or[0]) <= self.tol_one
) # powerline 0 now connects bus 0 and bus 14
assert (
np.abs(mat[0, 4] + obs.q_or[1]) <= self.tol_one
) # powerline 1 has not moved
def test_observation_space(self):
obs = self.env.observation_space(self.env)
assert self.env.observation_space.n == obs.size()
def test_shape_correct(self):
obs = self.env.observation_space(self.env)
assert obs.shape().shape == obs.dtype().shape
assert np.all(obs.dtype() == self.dtypes)
assert np.all(obs.shape() == self.shapes)
def test_0_load_properly(self):
# this test aims at checking that everything in setUp is working properly, eg that "ObsEnv" class has enough
# information for example
pass
def test_1_generating_obs(self):
# test that helper_obs is abl to generate a valid observation
obs = self.env.observation_space(self.env)
pass
def test_2_reset(self):
# test that helper_obs is abl to generate a valid observation
obs = self.env.observation_space(self.env)
assert obs.prod_p[0] is not None
obs.reset()
assert np.all(np.isnan(obs.prod_p))
assert np.all(obs.dtype() == self.dtypes)
assert np.all(obs.shape() == self.shapes)
def test_3_reset(self):
# test that helper_obs is able to generate a valid observation
obs = self.env.observation_space(self.env)
obs2 = obs.copy()
assert obs == obs2
obs2.reset()
assert np.all(np.isnan(obs2.prod_p))
assert np.all(obs2.dtype() == self.dtypes)
assert np.all(obs2.shape() == self.shapes)
# assert obs.prod_p is not None
def test_shapes_types(self):
obs = self.env.observation_space(self.env)
dtypes = obs.dtype()
assert np.all(dtypes == self.dtypes)
shapes = obs.shape()
assert np.all(shapes == self.shapes)
def test_4_to_from_vect(self):
# test that helper_obs is able to generate a valid observation
obs = self.env.observation_space(self.env)
obs2 = self.env.observation_space(self.env)
vect = obs.to_vect()
assert vect.shape[0] == obs.size()
obs2.reset()
obs2.from_vect(vect)
assert np.all(obs.dtype() == self.dtypes)
assert np.all(obs.shape() == self.shapes)
# TODO there is not reason that these 2 are equal: reset, will erase everything
# TODO whereas creating the observation
# assert obs == obs2
obs_diff, attr_diff = obs.where_different(obs2)
for el in attr_diff:
assert el in obs.attr_list_json, f"{el} should be equal in obs and obs2"
vect2 = obs2.to_vect()
assert np.all(vect == vect2)
def test_5_simulate_proper_timestep(self):
self.skipTest(
"This is extensively tested elswhere, and the chronics have been changed."
)
obs_orig = self.env.observation_space(self.env)
action = self.env.action_space({})
action2 = self.env.action_space({})
simul_obs, simul_reward, simul_has_error, simul_info = obs_orig.simulate(action)
real_obs, real_reward, real_has_error, real_info = self.env.step(action2)
assert not real_has_error, "The powerflow diverged"
# this is not true for every observation chronics, but we made sure in this files that the forecast were
# without any noise, maintenance, nor hazards
assert (
simul_obs == real_obs
), "there is a mismatch in the observation, though they are supposed to be equal"
assert np.abs(simul_reward - real_reward) <= self.tol_one
def test_6_simulate_dont_affect_env(self):
obs_orig = self.env.observation_space(self.env)
obs_orig = obs_orig.copy()
for i in range(self.env.backend.n_line):
# simulate lots of action
tmp = np.full(self.env.backend.n_line, fill_value=False, dtype=dt_bool)
tmp[i] = True
action = self.env.action_space({"change_line_status": tmp})
simul_obs, simul_reward, simul_has_error, simul_info = obs_orig.simulate(
action
)
obs_after = self.env.observation_space(self.env)
assert obs_orig == obs_after
def test_inspect_load(self):
obs = self.env.observation_space(self.env)
dict_ = obs.state_of(load_id=0)
assert "p" in dict_
assert np.abs(dict_["p"] - 21.2) <= self.tol_one
assert "q" in dict_
assert np.abs(dict_["q"] - 14.9) <= self.tol_one
assert "v" in dict_
assert np.abs(dict_["v"] - 142.1) <= self.tol_one
assert "bus" in dict_
assert dict_["bus"] == 1
assert "sub_id" in dict_
assert dict_["sub_id"] == 1
def test_inspect_gen(self):
obs = self.env.observation_space(self.env)
dict_ = obs.state_of(gen_id=0)
assert "p" in dict_
assert np.abs(dict_["p"] - 93.6) <= self.tol_one
assert "q" in dict_
assert np.abs(dict_["q"] - 65.49697) <= self.tol_one
assert "v" in dict_
assert np.abs(dict_["v"] - 142.1) <= self.tol_one
assert "bus" in dict_
assert dict_["bus"] == 1
assert "sub_id" in dict_
assert dict_["sub_id"] == 1
def test_inspect_line(self):
obs = self.env.observation_space(self.env)
dict_both = obs.state_of(line_id=0)
assert "origin" in dict_both
dict_ = dict_both["origin"]
assert "p" in dict_
assert np.abs(dict_["p"] - 39.33145) <= self.tol_one
assert "q" in dict_
assert np.abs(dict_["q"] - -15.304552) <= self.tol_one
assert "v" in dict_
assert np.abs(dict_["v"] - 142.1) <= self.tol_one
assert "bus" in dict_
assert dict_["bus"] == 1
assert "sub_id" in dict_
assert dict_["sub_id"] == 0
assert "extremity" in dict_both
dict_ = dict_both["extremity"]
assert "p" in dict_
assert np.abs(dict_["p"] - -39.034054) <= self.tol_one
assert "q" in dict_
assert np.abs(dict_["q"] - 10.362568) <= self.tol_one
assert "v" in dict_
assert np.abs(dict_["v"] - 142.1) <= self.tol_one
assert "bus" in dict_
assert dict_["bus"] == 1
assert "sub_id" in dict_
assert dict_["sub_id"] == 1
def test_inspect_topo(self):
obs = self.env.observation_space(self.env)
dict_ = obs.state_of(substation_id=1)
assert "topo_vect" in dict_
assert np.all(dict_["topo_vect"] == [1, 1, 1, 1, 1, 1])
assert "nb_bus" in dict_
assert dict_["nb_bus"] == 1
def test_get_obj_connect_to(self):
dict_ = self.env.observation_space.get_obj_connect_to(substation_id=1)
assert "loads_id" in dict_
assert np.all(dict_["loads_id"] == 0)
assert "generators_id" in dict_
assert np.all(dict_["generators_id"] == 0)
assert "lines_or_id" in dict_
assert np.all(dict_["lines_or_id"] == [7, 8, 9])
assert "lines_ex_id" in dict_
assert np.all(dict_["lines_ex_id"] == 0)
assert "nb_elements" in dict_
assert dict_["nb_elements"] == 6
def test_space_to_dict(self):
dict_ = self.env.observation_space.cls_to_dict()
for el in dict_:
assert el in self.dict_, f"missing key {el} in self.dict_"
for el in self.dict_:
assert el in dict_, f"missing key {el} in dict_"
for el in self.dict_:
val = dict_[el]
val_res = self.dict_[el]
if val is None and val_res is not None:
raise AssertionError(f"val is None and val_res is not None: val_res: {val_res}")
if val is not None and val_res is None:
raise AssertionError(f"val is not None and val_res is None: val {val}")
if val is None and val_res is None:
continue
ok_ = np.array_equal(val, val_res)
assert ok_, (f"values different for {el}: "
f"{dict_[el]}"
f"{self.dict_[el]}")
# self.maxDiff = None
# self.assertDictEqual(dict_, self.dict_)
def test_from_dict(self):
res = ObservationSpace.from_dict(self.dict_)
assert res.n_gen == self.env.observation_space.n_gen
assert res.n_load == self.env.observation_space.n_load
assert res.n_line == self.env.observation_space.n_line
assert np.all(res.sub_info == self.env.observation_space.sub_info)
assert np.all(res.load_to_subid == self.env.observation_space.load_to_subid)
assert np.all(res.gen_to_subid == self.env.observation_space.gen_to_subid)
assert np.all(
res.line_or_to_subid == self.env.observation_space.line_or_to_subid
)
assert np.all(
res.line_ex_to_subid == self.env.observation_space.line_ex_to_subid
)
assert np.all(res.load_to_sub_pos == self.env.observation_space.load_to_sub_pos)
assert np.all(res.gen_to_sub_pos == self.env.observation_space.gen_to_sub_pos)
assert np.all(
res.line_or_to_sub_pos == self.env.observation_space.line_or_to_sub_pos
)
assert np.all(
res.line_ex_to_sub_pos == self.env.observation_space.line_ex_to_sub_pos
)
assert np.all(
res.load_pos_topo_vect == self.env.observation_space.load_pos_topo_vect
)
assert np.all(
res.gen_pos_topo_vect == self.env.observation_space.gen_pos_topo_vect
)
assert np.all(
res.line_or_pos_topo_vect
== self.env.observation_space.line_or_pos_topo_vect
)
assert np.all(
res.line_ex_pos_topo_vect
== self.env.observation_space.line_ex_pos_topo_vect
)
assert issubclass(
res.observationClass, self.env.observation_space._init_subtype
)
def test_json_serializable(self):
dict_ = self.env.observation_space.cls_to_dict()
res = json.dumps(obj=dict_, indent=4, sort_keys=True)
def test_json_loadable(self):
dict_ = self.env.observation_space.cls_to_dict()
tmp = json.dumps(obj=dict_, indent=4, sort_keys=True)
res = ObservationSpace.from_dict(json.loads(tmp))
assert res.n_gen == self.env.observation_space.n_gen
assert res.n_load == self.env.observation_space.n_load
assert res.n_line == self.env.observation_space.n_line
assert np.all(res.sub_info == self.env.observation_space.sub_info)
assert np.all(res.load_to_subid == self.env.observation_space.load_to_subid)
assert np.all(res.gen_to_subid == self.env.observation_space.gen_to_subid)
assert np.all(
res.line_or_to_subid == self.env.observation_space.line_or_to_subid
)
assert np.all(
res.line_ex_to_subid == self.env.observation_space.line_ex_to_subid
)
assert np.all(res.load_to_sub_pos == self.env.observation_space.load_to_sub_pos)
assert np.all(res.gen_to_sub_pos == self.env.observation_space.gen_to_sub_pos)
assert np.all(
res.line_or_to_sub_pos == self.env.observation_space.line_or_to_sub_pos
)
assert np.all(
res.line_ex_to_sub_pos == self.env.observation_space.line_ex_to_sub_pos
)
assert np.all(
res.load_pos_topo_vect == self.env.observation_space.load_pos_topo_vect
)
assert np.all(
res.gen_pos_topo_vect == self.env.observation_space.gen_pos_topo_vect
)
assert np.all(
res.line_or_pos_topo_vect
== self.env.observation_space.line_or_pos_topo_vect
)
assert np.all(
res.line_ex_pos_topo_vect
== self.env.observation_space.line_ex_pos_topo_vect
)
assert issubclass(
res.observationClass, self.env.observation_space._init_subtype
)
def test_to_from_json(self):
"""test the to_json, and from_json and make sure these are all json serializable"""
obs = self.env.observation_space(self.env)
obs2 = self.env.observation_space(self.env)
dict_ = obs.to_json()
# test that the right dictionary is returned
for k in dict_:
assert (
dict_[k] == self.json_ref[k]
), f"error for key {k} (in dict_): {dict_[k]} vs {self.json_ref[k]} "
for k in self.json_ref:
assert dict_[k] == self.json_ref[k], f"error for key {k} (in self.json_ref)"
self.assertDictEqual(dict_, self.json_ref)
with tempfile.TemporaryDirectory() as tmpdirname:
# test i can save it (json serializable)
with open(os.path.join(tmpdirname, "test.json"), "w") as fp:
json.dump(obj=dict_, fp=fp)
# test i can properly load it back
with open(os.path.join(tmpdirname, "test.json"), "r") as fp:
dict_realoaded = json.load(fp=fp)
assert dict_realoaded == dict_
# test i can initialize an observation from it
obs2.reset()
obs2.from_json(dict_realoaded)
assert obs == obs2
class TestUpdateEnvironement(unittest.TestCase):
def setUp(self):
# Create env and obs in left hand
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.lenv = make("rte_case5_example", test=True)
self.lobs = self.lenv.reset()
# Create env and obs in right hand
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.renv = make("rte_case5_example", test=True)
# Step once to make it different
self.robs, _, _, _ = self.renv.step(self.renv.action_space())
# Update left obs with right hand side environement
self.lobs.update(self.renv)
def tearDown(self):
self.lenv.close()
self.renv.close()
def test_topology_updates(self):
# Check left observation topology is updated to the right observation topology
assert np.all(self.lobs.timestep_overflow == self.robs.timestep_overflow)
assert np.all(self.lobs.line_status == self.robs.line_status)
assert np.all(self.lobs.topo_vect == self.robs.topo_vect)
def test_prods_updates(self):
# Check left loads are updated to the right loads
assert np.all(self.lobs.prod_p == self.robs.prod_p)
assert np.all(self.lobs.prod_q == self.robs.prod_q)
assert np.all(self.lobs.prod_v == self.robs.prod_v)
def test_loads_updates(self):
# Check left loads are updated to the right loads
assert np.all(self.lobs.load_p == self.robs.load_p)
assert np.all(self.lobs.load_q == self.robs.load_q)
assert np.all(self.lobs.load_v == self.robs.load_v)
def test_lines_or_updates(self):
# Check left loads are updated to the right loads
assert np.all(self.lobs.p_or == self.robs.p_or)
assert np.all(self.lobs.q_or == self.robs.q_or)
assert np.all(self.lobs.v_or == self.robs.v_or)
assert np.all(self.lobs.a_or == self.robs.a_or)
def test_lines_ex_updates(self):
# Check left loads are updated to the rhs loads
assert np.all(self.lobs.p_ex == self.robs.p_ex)
assert np.all(self.lobs.q_ex == self.robs.q_ex)
assert np.all(self.lobs.v_ex == self.robs.v_ex)
assert np.all(self.lobs.a_ex == self.robs.a_ex)
def test_forecasts_updates(self):
# Check left forecasts are updated to the rhs forecasts
# Check forecasts sizes
assert len(self.lobs._forecasted_inj) == len(self.robs._forecasted_inj)
# Check each forecast
for i in range(len(self.lobs._forecasted_inj)):
# Check timestamp
assert self.lobs._forecasted_inj[i][0] == self.robs._forecasted_inj[i][0]
# Check load_p
l_load_p = self.lobs._forecasted_inj[i][1]["injection"]["load_p"]
r_load_p = self.robs._forecasted_inj[i][1]["injection"]["load_p"]
assert np.all(l_load_p == r_load_p)
# Check load_q
l_load_q = self.lobs._forecasted_inj[i][1]["injection"]["load_q"]
r_load_q = self.robs._forecasted_inj[i][1]["injection"]["load_q"]
assert np.all(l_load_q == r_load_q)
# Check prod_p
l_prod_p = self.lobs._forecasted_inj[i][1]["injection"]["prod_p"]
r_prod_p = self.robs._forecasted_inj[i][1]["injection"]["prod_p"]
assert np.all(l_prod_p == r_prod_p)
# Check prod_v
l_prod_v = self.lobs._forecasted_inj[i][1]["injection"]["prod_v"]
r_prod_v = self.robs._forecasted_inj[i][1]["injection"]["prod_v"]
assert np.all(l_prod_v == r_prod_v)
# Check maintenance
# we never forecasted the maintenance anyway
# l_maintenance = self.lobs._forecasted_inj[i][1]['maintenance']
# r_maintenance = self.robs._forecasted_inj[i][1]['maintenance']
# assert np.all(l_maintenance == r_maintenance)
# Check relative flows
assert np.all(self.lobs.rho == self.robs.rho)
def test_cooldowns_updates(self):
# Check left cooldowns are updated to the rhs CDs
assert np.all(
self.lobs.time_before_cooldown_line == self.robs.time_before_cooldown_line
)
assert np.all(
self.lobs.time_before_cooldown_sub == self.robs.time_before_cooldown_sub
)
assert np.all(
self.lobs.time_before_cooldown_line == self.robs.time_before_cooldown_line
)
assert np.all(
self.lobs.time_next_maintenance == self.robs.time_next_maintenance
)
assert np.all(
self.lobs.duration_next_maintenance == self.robs.duration_next_maintenance
)
def test_redispatch_updates(self):
# Check left redispatch are updated to the rhs redispatches
assert np.all(self.lobs.target_dispatch == self.robs.target_dispatch)
assert np.all(self.lobs.actual_dispatch == self.robs.actual_dispatch)
class TestSimulateEqualsStep(unittest.TestCase):
def _make_forecast_perfect(self, env):
# Set forecasts to actual values so that simulate runs on the same numbers as step
env.chronics_handler.real_data.data.prod_p_forecast = np.roll(
self.env.chronics_handler.real_data.data.prod_p, -1, axis=0
)
env.chronics_handler.real_data.data.prod_v_forecast = np.roll(
self.env.chronics_handler.real_data.data.prod_v, -1, axis=0
)
env.chronics_handler.real_data.data.load_p_forecast = np.roll(
self.env.chronics_handler.real_data.data.load_p, -1, axis=0
)
env.chronics_handler.real_data.data.load_q_forecast = np.roll(
self.env.chronics_handler.real_data.data.load_q, -1, axis=0
)
obs, _, _, _ = env.step(env.action_space({}))
return obs
def setUp(self):
# Create env
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_realistic", test=True)
self.obs = self._make_forecast_perfect(self.env)
self.sim_obs = None
self.step_obs = None
def tearDown(self):
self.env.close()
def test_do_nothing(self):
# Create action
donothing_act = self.env.action_space()
# Simulate & Step
self.sim_obs, _, _, _ = self.obs.simulate(donothing_act)
self.step_obs, _, _, _ = self.env.step(donothing_act)
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_change_line_status(self):
# Get change status vector
change_status = self.env.action_space.get_change_line_status_vect()
# Make a change
change_status[0] = True
# Create change action
change_act = self.env.action_space({"change_line_status": change_status})
# Simulate & Step
self.sim_obs, reward_sim, done_sim, _ = self.obs.simulate(change_act)
self.step_obs, reward_real, done_real, _ = self.env.step(change_act)
assert not done_sim
assert not done_real
assert abs(reward_sim - reward_real) <= 1e-7
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_set_line_status(self):
# Get set status vector
set_status = self.env.action_space.get_set_line_status_vect()
# Make a change
set_status[0] = -1 if self.obs.line_status[0] else 1
# Create set action
set_act = self.env.action_space({"set_line_status": set_status})
# Simulate & Step
self.sim_obs, _, _, _ = self.obs.simulate(set_act)
self.step_obs, _, _, _ = self.env.step(set_act)
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_change_bus(self):
# Create a change bus action for all types
change_act = self.env.action_space(
{
"change_bus": {
"loads_id": [0],
"generators_ids": [0],
"lines_or_id": [0],
"lines_ex_id": [0],
}
}
)
# Simulate & Step
self.sim_obs, _, _, _ = self.obs.simulate(change_act)
self.step_obs, _, _, _ = self.env.step(change_act)
assert isinstance(
self.sim_obs, type(self.step_obs)
), "sim_obs is not the same type as the step"
assert isinstance(
self.step_obs, type(self.sim_obs)
), "step is not the same type as the simulation"
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_set_bus(self):
# Increment buses from current topology
new_load_bus = self.obs.topo_vect[self.obs.load_pos_topo_vect[0]] + 1
new_gen_bus = self.obs.topo_vect[self.obs.gen_pos_topo_vect[0]] + 1
new_lor_bus = self.obs.topo_vect[self.obs.line_or_pos_topo_vect[0]] + 1
new_lex_bus = self.obs.topo_vect[self.obs.line_ex_pos_topo_vect[0]] + 1
# Create a set bus action for all types
set_act = self.env.action_space(
{
"set_bus": {
"loads_id": [(0, new_load_bus)],
"generators_ids": [(0, new_gen_bus)],
"lines_or_id": [(0, new_lor_bus)],
"lines_ex_id": [(0, new_lex_bus)],
}
}
)
# Simulate & Step
self.sim_obs, _, _, _ = self.obs.simulate(set_act)
self.step_obs, _, _, _ = self.env.step(set_act)
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_redispatch(self):
if DEACTIVATE_FAILING_TEST:
return
# Find first redispatchable generator
gen_id = next((i for i, j in enumerate(self.obs.gen_redispatchable) if j), None)
# Create valid ramp up
redisp_val = self.obs.gen_max_ramp_up[gen_id] / 2.0
# Create redispatch action
redisp_act = self.env.action_space({"redispatch": [(gen_id, redisp_val)]})
# Simulate & Step
self.sim_obs, _, _, _ = self.obs.simulate(redisp_act)
self.step_obs, _, _, _ = self.env.step(redisp_act)
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_change_simulate_reward(self):
"""test the env.observation_space.change_other_reward function"""
# Create env
other_rewards = {
"close_overflow": CloseToOverflowReward,
"l2rpn": L2RPNReward,
"redisp": RedispReward,
}
env = self.env
# do as if the environment were created with these rewards !
env.observation_space.change_other_rewards(copy.deepcopy(other_rewards))
env.other_rewards = {}
for k, reward in other_rewards.items():
env.other_rewards[k] = RewardHelper(reward)
env.other_rewards[k].initialize(env)
# Set forecasts to actual values so that simulate runs on the same numbers as step
first_obs = self._make_forecast_perfect(env)
sim_o, sim_r, sim_d, sim_i = first_obs.simulate(env.action_space())
for k in other_rewards.keys():
assert k in sim_i["rewards"]
obs, reward, done, info = env.step(env.action_space())
# check rewards are same, this is the case because simulate is in "perfect information"
assert np.all(sim_o.rho == obs.rho)
self._aux_comp_reward(info, sim_i)
assert np.all(sim_o.load_p == obs.load_p)
env.observation_space.change_other_rewards({})
sim_o, sim_r, sim_d, sim_i = obs.simulate(env.action_space())
# check the rewards have disappeared
for k in other_rewards.keys():
assert k not in sim_i["rewards"]
# check they are still present on real environment
obs, reward, done, info = env.step(env.action_space())
for k in other_rewards.keys():
assert k in info["rewards"]
env.observation_space.change_other_rewards(other_rewards)
sim_o, sim_r, sim_d, sim_i = obs.simulate(env.action_space())
for k in other_rewards.keys():
assert k in sim_i["rewards"]
obs, reward, done, info = env.step(env.action_space())
# check rewards are same, this is the case because simulate is in "perfect information"
assert np.all(sim_o.rho == obs.rho)
self._aux_comp_reward(info, sim_i)
assert np.all(sim_o.load_p == obs.load_p)
def _aux_comp_reward(self, info, sim_info):
for el in info["rewards"]:
tmp_info = info["rewards"][el]
tmp_sinfo = sim_info["rewards"][el]
assert np.allclose(tmp_info, tmp_sinfo), f"error for {el}: in info: {tmp_info}, in simulated info: {tmp_sinfo}"
def _multi_actions_sample(self):
actions = []
## do_nothing action
donothing_act = self.env.action_space()
actions.append(donothing_act)
## change_status action
# Get change status vector
change_status = self.env.action_space.get_change_line_status_vect()
# Make a change
change_status[0] = True
# Register change action
change_act = self.env.action_space({"change_line_status": change_status})
actions.append(change_act)
## set_status action
# Get set status vector
set_status = self.env.action_space.get_set_line_status_vect()
# Make a change
set_status[0] = -1 if self.obs.line_status[0] else 1
# Register set action
set_act = self.env.action_space({"set_line_status": set_status})
actions.append(set_act)
## change_bus action
# Register a change bus action for all types
change_bus_act = self.env.action_space(
{
"change_bus": {
"loads_id": [0],
"generators_ids": [0],
"lines_or_id": [0],
"lines_ex_id": [0],
}
}
)
actions.append(change_bus_act)
## set_bus_action
# Increment buses from current topology
new_load_bus = self.obs.topo_vect[self.obs.load_pos_topo_vect[0]] + 1
new_gen_bus = self.obs.topo_vect[self.obs.gen_pos_topo_vect[0]] + 1
new_lor_bus = self.obs.topo_vect[self.obs.line_or_pos_topo_vect[0]] + 1
new_lex_bus = self.obs.topo_vect[self.obs.line_ex_pos_topo_vect[0]] + 1
# Create a set bus action for all types
set_bus_act = self.env.action_space(
{
"set_bus": {
"loads_id": [(0, new_load_bus)],
"generators_ids": [(0, new_gen_bus)],
"lines_or_id": [(0, new_lor_bus)],
"lines_ex_id": [(0, new_lex_bus)],
}
}
)
actions.append(set_bus_act)
## redispatch action
# Find first redispatchable generator
gen_id = next((i for i, j in enumerate(self.obs.gen_redispatchable) if j), None)
# Create valid ramp up
redisp_val = self.obs.gen_max_ramp_up[gen_id] / 2.0
# Create redispatch action
redisp_act = self.env.action_space({"redispatch": [(gen_id, redisp_val)]})
actions.append(redisp_act)
return actions
def test_multi_simulate_last_do_nothing(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
# Add do_nothing last
actions.append(self.env.action_space())
# Simulate all actions
for act in actions:
self.sim_obs, _, _, _ = self.obs.simulate(act)
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_multi_simulate_last_change_line_status(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
## Add change_line_status last
# Get change status vector
change_status = self.env.action_space.get_change_line_status_vect()
# Make a change
change_status[1] = True
# Register change action
change_act = self.env.action_space({"change_line_status": change_status})
actions.append(change_act)
# Simulate all actions
for act in actions:
self.sim_obs, _, _, _ = self.obs.simulate(act)
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_multi_simulate_last_set_line_status(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
## Add set_status action last
# Get set status vector
set_status = self.env.action_space.get_set_line_status_vect()
# Make a change
set_status[1] = -1 if self.obs.line_status[1] else 1
# Register set action
set_act = self.env.action_space({"set_line_status": set_status})
actions.append(set_act)
# Simulate all actions
for act in actions:
self.sim_obs, _, _, _ = self.obs.simulate(act)
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_multi_simulate_last_change_bus(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
## Add change_bus action last
# Register a change bus action for all types
change_bus_act = self.env.action_space(
{
"change_bus": {
"loads_id": [1],
"generators_ids": [1],
"lines_or_id": [1],
"lines_ex_id": [1],
}
}
)
actions.append(change_bus_act)
# Simulate all actions
for act in actions:
self.sim_obs, _, _, _ = self.obs.simulate(act)
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_multi_simulate_last_set_bus(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
## Add set_bus_action last
# Increment buses from current topology
new_load_bus = self.obs.topo_vect[self.obs.load_pos_topo_vect[1]] + 1
new_gen_bus = self.obs.topo_vect[self.obs.gen_pos_topo_vect[1]] + 1
new_lor_bus = self.obs.topo_vect[self.obs.line_or_pos_topo_vect[1]] + 1
new_lex_bus = self.obs.topo_vect[self.obs.line_ex_pos_topo_vect[1]] + 1
# Create a set bus action for all types
set_bus_act = self.env.action_space(
{
"set_bus": {
"loads_id": [(1, new_load_bus)],
"generators_ids": [(1, new_gen_bus)],
"lines_or_id": [(1, new_lor_bus)],
"lines_ex_id": [(1, new_lex_bus)],
}
}
)
actions.append(set_bus_act)
# Simulate all actions
for act in actions:
self.sim_obs, _, _, _ = self.obs.simulate(act)
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_multi_simulate_last_redispatch(self):
if DEACTIVATE_FAILING_TEST:
return
actions = self._multi_actions_sample()
## Add redispatch action last
# Find second redispatchable generator
matches = 0
gen_id = -1
for i, j in enumerate(self.obs.gen_redispatchable):
if j:
matches += 1
gen_id = i
if matches == 2:
break
# Make sure we have a generator
assert gen_id != -1
# Create valid ramp up
redisp_val = self.obs.gen_max_ramp_up[gen_id] / 2.0
# Create redispatch action
redisp_act = self.env.action_space({"redispatch": [(gen_id, redisp_val)]})
actions.append(redisp_act)
# Simulate all actions
# for act in actions:
# self.sim_obs, _, _, _ = self.obs.simulate(act)
self.sim_obs, _, _, _ = self.obs.simulate(actions[-1])
# Step with last action
self.step_obs, _, _, _ = self.env.step(actions[-1])
# Test observations are the same
if self.sim_obs != self.step_obs:
diff_, attr_diff = self.sim_obs.where_different(self.step_obs)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_forecasted_inj(self):
sim_obs, _, _, _ = self.obs.simulate(self.env.action_space())
prod_p_f, prod_v_f, load_p_f, load_q_f = self.obs.get_forecasted_inj()
assert np.sum(np.abs(prod_v_f - sim_obs.prod_v)) < 1e-5
assert np.sum(np.abs(load_p_f - sim_obs.load_p)) < 1e-5
assert np.sum(np.abs(load_q_f - sim_obs.load_q)) < 1e-5
# test all prod p are equal, of course we remove the slack bus...
assert np.sum(np.abs(prod_p_f[:-1] - sim_obs.prod_p[:-1])) < 1e-5
def _check_equal(self, obs1, obs2):
tol = 1e-8
assert np.all(np.abs(obs1.prod_p - obs2.prod_p) <= tol), "issue with prod_p"
assert np.all(np.abs(obs1.prod_v - obs2.prod_v) <= tol), "issue with prod_v"
assert np.all(np.abs(obs1.prod_q - obs2.prod_q) <= tol), "issue with prod_q"
assert np.all(np.abs(obs1.load_p - obs2.load_p) <= tol), "issue with load_p"
assert np.all(np.abs(obs1.load_q - obs2.load_q) <= tol), "issue with load_q"
assert np.all(np.abs(obs1.load_v - obs2.load_v) <= tol), "issue with load_v"
assert np.all(np.abs(obs1.rho - obs2.rho) <= tol), "issue with rho"
assert np.all(np.abs(obs1.p_or - obs2.p_or) <= tol), "issue with p_or"
assert np.all(np.abs(obs1.q_or - obs2.q_or) <= tol), "issue with q_or"
assert np.all(np.abs(obs1.v_or - obs2.v_or) <= tol), "issue with v_or"
assert np.all(np.abs(obs1.a_or - obs2.a_or) <= tol), "issue with a_or"
assert np.all(np.abs(obs1.p_ex - obs2.p_ex) <= tol), "issue with p_ex"
assert np.all(np.abs(obs1.q_ex - obs2.q_ex) <= tol), "issue with q_ex"
assert np.all(np.abs(obs1.v_ex - obs2.v_ex) <= tol), "issue with v_ex"
assert np.all(np.abs(obs1.a_ex - obs2.a_ex) <= tol), "issue with a_ex"
assert np.all(
np.abs(obs1.storage_power - obs2.storage_power) <= tol
), "issue with storage_power"
def test_simulate_current_ts(self):
sim_obs, _, _, _ = self.obs.simulate(self.env.action_space(), time_step=0)
# check that the observations are equal
self._check_equal(sim_obs, self.obs)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
obs = self.env.reset()
sim_obs1, rew1, done1, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
sim_obs2, rew2, done2, _ = obs.simulate(self.env.action_space(), time_step=0)
sim_obs3, rew3, done3, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
assert not done1
assert not done2
assert not done3
self._check_equal(sim_obs2, obs)
assert abs(rew1 - rew3) <= 1e-8, "issue with reward"
self._check_equal(sim_obs1, sim_obs3)
def test_nb_step(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
obs = self.env.reset()
sim_obs1, rew1, done1, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
sim_obs2, rew2, done2, _ = obs.simulate(self.env.action_space(), time_step=0)
sim_obs3, rew3, done3, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
assert obs.current_step == 0
assert sim_obs1.current_step == 1
assert sim_obs2.current_step == 1
assert sim_obs3.current_step == 1
obs, *_ = self.env.step(self.env.action_space())
sim_obs1, rew1, done1, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
assert obs.current_step == 1
assert sim_obs1.current_step == 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
obs = self.env.reset()
sim_obs1, rew1, done1, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
sim_obs2, rew2, done2, _ = obs.simulate(self.env.action_space(), time_step=0)
sim_obs3, rew3, done3, _ = obs.simulate(
self.env.action_space.disconnect_powerline(line_id=2)
)
assert obs.current_step == 0
assert sim_obs1.current_step == 1
assert sim_obs2.current_step == 1
assert sim_obs3.current_step == 1
class TestSimulateEqualsStepStorageCurtail(TestSimulateEqualsStep):
def setUp(self):
# Create env
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"educ_case14_storage", test=True, action_class=PlayableAction
)
self.obs = self._make_forecast_perfect(self.env)
self.sim_obs = None
self.step_obs = None
def test_storage_act(self):
"""test i can do storage actions in simulate"""
act = self.env.action_space()
act.storage_power = [(0, 3)]
obs = self.env.get_obs()
sim_obs1, rew1, done1, _ = obs.simulate(act)
assert not done1
sim_obs2, rew2, done2, _ = obs.simulate(self.env.action_space(), time_step=0)
assert not done2
sim_obs3, rew3, done3, _ = obs.simulate(act)
assert not done3
real_obs, real_rew, real_done, _ = self.env.step(act)
assert not real_done
self._check_equal(sim_obs1, sim_obs3)
self._check_equal(sim_obs2, obs)
assert abs(rew1 - rew3) <= 1e-8, "issue with reward"
self._check_equal(sim_obs1, sim_obs3)
assert abs(rew1 - real_rew) <= 1e-8, "issue with reward"
if real_obs != sim_obs3:
diff_, attr_diff = real_obs.where_different(sim_obs3)
raise AssertionError(f"Following attributes are different: {attr_diff}")
def test_curtail_act(self):
"""test i can do a curtailment actions in simulate"""
act = self.env.action_space()
act.curtail = [(2, 0.1)]
obs = self.env.get_obs()
sim_obs1, rew1, done1, _ = obs.simulate(act)
assert not done1
sim_obs2, rew2, done2, _ = obs.simulate(self.env.action_space(), time_step=0)
assert not done2
sim_obs3, rew3, done3, _ = obs.simulate(act)
assert not done3
real_obs, real_rew, real_done, _ = self.env.step(act)
assert not real_done
self._check_equal(sim_obs1, sim_obs3)
self._check_equal(sim_obs2, obs)
assert (
abs(rew1 - rew3) <= 1e-8
), "issue with reward between the two simulated actions"
self._check_equal(sim_obs1, sim_obs3)
assert abs(rew1 - real_rew) <= 1e-8, (
"issue with reward between simulate (first curtail) "
"and step (with curtail)"
)
if real_obs != sim_obs3:
diff_, attr_diff = real_obs.where_different(sim_obs3)
raise AssertionError(f"Following attributes are different: {attr_diff}")
if __name__ == "__main__":
unittest.main()
| 104,402 | 33.422354 | 124 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_ObservationHazard_Maintenance.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import pdb
from grid2op.tests.helper_path_test import *
from grid2op.Exceptions import *
from grid2op.Observation import CompleteObservation
from grid2op.Chronics import (
ChronicsHandler,
GridStateFromFile,
GridStateFromFileWithForecasts,
)
from grid2op.Rules import RulesChecker, DefaultRules
from grid2op.Reward import L2RPNReward
from grid2op.Parameters import Parameters
from grid2op.Backend import PandaPowerBackend
from grid2op.Environment import Environment
# TODO add unit test for the proper update the backend in the observation [for now there is a "data leakage" as
# the real backend is copied when the observation is built, but i need to make a test to check that's it's properly
# copied]
# temporary deactivation of all the failing test until simulate is fixed
DEACTIVATE_FAILING_TEST = False
import warnings
warnings.simplefilter("error")
class TestObservationHazard(unittest.TestCase):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
# from ADNBackend import ADNBackend
# self.backend = ADNBackend()
# self.path_matpower = "/home/donnotben/Documents/RL4Grid/RL4Grid/data"
# self.case_file = "ieee14_ADN.xml"
# self.backend.load_grid(self.path_matpower, self.case_file)
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
# pdb.set_trace()
self.rewardClass = L2RPNReward
self.reward_helper = self.rewardClass()
self.obsClass = CompleteObservation
self.parameters = Parameters()
# powergrid
self.backend = PandaPowerBackend()
self.path_matpower = PATH_DATA_TEST_PP
self.case_file = "test_case14.json"
# chronics
self.path_chron = os.path.join(PATH_CHRONICS, "chronics_with_hazards")
self.chronics_handler = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path_chron
)
self.tolvect = 1e-2
self.tol_one = 1e-5
self.id_chron_to_back_load = np.array([0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9])
# force the verbose backend
self.backend.detailed_infos_for_cascading_failures = True
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
# _parameters for the environment
self.env_params = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = Environment(
init_grid_path=os.path.join(self.path_matpower, self.case_file),
backend=self.backend,
init_env_path=os.path.join(self.path_matpower, self.case_file),
chronics_handler=self.chronics_handler,
parameters=self.env_params,
names_chronics_to_backend=self.names_chronics_to_backend,
rewardClass=self.rewardClass,
name="test_obs_env1",
)
def tearDown(self) -> None:
self.env.close()
def test_1_generating_obs_withhazard(self):
# test that helper_obs is abl to generate a valid observation
obs = self.env.get_obs()
assert np.all(
obs.time_before_cooldown_line
== [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
)
action = self.env.action_space({})
_ = self.env.step(action)
obs = self.env.get_obs()
assert np.all(
obs.time_before_cooldown_line
== [0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
)
_ = self.env.step(action)
obs = self.env.get_obs()
assert np.all(
obs.time_before_cooldown_line
== [0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
)
class TestObservationMaintenance(unittest.TestCase):
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
self.rewardClass = L2RPNReward
self.reward_helper = self.rewardClass()
self.obsClass = CompleteObservation
self.parameters = Parameters()
# powergrid
self.backend = PandaPowerBackend()
self.path_matpower = PATH_DATA_TEST_PP
self.case_file = "test_case14.json"
# chronics
self.path_chron = os.path.join(PATH_CHRONICS, "chronics_with_maintenance")
self.chronics_handler = ChronicsHandler(
chronicsClass=GridStateFromFileWithForecasts, path=self.path_chron
)
self.tolvect = 1e-2
self.tol_one = 1e-5
self.id_chron_to_back_load = np.array([0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9])
# force the verbose backend
self.backend.detailed_infos_for_cascading_failures = True
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
# _parameters for the environment
self.env_params = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = Environment(
init_grid_path=os.path.join(self.path_matpower, self.case_file),
backend=self.backend,
init_env_path=os.path.join(self.path_matpower, self.case_file),
chronics_handler=self.chronics_handler,
parameters=self.env_params,
names_chronics_to_backend=self.names_chronics_to_backend,
rewardClass=self.rewardClass,
name="test_obs_env2",
legalActClass=DefaultRules,
)
def tearDown(self) -> None:
self.env.close()
def test_1_generating_obs_withmaintenance(self):
# test that helper_obs is abl to generate a valid observation
obs = self.env.get_obs()
assert np.all(
obs.time_next_maintenance
== np.array(
[
-1,
-1,
-1,
-1,
1,
-1,
276,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
]
)
)
assert np.all(
obs.duration_next_maintenance
== np.array([0, 0, 0, 0, 12, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
)
action = self.env.action_space({})
_ = self.env.step(action)
obs = self.env.get_obs()
assert np.all(
obs.time_next_maintenance
== np.array(
[
-1,
-1,
-1,
-1,
0,
-1,
275,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
]
)
)
assert np.all(
obs.duration_next_maintenance
== np.array([0, 0, 0, 0, 12, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
)
_ = self.env.step(action)
obs = self.env.get_obs()
assert np.all(
obs.time_next_maintenance
== np.array(
[
-1,
-1,
-1,
-1,
0,
-1,
274,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
]
)
)
assert np.all(
obs.duration_next_maintenance
== np.array([0, 0, 0, 0, 11, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
)
def test_simulate_disco_planned_maintenance(self):
reco_line = self.env.action_space()
reco_line.line_set_status = [(4, +1)]
obs = self.env.get_obs()
assert obs.line_status[4]
assert obs.time_next_maintenance[4] == 1
assert obs.duration_next_maintenance[4] == 12
# line will be disconnected next time step
sim_obs, *_ = obs.simulate(self.env.action_space(), time_step=1)
assert not sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == 0
assert sim_obs.duration_next_maintenance[4] == 12
# simulation at current step
sim_obs, *_ = obs.simulate(self.env.action_space(), time_step=0)
assert sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == 1
assert sim_obs.duration_next_maintenance[4] == 12
# line will be disconnected next time step
sim_obs, *_ = obs.simulate(self.env.action_space(), time_step=1)
assert not sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == 0
assert sim_obs.duration_next_maintenance[4] == 12
for ts in range(11):
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_next_maintenance[4] == 0
assert obs.duration_next_maintenance[4] == 12-ts, f"should be {12-ts} but is {obs.duration_next_maintenance[4]} (step ts)"
# at this step if I attempt a reco it fails
obs, reward, done, info = self.env.step(self.env.action_space())
# maintenance will be over next time step
assert not obs.line_status[4]
assert obs.time_next_maintenance[4] == 0
assert obs.duration_next_maintenance[4] == 1
# if i don't do anything, it's updated properly
sim_obs, *_ = obs.simulate(self.env.action_space(), time_step=1)
assert not sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == -1
assert sim_obs.duration_next_maintenance[4] == 0
# i don't have the right to reconnect it if i don't simulate in the future
sim_obs, reward, done, info = obs.simulate(reco_line, time_step=0)
assert info["is_illegal"]
assert not sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == 0
assert sim_obs.duration_next_maintenance[4] == 1
# I still have to wait 1 step before reconnection, so this raises
sim_obs, reward, done, info = obs.simulate(reco_line, time_step=1)
assert info["is_illegal"], f"there should be no error, but action is illegal"
assert not sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == -1
assert sim_obs.duration_next_maintenance[4] == 0
# at this step if I attempt a reco it fails
obs, reward, done, info = self.env.step(reco_line)
# maintenance will be over next time step
assert info["is_illegal"]
assert not obs.line_status[4]
assert obs.time_next_maintenance[4] == -1
assert obs.duration_next_maintenance[4] == 0
# I can reco the line next step
sim_obs, reward, done, info = obs.simulate(reco_line, time_step=1)
assert not info["is_illegal"], f"there should be no error, but action is illegal"
assert sim_obs.line_status[4]
assert sim_obs.time_next_maintenance[4] == -1
assert sim_obs.duration_next_maintenance[4] == 0
# TODO be careful here, if the rules allows for reconnection, then the
# TODO action becomes legal, and the powerline is reconnected
# TODO => this is because the "_obs_env" do not attempt to force the disconnection
# TODO of maintenance / hazards powerline
if __name__ == "__main__":
unittest.main()
| 15,804 | 34.596847 | 134 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Opponent.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import tempfile
import warnings
import grid2op
from grid2op.Opponent.OpponentSpace import OpponentSpace
from grid2op.tests.helper_path_test import *
from grid2op.Chronics import ChangeNothing
from grid2op.Opponent import (
BaseOpponent,
RandomLineOpponent,
WeightedRandomOpponent,
GeometricOpponent
)
from grid2op.Opponent.geometricOpponentMultiArea import GeometricOpponentMultiArea
from grid2op.Action import TopologyAction
from grid2op.MakeEnv import make
from grid2op.Opponent.BaseActionBudget import BaseActionBudget
from grid2op.dtypes import dt_int
from grid2op.Parameters import Parameters
from grid2op.Runner import Runner
from grid2op.Episode import EpisodeData
from grid2op.Environment import SingleEnvMultiProcess
from grid2op.Exceptions import OpponentError
import pdb
ATTACK_DURATION = 48
ATTACK_COOLDOWN = 100
LINES_ATTACKED = ["1_3_3", "1_4_4", "3_6_15", "9_10_12", "11_12_13", "12_13_14"]
RHO_NORMALIZATION = [1, 1, 1, 1, 1, 1]
class TestSuiteBudget_001(BaseActionBudget):
"""just for testing"""
pass
class TestSuiteOpponent_001(BaseOpponent):
"""test class that disconnects randomly the powerlines"""
def __init__(self, action_space):
BaseOpponent.__init__(self, action_space)
self.line_id = [0, 1, 2, 3]
self.possible_attack = [
self.action_space.disconnect_powerline(line_id=el) for el in self.line_id
]
def attack(self, observation, agent_action, env_action, budget, previous_fails):
if observation is None: # On first step
return None
attack = self.space_prng.choice(self.possible_attack)
return attack, None
class TestWeightedRandomOpponent(WeightedRandomOpponent):
def init(self, lines_attacked=[], rho_normalization=[], **kwargs):
WeightedRandomOpponent.init(
self,
lines_attacked=lines_attacked,
rho_normalization=rho_normalization,
**kwargs,
)
self._attack_counter = 0
self._attack_continues_counter = 0
def tell_attack_continues(self, observation, agent_action, env_action, budget):
self._attack_continues_counter += 1
WeightedRandomOpponent.tell_attack_continues(
self, observation, agent_action, env_action, budget
)
def attack(self, observation, agent_action, env_action, budget, previous_fails):
self._attack_counter += 1
return WeightedRandomOpponent.attack(
self, observation, agent_action, env_action, budget, previous_fails
)
class TestLoadingOpp(unittest.TestCase):
def test_creation_BaseOpponent(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
my_opp = BaseOpponent(action_space=env.action_space)
def test_env_modif_oppo(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, opponent_class=TestSuiteOpponent_001
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert isinstance(env._opponent, TestSuiteOpponent_001)
def test_env_modif_oppobudg(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example",
test=True,
opponent_budget_class=TestSuiteBudget_001,
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert isinstance(env._compute_opp_budget, TestSuiteBudget_001)
def test_env_modif_opponent_init_budget(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budg = 100.0
with make(
"rte_case5_example", test=True, opponent_init_budget=init_budg
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert env._opponent_init_budget == init_budg
def test_env_modif_opponent_init_budget_ts(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budg = 100.0
with make(
"rte_case5_example", test=True, opponent_budget_per_ts=init_budg
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert env._opponent_budget_per_ts == init_budg
def test_env_modif_opponent_action_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, opponent_action_class=TopologyAction
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert issubclass(env._opponent_action_class, TopologyAction)
def test_env_opp_attack(self):
# and test reset, which apparently is NOT done correctly
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budg = 100.0
with make(
"rte_case5_example",
test=True,
opponent_init_budget=init_budg,
opponent_action_class=TopologyAction,
opponent_budget_class=TestSuiteBudget_001,
opponent_attack_duration=ATTACK_DURATION,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=TestSuiteOpponent_001,
) as env:
obs = env.reset()
# opponent should not attack at the first time step
assert np.all(obs.line_status)
assert env._opponent_init_budget == init_budg
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == init_budg - 1.0
obs = env.reset()
# opponent should not attack at the first time step
assert np.all(obs.line_status)
assert env._opponent_init_budget == init_budg
assert env._oppSpace.budget == init_budg
def test_env_opp_attack_budget_ts(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budg_ts = 0.5
with make(
"rte_case5_example",
test=True,
opponent_budget_per_ts=init_budg_ts,
opponent_attack_duration=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=TestSuiteBudget_001,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=TestSuiteOpponent_001,
) as env:
obs = env.reset()
assert env._opponent_init_budget == 0.0
obs, reward, done, info = env.step(env.action_space())
# no attack possible
assert env._oppSpace.budget == init_budg_ts
obs, reward, done, info = env.step(env.action_space())
# i can attack at the second time steps, and budget of an attack is 1, so I have 0 now
assert env._oppSpace.budget == 0.0
obs = env.reset()
assert env._opponent_init_budget == 0.0
assert env._opponent_budget_per_ts == 0.5
assert env._oppSpace.budget == 0.0
def test_RandomLineOpponent_not_enough_budget(self):
"""Tests that the attack is ignored when the budget is too low"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 50
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True # otherwise there's a game over
with make(
"rte_case14_realistic",
test=True,
param=param,
opponent_attack_cooldown=0, # only for testing
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
obs = env.reset()
assert env._oppSpace.budget == init_budget
# The opponent can attack
for i in range(env._oppSpace.attack_max_duration):
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
assert env._oppSpace.budget == init_budget - i - 1
assert any(attack._set_line_status != 0)
# There is not enough budget for a second attack
assert (
abs(env._oppSpace.budget - (init_budget - ATTACK_DURATION)) <= 1e-5
)
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
assert attack is None
def test_RandomLineOpponent_attackable_lines(self):
"""Tests that the RandomLineOpponent only attacks the authorized lines"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
tries = 30
attackable_lines_case14 = LINES_ATTACKED
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
for _ in range(tries):
obs = env.reset()
assert env._oppSpace.budget == init_budget
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == init_budget - 1
attack = env._oppSpace.last_attack
attacked_line = np.where(attack._set_line_status == -1)[0][0]
line_name = env.action_space.name_line[attacked_line]
assert line_name in attackable_lines_case14
def test_RandomLineOpponent_disconnects_only_one_line(self):
"""Tests that the RandomLineOpponent does not disconnect several lines at a time"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
tries = 30
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
for _ in range(tries):
obs = env.reset()
assert env._oppSpace.budget == init_budget
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == init_budget - 1
attack = env._oppSpace.last_attack
n_disconnected = np.sum(attack._set_line_status == -1)
assert n_disconnected == 1
def test_RandomLineOpponent_with_agent(self):
"""Tests that the line status cooldown is correctly updated when the opponent attacks a line with an agent"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# to prevent attack on first time step
init_budget = 8
opponent_budget_per_ts = 1
length = 300
agent_line_cooldown = 30
attack_duration = 10
attack_cooldown = 20000 # i do one attack
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = agent_line_cooldown
line_opponent_attack = 4
line_opponent_attack = 15
lines_attacked = ["3_6_15"]
with make(
"rte_case14_realistic",
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": lines_attacked},
) as env:
env.seed(0)
obs = env.reset()
reward = 0
assert env._oppSpace.budget == init_budget
assert np.all(obs.time_before_cooldown_line == 0)
# the "agent" does an action (on the same powerline as the opponent attacks)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(line_opponent_attack, 1)]})
)
assert np.all(obs.line_status)
assert (
obs.time_before_cooldown_line[line_opponent_attack]
== agent_line_cooldown
)
# check that the opponent cooldown is not taken into account (lower than the cooldown on line)
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
assert "opponent_attack_line" in info
assert (
np.sum(info["opponent_attack_line"]) == 1
), "error at iteration {} for attack".format(i)
assert info["opponent_attack_line"][line_opponent_attack]
assert obs.time_before_cooldown_line[
line_opponent_attack
] == agent_line_cooldown - (i + 1), "error at iteration {}".format(
i
)
obs, reward, done, info = env.step(env.action_space())
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is None # no more attack
assert (
obs.time_before_cooldown_line[line_opponent_attack]
== agent_line_cooldown - 11
)
def test_RandomLineOpponent_with_maintenance_1(self):
"""Tests that the line status cooldown is correctly updated when the opponent attacks a line with an agent"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# to prevent attack on first time step
init_budget = 8
opponent_budget_per_ts = 1
length = 300
agent_line_cooldown = 30
attack_duration = 5
attack_cooldown = 20000 # i do one attack
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = agent_line_cooldown
line_opponent_attack = 4
line_opponent_attack = 11
# 1. attack is at the same time than the maintenance
lines_attacked = ["8_13_11"]
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": lines_attacked},
) as env:
env.seed(0)
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
# the opponent has attacked
assert "opponent_attack_line" in info
assert (
np.sum(info["opponent_attack_line"]) == 1
), "error at iteration {} for attack".format(0)
assert info["opponent_attack_line"][line_opponent_attack]
# but the maintenance cooldown has priority (longer)
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# 2. attack is before than the maintenance
init_budget = 8
opponent_budget_per_ts = 1
attack_duration = 5
lines_attacked = ["9_10_12"]
line_id = 12
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": lines_attacked},
) as env:
env.seed(0)
obs = env.reset()
env.fast_forward_chronics(274)
obs, reward, done, info = env.step(env.action_space())
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 1
# the opponent has attacked at this time step
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][line_id]
assert info["opponent_attack_duration"] == 4
# cooldown should be updated correctly
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
for i in range(3):
obs, reward, done, info = env.step(
env.action_space()
) # the maintenance is happening
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 0
# the attack continued
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][line_id]
assert info["opponent_attack_duration"] == 3 - i
assert np.all(
obs.time_before_cooldown_line
== np.array(
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
12 - i,
0,
0,
0,
0,
0,
0,
0,
],
dtype=dt_int,
)
)
# attack should be over
obs, reward, done, info = env.step(
env.action_space()
) # the maintenance is happening
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 0
# the attack continued
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is None
assert info["opponent_attack_duration"] == 0
assert np.all(
obs.time_before_cooldown_line
== np.array(
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
12 - 3,
0,
0,
0,
0,
0,
0,
0,
],
dtype=dt_int,
)
)
def test_RandomLineOpponent_only_attack_connected(self):
"""
Tests that the RandomLineOpponent does not attack lines that are already disconnected
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 10000
length = 300
env = make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=0, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
)
env.seed(0)
# Collect some attacks
# and check that they belong to the correct lines
pre_obs = env.reset()
done = False
assert env._oppSpace.budget == init_budget
for i in range(length):
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
attacked_line = np.where(attack._set_line_status == -1)[0][0]
if (
env._oppSpace.current_attack_duration
< env._oppSpace.attack_max_duration
):
# The attack is ungoing. The line must have been disconnected already
assert not pre_obs.line_status[attacked_line]
else:
# A new attack was launched. The line must have been connected
assert pre_obs.line_status[attacked_line]
pre_obs = obs
if done:
pre_obs = env.reset()
def test_RandomLineOpponent_same_attack_order_and_attacks_all_lines(self):
"""Tests that the RandomLineOpponent has the same attack order (when seeded) and attacks all lines"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
length = 30
# new attack order in version 1.6.5 because of the new reset method
expected_attack_order = [
4,
12,
14,
14,
12,
13,
3,
15,
15,
12,
4,
15,
14,
12,
15,
4,
4,
3,
15,
13,
12,
14,
12,
]
attack_order = []
has_disconnected_all = False
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
obs = env.reset()
done = False
assert env._oppSpace.budget == init_budget
for i in range(length):
if done:
obs = env.reset()
pre_done = done
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
if (
attack is None and not done
): # should only happen here if all attackable lines are already disconnected
assert np.sum(obs.line_status == False) == 6
continue
elif done:
continue
assert any(attack._set_line_status == -1)
attacked_line = np.where(attack._set_line_status == -1)[0][0]
if pre_done or not (
attack_order and attack_order[-1] == attacked_line
):
attack_order.append(attacked_line)
assert len(set(attack_order)) == 6
assert attack_order == expected_attack_order
def test_simulate(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
opponent_attack_duration = 15
opponent_attack_cooldown = 20
line_id = 4
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
reco_line = env.action_space({"set_line_status": [(line_id, 1)]})
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
simobs, sim_r, sim_d, sim_info = obs.simulate(env.action_space())
assert simobs.rho[line_id] == 0.0
assert not simobs.line_status[line_id]
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] == 0.0
assert not simobs.line_status[line_id]
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# check that the budget of the opponent in the ObsEnv does not decrease
for i in range(opponent_attack_duration):
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] == 0.0
assert not simobs.line_status[line_id]
# check that the opponent continue its attacks
for i in range(opponent_attack_duration - 2):
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# i should be able to simulate a reconnection now
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] > 0.0
assert simobs.line_status[line_id]
# this should not affect the environment
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# and now that i'm able to reconnect the powerline in step
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] > 0.0
assert obs.line_status[line_id]
def test_opponent_load(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example",
test=True,
opponent_action_class=TopologyAction,
opponent_class=RandomLineOpponent,
) as env_1:
env_1.seed(0)
obs, reward, done, info = env_1.step(env_1.action_space())
with make(
"rte_case118_example",
test=True,
opponent_action_class=TopologyAction,
opponent_class=RandomLineOpponent,
) as env_2:
env_2.seed(0)
obs, reward, done, info = env_2.step(env_2.action_space())
def test_proper_action_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
opponent_attack_duration = 15
opponent_attack_cooldown = 20
line_id = 4
opponent_action_class = TopologyAction
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_action_class=opponent_action_class,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
assert env._opponent_action_class == opponent_action_class
assert issubclass(
env._oppSpace.action_space.actionClass, opponent_action_class
)
assert issubclass(
env._opponent_action_space.actionClass, opponent_action_class
)
opp_space = env._oppSpace
attack, duration = opp_space.attack(
env.get_obs(), env.action_space(), env.action_space()
)
assert isinstance(attack, opponent_action_class)
def test_get_set_state(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
opponent_attack_duration = 15
opponent_attack_cooldown = 20
line_id = 4
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
agent_action = env.action_space()
observation = env.get_obs()
env_action = env.action_space()
opp_space = env._oppSpace
# FIRST CHECK: WHEN NO ATTACK ARE PERFORMED
# test that if i do "a loop of get / set" i get the same stuff
init_state = opp_space._get_state()
opp_space._set_state(*init_state)
second_init_state = opp_space._get_state()
assert np.all(init_state == second_init_state)
# now do absolutely anything
for i in range(70):
opp_space.attack(observation, agent_action, env_action)
# check that indeed the state should have changed
other_state = opp_space._get_state()
assert np.any(init_state != other_state)
# check that if i set the state back, the
opp_space._set_state(*init_state)
second_init_state = opp_space._get_state()
assert np.all(init_state == second_init_state)
# note due to the "random effect" we don't impose the opponent to act on the same line again...
# this normal and should be explained in the notebooks.
# SECOND CHECK WHEN AN ATTACK NEED TO BE CONTINUED
# now i do an attack that should be continues
attack1 = opp_space.attack(observation, agent_action, env_action)
init_state = opp_space._get_state()
for i in range(70):
opp_space.attack(observation, agent_action, env_action)
opp_space._set_state(*init_state)
second_init_state = opp_space._get_state()
assert np.all(init_state == second_init_state)
# this time the attack continues, so it should be same
attack2 = opp_space.attack(observation, agent_action, env_action)
# attack are the same
assert np.all(attack1[0].to_vect() == attack2[0].to_vect())
# the second time i attacked twice, the first one only once, i check the budget
assert np.all(attack1[1] == attack2[1] + 1)
def test_withrunner(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
opponent_attack_duration = 15
opponent_attack_cooldown = 30
opponent_budget_per_ts = 0.0
opponent_action_class = TopologyAction
line_id = 3
p = Parameters()
p.NO_OVERFLOW_DISCONNECTION = True
env = make(
"rte_case14_realistic",
test=True,
param=p,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_action_class=opponent_action_class,
opponent_budget_class=BaseActionBudget,
opponent_class=RandomLineOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
)
env.seed(0)
runner = Runner(**env.get_params_for_runner())
assert runner.opponent_init_budget == init_budget
assert runner.opponent_budget_per_ts == opponent_budget_per_ts
assert runner.opponent_attack_cooldown == opponent_attack_cooldown
assert runner.opponent_attack_duration == opponent_attack_duration
assert runner.opponent_action_class == opponent_action_class
f = tempfile.mkdtemp()
res = runner.run(
nb_episode=1,
env_seeds=[4],
agent_seeds=[0],
max_iter=opponent_attack_cooldown - 1,
path_save=f,
)
for i, episode_name, cum_reward, timestep, total_ts in res:
episode_data = EpisodeData.from_disk(agent_path=f, name=episode_name)
assert np.any(
episode_data.attacks.collection[:, line_id] == -1.0
), "no attack on powerline {}".format(line_id)
assert (
np.sum(episode_data.attacks.collection[:, line_id])
== -opponent_attack_duration
), "too much / not enought attack on powerline {}".format(line_id)
assert np.all(episode_data.attacks.collection[:, 0] == 0.0)
def test_env_opponent(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_opponent", test=True, param=param)
env.seed(0) # make sure i have reproducible experiments
obs = env.reset()
assert env._oppSpace.budget == 0
assert np.all(obs.line_status)
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == 0.5
assert np.all(obs.line_status)
obs, reward, done, info = env.step(env.action_space())
env.close()
def test_multienv_opponent(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case14_opponent", test=True, param=param)
env.seed(0) # make sure i have reproducible experiments
multi_env = SingleEnvMultiProcess(env=env, nb_env=2)
obs = multi_env.reset()
for ob in obs:
assert np.all(ob.line_status)
assert np.all(multi_env._opponent[0]._lines_ids == [3, 4, 15, 12, 13, 14])
assert np.all(multi_env._opponent[1]._lines_ids == [3, 4, 15, 12, 13, 14])
env.close()
multi_env.close()
def test_WeightedRandomOpponent_not_enough_budget(self):
"""Tests that the attack is ignored when the budget is too low"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 50
with make(
"rte_case14_realistic",
test=True,
opponent_attack_cooldown=1, # only for testing
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": 1,
},
) as env:
env.seed(0)
obs = env.reset()
assert env._oppSpace.budget == init_budget
# The opponent can attack
for i in range(env._oppSpace.attack_max_duration):
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
assert env._oppSpace.budget == init_budget - i - 1
assert any(attack._set_line_status != 0)
# There is not enough budget for a second attack
assert (
abs(env._oppSpace.budget - (init_budget - ATTACK_DURATION)) <= 1e-5
)
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
assert attack is None
def test_WeightedRandomOpponent_attackable_lines(self):
"""Tests that the WeightedRandomOpponent only attacks the authorized lines"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
tries = 30
attackable_lines_case14 = LINES_ATTACKED
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": 1,
},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
for _ in range(tries):
obs = env.reset()
assert env._oppSpace.budget == init_budget
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == init_budget - 1
attack = env._oppSpace.last_attack
attacked_line = np.where(attack._set_line_status == -1)[0][0]
line_name = env.action_space.name_line[attacked_line]
assert line_name in attackable_lines_case14
def test_WeightedRandomOpponent_disconnects_only_one_line(self):
"""Tests that the WeightedRandomOpponent does not disconnect several lines at a time"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
tries = 30
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_attack_cooldown=ATTACK_COOLDOWN,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": 1,
},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
for _ in range(tries):
obs = env.reset()
assert env._oppSpace.budget == init_budget
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.budget == init_budget - 1
attack = env._oppSpace.last_attack
n_disconnected = np.sum(attack._set_line_status == -1)
assert n_disconnected == 1
def test_WeightedRandomOpponent_with_agent(self):
"""Tests that the line status cooldown is correctly updated when the opponent attacks a line with an agent"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# to prevent attack on first time step
init_budget = 8
opponent_budget_per_ts = 1
length = 300
agent_line_cooldown = 30
attack_duration = 10
attack_cooldown = 20000 # i do one attack
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = agent_line_cooldown
line_opponent_attack = 4
line_opponent_attack = 15
lines_attacked = ["3_6_15"]
rho_normalization = [1]
with make(
"rte_case14_realistic",
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": lines_attacked,
"rho_normalization": rho_normalization,
"attack_period": 1,
},
) as env:
env.seed(0)
obs = env.reset()
reward = 0
assert env._oppSpace.budget == init_budget
assert np.all(obs.time_before_cooldown_line == 0)
# the "agent" does an action (on the same powerline as the opponent attacks)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(line_opponent_attack, 1)]})
)
assert np.all(obs.line_status)
assert (
obs.time_before_cooldown_line[line_opponent_attack]
== agent_line_cooldown
)
# check that the opponent cooldown is not taken into account (lower than the cooldown on line)
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
assert "opponent_attack_line" in info
assert (
np.sum(info["opponent_attack_line"]) == 1
), "error at iteration {} for attack".format(i)
assert info["opponent_attack_line"][line_opponent_attack]
assert obs.time_before_cooldown_line[
line_opponent_attack
] == agent_line_cooldown - (i + 1), "error at iteration {}".format(
i
)
obs, reward, done, info = env.step(env.action_space())
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is None # no more attack
assert (
obs.time_before_cooldown_line[line_opponent_attack]
== agent_line_cooldown - 11
)
def test_WeightedRandomOpponent_with_maintenance_1(self):
"""Tests that the line status cooldown is correctly updated when the opponent attacks a line with an agent"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# to prevent attack on first time step
init_budget = 8
opponent_budget_per_ts = 1
length = 300
agent_line_cooldown = 30
attack_duration = 5
attack_cooldown = 20000 # i do one attack
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = agent_line_cooldown
line_opponent_attack = 4
line_opponent_attack = 11
# 1. attack is at the same time than the maintenance
lines_attacked = ["8_13_11"]
rho_normalization = [1]
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": lines_attacked,
"rho_normalization": rho_normalization,
"attack_period": 1,
},
) as env:
env.seed(0)
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
# the opponent has attacked
assert "opponent_attack_line" in info
assert (
np.sum(info["opponent_attack_line"]) == 1
), "error at iteration 0 for attack"
assert info["opponent_attack_line"][line_opponent_attack]
# but the maintenance cooldown has priority (longer)
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
# 2. attack is before than the maintenance
init_budget = 8
opponent_budget_per_ts = 1
attack_duration = 5
lines_attacked = ["9_10_12"]
rho_normalization = [1]
line_id = 12
with make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
opponent_init_budget=init_budget,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=attack_duration,
opponent_attack_cooldown=attack_cooldown,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": lines_attacked,
"rho_normalization": rho_normalization,
"attack_period": 1,
},
) as env:
env.seed(0)
obs = env.reset()
env.fast_forward_chronics(274)
obs, reward, done, info = env.step(env.action_space())
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 1
# the opponent has attacked at this time step
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][line_id]
assert info["opponent_attack_duration"] == 4
# cooldown should be updated correctly
assert np.all(
obs.time_before_cooldown_line
== np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0],
dtype=dt_int,
)
)
for i in range(3):
obs, reward, done, info = env.step(
env.action_space()
) # the maintenance is happening
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 0
# the attack continued
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][line_id]
assert info["opponent_attack_duration"] == 3 - i
assert np.all(
obs.time_before_cooldown_line
== np.array(
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
12 - i,
0,
0,
0,
0,
0,
0,
0,
],
dtype=dt_int,
)
)
# attack should be over
obs, reward, done, info = env.step(
env.action_space()
) # the maintenance is happening
# i have a maintenance in 1 time step
assert obs.time_next_maintenance[line_id] == 0
# the attack continued
assert "opponent_attack_line" in info
assert info["opponent_attack_line"] is None
assert info["opponent_attack_duration"] == 0
assert np.all(
obs.time_before_cooldown_line
== np.array(
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
12 - 3,
0,
0,
0,
0,
0,
0,
0,
],
dtype=dt_int,
)
)
def test_WeightedRandomOpponent_only_attack_connected(self):
"""
Tests that the WeightedRandomOpponent does not attack lines that are already disconnected
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 10000
length = 300
env = make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_attack_duration=ATTACK_DURATION,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": 1,
},
)
env.seed(0)
# Collect some attacks
# and check that they belong to the correct lines
pre_obs = env.reset()
done = False
assert env._oppSpace.budget == init_budget
for i in range(length):
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
attacked_line = np.where(attack._set_line_status == -1)[0][0]
if (
env._oppSpace.current_attack_duration
< env._oppSpace.attack_max_duration
):
# The attack is ungoing. The line must have been disconnected already
assert not pre_obs.line_status[attacked_line]
else:
# A new attack was launched. The line must have been connected
assert pre_obs.line_status[attacked_line]
pre_obs = obs
if done:
pre_obs = env.reset()
def test_WeightedRandomOpponent_same_attack_order_and_attacks_all_lines(self):
"""Tests that the WeightedRandomOpponent has the same attack order (when seeded) and attacks all lines"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
length = 30
expected_attack_order = [
4,
3,
14,
15,
12,
15,
12,
3,
12,
13,
3,
15,
4,
14,
15,
13,
14,
4,
3,
3,
4,
14,
15,
12,
15,
13,
4,
14,
12,
3,
]
attack_order = []
has_disconnected_all = False
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=1, # only for testing
opponent_attack_duration=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=WeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": 1,
},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
obs = env.reset()
done = False
assert env._oppSpace.budget == init_budget
for i in range(length):
if done:
obs = env.reset()
pre_done = done
obs, reward, done, info = env.step(env.action_space())
attack = env._oppSpace.last_attack
if attack is None and not done:
# should only happen here if all attackable lines are already disconnected
# OR if there are a game over
assert np.sum(obs.line_status == False) == 6 or done
continue
assert any(attack._set_line_status == -1)
attacked_line = np.where(attack._set_line_status == -1)[0][0]
if pre_done or not (
attack_order and attack_order[-1] == attacked_line
):
attack_order.append(attacked_line)
assert attack_order == expected_attack_order
assert len(set(attack_order)) == 6
def test_either_attack_or_tell_attack_continues(self):
"""Tests that at each step, either the attack or the tell_attack_continues method is called once"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
init_budget = 1000
length = 100
attack_cooldown = 15
with make(
"rte_case14_realistic",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=attack_cooldown, # only for testing
opponent_attack_duration=5, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=TestWeightedRandomOpponent,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"rho_normalization": RHO_NORMALIZATION,
"attack_period": attack_cooldown,
},
) as env:
env.seed(0)
# Collect some attacks and check that they belong to the correct lines
obs = env.reset()
done = False
assert env._oppSpace.budget == init_budget
for i in range(length):
if done:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert env._oppSpace.opponent._attack_counter == 70
assert env._oppSpace.opponent._attack_continues_counter == 30
assert (
env._oppSpace.opponent._attack_counter
+ env._oppSpace.opponent._attack_continues_counter
== length
)
class TestGeometricOpponent(unittest.TestCase):
def test_can_create(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
my_opp = GeometricOpponent(action_space=env.action_space)
def test_can_init(self):
init_budget = 120.0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
obs = env.reset()
def test_does_attack_outsideenv(self):
init_budget = 120.0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=0.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=1, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_times == [64, 407, 487, 522])
assert np.all(opponent._attack_waiting_times == [64, 312, 48, 4])
assert np.all(opponent._attack_durations == [31, 32, 31, 25])
assert np.all(opponent._number_of_attacks == 4)
# now i simulate what happens in the "real" game up to the first attack, it should not attack !
# 64 is hard coded here because i set the seed ! and it's an error if the seeding does not work
for i in range(64):
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is None
assert duration is None
# it should do an attack
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is not None
assert duration == 31
lines_impacted, subs_impacted = attack.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert lines_impacted[4]
# now the attack last 31 steps, so I "tell attack continues" for that long
for i in range(31):
opponent.tell_attack_continues(obs, None, None, None)
# now i have to wait for another 312 steps
for i in range(312):
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is None, f"error for step {i}"
assert duration is None, f"error for step {i}"
# it should do another attack
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is not None
assert duration == 32
lines_impacted, subs_impacted = attack.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert lines_impacted[12]
# now i reset it
obs = env.reset() # behaviour changed in 1.6.5
assert np.all(opponent._attack_times == [189, 250, 351, 446])
assert np.all(opponent._attack_waiting_times == [189, 18, 67, 66])
assert np.all(opponent._attack_durations == [43, 34, 29, 49])
assert np.all(opponent._number_of_attacks == 4)
for i in range(189):
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is None
assert duration is None
# it should do an attack
attack, duration = opponent.attack(obs, None, None, None, None)
assert attack is not None
assert duration == 43
lines_impacted, subs_impacted = attack.get_topological_impact()
assert np.sum(lines_impacted) == 1
assert lines_impacted[13]
def test_does_attack(self):
init_budget = 500
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=300, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_times == [64, 407, 487, 522])
assert np.all(opponent._attack_waiting_times == [64, 312, 48, 4])
assert np.all(opponent._attack_durations == [31, 32, 31, 25])
assert np.all(opponent._number_of_attacks == 4)
# it should not attack before due time
for i in range(64):
obs, reward, done, info = env.step(env.action_space())
assert (
info["opponent_attack_duration"] == 0
), f"attack detected at iteration {i}"
assert (
info["opponent_attack_line"] is None
), f"attack detected at iteration {i}"
# now it should attack
obs, reward, done, info = env.step(env.action_space())
assert info["opponent_attack_duration"] == 31
assert info["opponent_attack_line"][4]
# here the attack continues
for i in range(30):
obs, reward, done, info = env.step(env.action_space())
assert (
info["opponent_attack_duration"] == 30 - i
), f"wrong attack duration at iteration {i}"
assert info["opponent_attack_line"][
4
], f"wrong line attacked at iteration {i}"
# I will NOT simulate the 312 steps where the opponent does not attack... I only do a few for speed
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
assert (
info["opponent_attack_duration"] == 0
), f"attack detected at iteration {i}"
assert (
info["opponent_attack_line"] is None
), f"attack detected at iteration {i}"
# reset
obs = env.reset()
# NOTE this is not the same times as above... Indeed the sequence of prn generated is not the same
# (because as opposed to test_does_attack_outsideenv, this time i don't simulate everything)
assert np.all(
opponent._attack_times == [189, 250, 351, 446]
) # reset changed in grid2op 1.6.5
assert np.all(opponent._attack_waiting_times == [189, 18, 67, 66])
assert np.all(opponent._attack_durations == [43, 34, 29, 49])
assert np.all(opponent._number_of_attacks == 4)
# it should not attack before due time, but i don't simulate everything...
for i in range(10):
obs, reward, done, info = env.step(env.action_space())
assert (
info["opponent_attack_duration"] == 0
), f"attack detected at iteration {i}"
assert (
info["opponent_attack_line"] is None
), f"attack detected at iteration {i}"
def test_minimum_attack_duration(self):
init_budget = 500
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=300, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"attack_every_xxx_hour": 24,
"average_attack_duration_hour": 5,
"minimum_attack_duration_hour": 4,
},
) as env:
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_durations >= 48)
obs = env.reset()
assert np.all(opponent._attack_durations >= 48)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=300, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"attack_every_xxx_hour": 24,
"average_attack_duration_hour": 5,
"minimum_attack_duration_hour": 1,
},
) as env:
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_durations >= 12)
obs = env.reset()
assert np.all(opponent._attack_durations >= 12)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=300, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={
"lines_attacked": LINES_ATTACKED,
"attack_every_xxx_hour": 50,
"average_attack_duration_hour": 31,
"minimum_attack_duration_hour": 30,
},
) as env:
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_durations >= 30 * 12)
obs = env.reset()
assert np.all(opponent._attack_durations >= 30 * 12)
def test_average_attack_duration(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, chronics_class=ChangeNothing
) as env:
my_opp = GeometricOpponent(action_space=env.action_space)
with self.assertRaises(OpponentError):
# this is not supported, as there are an infinite number of steps in this environment
my_opp.init(
partial_env=env,
lines_attacked=env.name_line,
attack_every_xxx_hour=24,
average_attack_duration_hour=2,
minimum_attack_duration_hour=1,
)
env.set_max_iter(3000000)
threshold = 1.0 # balance between test speed and precision i ask to match the theoretical average
for mean_duration_hour in [2, 4, 8, 12, 16, 20]:
my_opp.seed(0)
my_opp.init(
partial_env=env,
lines_attacked=env.name_line,
attack_every_xxx_hour=24,
average_attack_duration_hour=mean_duration_hour,
minimum_attack_duration_hour=1,
)
assert (
abs(np.mean(my_opp._attack_durations) - mean_duration_hour * 12)
< threshold
), f"error for {mean_duration_hour}: {np.mean(my_opp._attack_durations):.2f}"
def test_attack_every_xxx_hour(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True, chronics_class=ChangeNothing
) as env:
my_opp = GeometricOpponent(action_space=env.action_space)
n_ = 3_000_000
env.set_max_iter(n_)
threshold = 0.03 # balance between test speed and precision i ask to match the theoretical average
average_attack_duration_hour = 2
for mean_attack_every_xxx_hour in [12, 16, 20, 24, 48]:
my_opp.seed(1)
my_opp.init(
partial_env=env,
lines_attacked=env.name_line,
attack_every_xxx_hour=mean_attack_every_xxx_hour,
average_attack_duration_hour=average_attack_duration_hour,
minimum_attack_duration_hour=1,
)
std = np.sqrt(
(1 - my_opp._attack_hazard_rate)
/ (my_opp._attack_hazard_rate**2)
)
duration_avg = np.mean(
my_opp._attack_waiting_times + my_opp._attack_durations
)
assert (
abs(duration_avg - mean_attack_every_xxx_hour * 12)
< threshold * std
), f"error for {mean_attack_every_xxx_hour}: {duration_avg:.2f}"
def test_cannot_init_with_wrong_param(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
my_opp = GeometricOpponent(action_space=env.action_space)
with self.assertRaises(OpponentError):
# i cannot do an attack every 19 hours on average when an attack last 21h on average
my_opp.init(
partial_env=env,
lines_attacked=LINES_ATTACKED,
attack_every_xxx_hour=19,
average_attack_duration_hour=21,
minimum_attack_duration_hour=20,
)
with self.assertRaises(OpponentError):
# i cannot do an attack that last 19 hours on average and a minimum of 20 hours
my_opp.init(
partial_env=env,
lines_attacked=LINES_ATTACKED,
attack_every_xxx_hour=50,
average_attack_duration_hour=19,
minimum_attack_duration_hour=20,
)
def test_simulate(self):
"""test the opponent is working with the simulate function"""
init_budget = 500
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
line_id = 4
opponent_attack_duration = 31
first_attack_ts = 64
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=300, # only for testing
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
reco_line = env.action_space({"set_line_status": [(line_id, 1)]})
env.seed(0)
obs = env.reset()
opponent = env._opponent
assert np.all(opponent._attack_times == [64, 407, 487, 522])
assert np.all(opponent._attack_waiting_times == [64, 312, 48, 4])
assert np.all(opponent._attack_durations == [31, 32, 31, 25])
assert np.all(opponent._number_of_attacks == 4)
# do steps just before the first attack
for i in range(first_attack_ts):
obs, reward, done, info = env.step(env.action_space())
# i can simulate anything and it should be working
# opponent won't disconnect anything in simulate
simobs, sim_r, sim_d, sim_info = obs.simulate(env.action_space())
assert simobs.rho[line_id] > 0.0
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] > 0.0
# i do a step, powerline should be disconnected even if i reconnect it
# => basically i check the attack has been performed
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# check that the line disconnected cannot be reconnected
for i in range(opponent_attack_duration + 1):
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] == 0.0
assert not simobs.line_status[line_id]
# check that the opponent continue its attacks
for i in range(opponent_attack_duration - 1):
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# i should be able to simulate a reconnection now (attack is over)
simobs, sim_r, sim_d, sim_info = obs.simulate(reco_line)
assert simobs.rho[line_id] > 0.0
assert simobs.line_status[line_id]
# this should not affect the environment
assert obs.rho[line_id] == 0.0
assert not obs.line_status[line_id]
# and now that i'm able to reconnect the powerline in the real environment
obs, reward, done, info = env.step(reco_line)
assert obs.rho[line_id] > 0.0
assert obs.line_status[line_id]
def test_last_attack(self):
init_budget = 500
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"l2rpn_case14_sandbox",
test=True,
opponent_init_budget=init_budget,
opponent_budget_per_ts=200.0,
opponent_attack_cooldown=0, # only for testing
opponent_attack_duration=30, # max
opponent_action_class=TopologyAction,
opponent_budget_class=BaseActionBudget,
opponent_class=GeometricOpponent,
param=param,
kwargs_opponent={"lines_attacked": LINES_ATTACKED},
) as env:
env.seed(0)
_ = env.reset()
# opponent = env._opponent
# opponent._attack_durations : should be [31, 32, 31, 25]
# opponent._attack_times : should be [64, 407, 487, 522]
dn = env.action_space()
for ts in range(522):
# here the opponent cannot attack due to the `opponent_attack_duration` that is too low
# chosen duration is below max_duration, so attack is not done.
obs, reward, done, info = env.step(dn)
assert info["opponent_attack_line"] is None
# opponent should attack at this exact step
obs, reward, done, info = env.step(dn)
assert info["opponent_attack_line"] is not None
class TestChangeOppSpace(unittest.TestCase):
"""test i can change the opponent_space_type when creating an environment"""
def test_change_opp_space_type(self):
class OpponentSpaceCust(OpponentSpace):
pass
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_icaps_2021", test=True)
assert isinstance(env._oppSpace, OpponentSpace)
# check i can change it from "make"
env = grid2op.make("l2rpn_icaps_2021", opponent_space_type=OpponentSpaceCust, test=True)
assert isinstance(env._oppSpace, OpponentSpaceCust)
# check it's properly propagated when copied
env_cpy = env.copy()
assert isinstance(env_cpy._oppSpace, OpponentSpaceCust)
# check it's properly propagated in the kwargs
env_params = env.get_kwargs()
assert env_params["opponent_space_type"] == OpponentSpaceCust
# check it's properly propagated in the runner
runner_params = env.get_params_for_runner()
assert runner_params["opponent_space_type"] == OpponentSpaceCust
runner = Runner(**runner_params)
assert runner._opponent_space_type == OpponentSpaceCust
# check the runner can make an env with the right opponent space type
env_runner = runner.init_env()
assert isinstance(env_runner._oppSpace, OpponentSpaceCust)
if __name__ == "__main__":
unittest.main()
| 86,653 | 43.188679 | 117 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_PandaPowerBackend.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
from grid2op import make
from grid2op.tests.helper_path_test import PATH_DATA_TEST_PP, PATH_DATA_TEST
from grid2op.Backend import PandaPowerBackend
from grid2op.tests.helper_path_test import HelperTests
from grid2op.tests.BaseBackendTest import BaseTestNames
from grid2op.tests.BaseBackendTest import BaseTestLoadingCase
from grid2op.tests.BaseBackendTest import BaseTestLoadingBackendFunc
from grid2op.tests.BaseBackendTest import BaseTestTopoAction
from grid2op.tests.BaseBackendTest import BaseTestEnvPerformsCorrectCascadingFailures
from grid2op.tests.BaseBackendTest import BaseTestChangeBusAffectRightBus
from grid2op.tests.BaseBackendTest import BaseTestShuntAction
from grid2op.tests.BaseBackendTest import BaseTestResetEqualsLoadGrid
from grid2op.tests.BaseBackendTest import BaseTestVoltageOWhenDisco
from grid2op.tests.BaseBackendTest import BaseTestChangeBusSlack
from grid2op.tests.BaseBackendTest import BaseIssuesTest
from grid2op.tests.BaseBackendTest import BaseStatusActions
from grid2op.tests.BaseBackendTest import BaseTestStorageAction
PATH_DATA_TEST_INIT = PATH_DATA_TEST
PATH_DATA_TEST = PATH_DATA_TEST_PP
import warnings
warnings.simplefilter("error")
class TestNames(HelperTests, BaseTestNames):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST_INIT
class TestLoadingCase(HelperTests, BaseTestLoadingCase):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestLoadingBackendFunc(HelperTests, BaseTestLoadingBackendFunc):
def setUp(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestTopoAction(HelperTests, BaseTestTopoAction):
def setUp(self):
BaseTestTopoAction.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestTopoAction.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestEnvPerformsCorrectCascadingFailures(
HelperTests, BaseTestEnvPerformsCorrectCascadingFailures
):
def setUp(self):
BaseTestEnvPerformsCorrectCascadingFailures.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestEnvPerformsCorrectCascadingFailures.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_casefile(self):
return "test_case14.json"
def get_path(self):
return PATH_DATA_TEST
class TestChangeBusAffectRightBus(HelperTests, BaseTestChangeBusAffectRightBus):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestShuntAction(HelperTests, BaseTestShuntAction):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestResetEqualsLoadGrid(HelperTests, BaseTestResetEqualsLoadGrid):
def setUp(self):
BaseTestResetEqualsLoadGrid.setUp(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestVoltageOWhenDisco(HelperTests, BaseTestVoltageOWhenDisco):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestChangeBusSlack(HelperTests, BaseTestChangeBusSlack):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestIssuesTest(HelperTests, BaseIssuesTest):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestStatusAction(HelperTests, BaseStatusActions):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestStorageAction(HelperTests, BaseTestStorageAction):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
# Specific to pandapower power
class TestChangeBusAffectRightBus2(unittest.TestCase):
def skip_if_needed(self):
pass
def make_backend(self):
return PandaPowerBackend()
def test_set_bus(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
# action = env.action_space({"change_bus": {"lines_or_id": [17]}})
action = env.action_space({"set_bus": {"lines_or_id": [(17, 2)]}})
obs, reward, done, info = env.step(action)
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
def test_change_bus(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
def test_change_bustwice(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert not done
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
assert env.backend._grid["trafo"]["hv_bus"][2] == 18
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert not done
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 14
assert env.backend._grid["trafo"]["hv_bus"][2] == 4
if __name__ == "__main__":
unittest.main()
| 8,745 | 34.99177 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_PandaPowerBackendDefaultFunc.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
from grid2op import make
from grid2op.tests.helper_path_test import PATH_DATA_TEST_PP, PATH_DATA_TEST
from grid2op.Backend import PandaPowerBackend, Backend
from grid2op.dtypes import dt_int, dt_bool
from grid2op.tests.helper_path_test import HelperTests
from grid2op.tests.BaseBackendTest import BaseTestNames
from grid2op.tests.BaseBackendTest import BaseTestLoadingCase
from grid2op.tests.BaseBackendTest import BaseTestLoadingBackendFunc
from grid2op.tests.BaseBackendTest import BaseTestTopoAction
from grid2op.tests.BaseBackendTest import BaseTestEnvPerformsCorrectCascadingFailures
from grid2op.tests.BaseBackendTest import BaseTestChangeBusAffectRightBus
from grid2op.tests.BaseBackendTest import BaseTestShuntAction
from grid2op.tests.BaseBackendTest import BaseTestResetEqualsLoadGrid
from grid2op.tests.BaseBackendTest import BaseTestVoltageOWhenDisco
from grid2op.tests.BaseBackendTest import BaseTestChangeBusSlack
from grid2op.tests.BaseBackendTest import BaseIssuesTest
from grid2op.tests.BaseBackendTest import BaseStatusActions
PATH_DATA_TEST_INIT = PATH_DATA_TEST
PATH_DATA_TEST = PATH_DATA_TEST_PP
import warnings
warnings.simplefilter("error")
class PandaPowerBackendDefault(PandaPowerBackend):
"""
test the class for pandapower, if the default implementation of the backend are used, instead of the
more optimized pandapower implementation.
"""
def __init__(self, detailed_infos_for_cascading_failures=False):
PandaPowerBackend.__init__(
self,
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures,
)
def copy(self):
return Backend.copy(self)
def get_line_status(self):
return Backend.get_line_status(self)
def get_line_flow(self):
return Backend.get_line_flow(self)
def _disconnect_line(self, l_id):
return Backend._disconnect_line(self, l_id)
def get_topo_vect(self):
"""
otherwise there are some infinite recursions
"""
res = np.full(self.dim_topo, fill_value=np.NaN, dtype=dt_int)
line_status = np.concatenate(
(
self._grid.line["in_service"].values,
self._grid.trafo["in_service"].values,
)
).astype(dt_bool)
i = 0
for row in self._grid.line[["from_bus", "to_bus"]].values:
bus_or_id = row[0]
bus_ex_id = row[1]
if line_status[i]:
res[self.line_or_pos_topo_vect[i]] = (
1 if bus_or_id == self.line_or_to_subid[i] else 2
)
res[self.line_ex_pos_topo_vect[i]] = (
1 if bus_ex_id == self.line_ex_to_subid[i] else 2
)
else:
res[self.line_or_pos_topo_vect[i]] = -1
res[self.line_ex_pos_topo_vect[i]] = -1
i += 1
nb = self._grid.line.shape[0]
i = 0
for row in self._grid.trafo[["hv_bus", "lv_bus"]].values:
bus_or_id = row[0]
bus_ex_id = row[1]
j = i + nb
if line_status[j]:
res[self.line_or_pos_topo_vect[j]] = (
1 if bus_or_id == self.line_or_to_subid[j] else 2
)
res[self.line_ex_pos_topo_vect[j]] = (
1 if bus_ex_id == self.line_ex_to_subid[j] else 2
)
else:
res[self.line_or_pos_topo_vect[j]] = -1
res[self.line_ex_pos_topo_vect[j]] = -1
i += 1
i = 0
for bus_id in self._grid.gen["bus"].values:
res[self.gen_pos_topo_vect[i]] = 1 if bus_id == self.gen_to_subid[i] else 2
i += 1
i = 0
for bus_id in self._grid.load["bus"].values:
res[self.load_pos_topo_vect[i]] = (
1 if bus_id == self.load_to_subid[i] else 2
)
i += 1
# do not forget storage units !
i = 0
for bus_id in self._grid.storage["bus"].values:
res[self.storage_pos_topo_vect[i]] = (
1 if bus_id == self.storage_to_subid[i] else 2
)
i += 1
return res
class TestNames(HelperTests, BaseTestNames):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST_INIT
class TestLoadingCase(HelperTests, BaseTestLoadingCase):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestLoadingBackendFunc(HelperTests, BaseTestLoadingBackendFunc):
def setUp(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestLoadingBackendFunc.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestTopoAction(HelperTests, BaseTestTopoAction):
def setUp(self):
BaseTestTopoAction.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestTopoAction.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST
def get_casefile(self):
return "test_case14.json"
class TestEnvPerformsCorrectCascadingFailures(
HelperTests, BaseTestEnvPerformsCorrectCascadingFailures
):
def setUp(self):
BaseTestEnvPerformsCorrectCascadingFailures.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestEnvPerformsCorrectCascadingFailures.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_casefile(self):
return "test_case14.json"
def get_path(self):
return PATH_DATA_TEST
class TestChangeBusAffectRightBus(HelperTests, BaseTestChangeBusAffectRightBus):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestShuntAction(HelperTests, BaseTestShuntAction):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestResetEqualsLoadGrid(HelperTests, BaseTestResetEqualsLoadGrid):
def setUp(self):
BaseTestResetEqualsLoadGrid.setUp(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestVoltageOWhenDisco(HelperTests, BaseTestVoltageOWhenDisco):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestChangeBusSlack(HelperTests, BaseTestChangeBusSlack):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestIssuesTest(HelperTests, BaseIssuesTest):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestStatusAction(HelperTests, BaseStatusActions):
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackendDefault(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
# Specific to pandapower power
class TestChangeBusAffectRightBus2(unittest.TestCase):
def skip_if_needed(self):
pass
def make_backend(self):
return PandaPowerBackendDefault()
def test_set_bus(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
# action = env.action_space({"change_bus": {"lines_or_id": [17]}})
action = env.action_space({"set_bus": {"lines_or_id": [(17, 2)]}})
obs, reward, done, info = env.step(action)
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
def test_change_bus(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
def test_change_bustwice(self):
self.skip_if_needed()
backend = self.make_backend()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make('rte_case14_realistic', test=True, backend=backend)
env.reset()
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert not done
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 15
assert env.backend._grid["trafo"]["hv_bus"][2] == 18
action = env.action_space({"change_bus": {"lines_or_id": [17]}})
obs, reward, done, info = env.step(action)
assert not done
assert np.all(np.isfinite(obs.v_or))
assert np.sum(env.backend._grid["bus"]["in_service"]) == 14
assert env.backend._grid["trafo"]["hv_bus"][2] == 4
if __name__ == "__main__":
unittest.main()
| 11,615 | 34.2 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Parameters.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import tempfile
import json
from grid2op.Parameters import Parameters
class TestParameters(unittest.TestCase):
def test_default_builds(self):
p = Parameters()
def test_to_dict(self):
p = Parameters()
p_dict = p.to_dict()
assert isinstance(p_dict, dict)
def test_init_from_dict(self):
p = Parameters()
p_dict = p.to_dict()
p_dict["NB_TIMESTEP_OVERFLOW_ALLOWED"] = 42
p.init_from_dict(p_dict)
assert p.NB_TIMESTEP_OVERFLOW_ALLOWED == 42
def test_from_json(self):
p = Parameters()
p_dict = p.to_dict()
p_dict["NB_TIMESTEP_OVERFLOW_ALLOWED"] = 42
p_json = json.dumps(p_dict, indent=2)
with tempfile.NamedTemporaryFile(delete=False) as tf:
tf = tempfile.NamedTemporaryFile(delete=False)
tf.write(bytes(p_json, "utf-8"))
tf.close()
p2 = Parameters.from_json(tf.name)
assert p2.NB_TIMESTEP_OVERFLOW_ALLOWED == 42
def test_init_from_json(self):
p = Parameters()
p_dict = p.to_dict()
p_dict["NB_TIMESTEP_OVERFLOW_ALLOWED"] = 42
p_json = json.dumps(p_dict, indent=2)
with tempfile.NamedTemporaryFile(delete=False) as tf:
tf.write(bytes(p_json, "utf-8"))
tf.close()
p.init_from_json(tf.name)
assert p.NB_TIMESTEP_OVERFLOW_ALLOWED == 42
def _aux_check_attr_int(self, param, attr_name):
# don't work with string
setattr(param, attr_name, "toto")
with self.assertRaises(RuntimeError):
param.check_valid()
# don't work with list
setattr(param, attr_name, [1, 2])
with self.assertRaises(RuntimeError):
param.check_valid()
# dont work with set
setattr(param, attr_name, {1, 2})
with self.assertRaises(RuntimeError):
param.check_valid()
# work with bool
setattr(param, attr_name, True)
param.check_valid()
# work with float
setattr(param, attr_name, 2.0)
param.check_valid()
# work with int
setattr(param, attr_name, 1)
param.check_valid()
# check fail negative
setattr(param, attr_name, -2)
with self.assertRaises(RuntimeError):
param.check_valid()
# restore correct value
setattr(param, attr_name, 1)
param.check_valid()
def _aux_check_attr_float(self, param, attr_name):
tmp = getattr(param, attr_name)
# don't work with string
setattr(param, attr_name, "toto")
with self.assertRaises(RuntimeError):
param.check_valid()
# don't work with list
setattr(param, attr_name, [1, 2])
with self.assertRaises(RuntimeError):
param.check_valid()
# dont work with set
setattr(param, attr_name, {1, 2})
with self.assertRaises(RuntimeError):
param.check_valid()
# work with bool
setattr(param, attr_name, True)
param.check_valid()
# work with int value
setattr(param, attr_name, int(tmp))
param.check_valid()
# work with init value
setattr(param, attr_name, tmp)
param.check_valid()
def test_check_valid(self):
"""test the param.check_valid() is working correctly (accept valid param, reject wrong param)"""
p = Parameters()
p.check_valid() # default params are valid
# boolean attribute
p.NO_OVERFLOW_DISCONNECTION = 1
with self.assertRaises(RuntimeError):
p.check_valid()
p.NO_OVERFLOW_DISCONNECTION = True
p.IGNORE_MIN_UP_DOWN_TIME = "True"
with self.assertRaises(RuntimeError):
p.check_valid()
p.IGNORE_MIN_UP_DOWN_TIME = True
p.ACTIVATE_STORAGE_LOSS = 42.0
with self.assertRaises(RuntimeError):
p.check_valid()
p.ACTIVATE_STORAGE_LOSS = False
p.ENV_DC = [1, 2]
with self.assertRaises(RuntimeError):
p.check_valid()
p.ENV_DC = True
p.ALLOW_DISPATCH_GEN_SWITCH_OFF = {1, 2}
with self.assertRaises(RuntimeError):
p.check_valid()
p.ALLOW_DISPATCH_GEN_SWITCH_OFF = False
p.check_valid() # everything valid again
# int types
for attr_nm in [
"NB_TIMESTEP_OVERFLOW_ALLOWED",
"NB_TIMESTEP_RECONNECTION",
"NB_TIMESTEP_COOLDOWN_LINE",
"NB_TIMESTEP_COOLDOWN_SUB",
"MAX_SUB_CHANGED",
"MAX_LINE_STATUS_CHANGED",
]:
try:
self._aux_check_attr_int(p, attr_nm)
except Exception as exc_:
raise RuntimeError(f'Exception "{exc_}" for attribute "{attr_nm}"')
# float types
for attr_nm in ["HARD_OVERFLOW_THRESHOLD", "INIT_STORAGE_CAPACITY"]:
try:
self._aux_check_attr_float(p, attr_nm)
except Exception as exc_:
raise RuntimeError(f'Exception "{exc_}" for attribute "{attr_nm}"')
p.HARD_OVERFLOW_THRESHOLD = 0.5 # should not validate
with self.assertRaises(RuntimeError):
p.check_valid()
p.ACTIVATE_STORAGE_LOSS = -0.1 # should not validate
with self.assertRaises(RuntimeError):
p.check_valid()
p.ACTIVATE_STORAGE_LOSS = 1.1 # should not validate
with self.assertRaises(RuntimeError):
p.check_valid()
if __name__ == "__main__":
unittest.main()
| 6,055 | 33.605714 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_PlotGrid.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
from abc import ABC, abstractmethod
import unittest
import warnings
from grid2op.Exceptions import *
from grid2op.MakeEnv import make
from grid2op.PlotGrid import *
class BaseTestPlot(ABC):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make("rte_case14_redisp", test=True)
self.obs = self.env.current_obs
self.plot = self._plotter(self.env.observation_space)
def tearDown(self):
self.env.close()
@abstractmethod
def _plotter(self, obs_space):
pass
def test_plot_layout(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_layout()
def test_plot_info_line(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_info(
line_values=self.obs.rho, gen_values=None, load_values=None
)
def test_plot_info_gen(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_info(
line_values=None, gen_values=self.obs.prod_q, load_values=None
)
def test_plot_info_load(self):
self.plot.plot_info(
line_values=None, gen_values=None, load_values=self.obs.load_q
)
def test_plot_obs_default(self):
self.plot.plot_obs(self.obs)
def test_plot_obs_volts(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info="v", gen_info="v", load_info="v")
def test_plot_obs_invalid_line(self):
with self.assertRaises(PlotError):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(
self.obs, line_info="error", gen_info="v", load_info="v"
)
def test_plot_obs_no_line(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info=None, gen_info="p", load_info="p")
def test_plot_obs_invalid_gen(self):
with self.assertRaises(PlotError):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(
self.obs, line_info="v", gen_info="error", load_info="v"
)
def test_plot_obs_no_gen(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info="rho", gen_info=None, load_info="p")
def test_plot_obs_invalid_load(self):
with self.assertRaises(PlotError):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(
self.obs, line_info="rho", gen_info="v", load_info="error"
)
def test_plot_obs_no_load(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info="v", gen_info="v", load_info=None)
def test_plot_obs_line(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info="a", gen_info=None, load_info=None)
def test_plot_obs_gen(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info=None, gen_info="p", load_info=None)
def test_plot_obs_load(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.plot.plot_obs(self.obs, line_info=None, gen_info=None, load_info="p")
class TestPlotMatplot(BaseTestPlot, unittest.TestCase):
def _plotter(self, obs_space):
return PlotMatplot(obs_space)
class TestPlotPlotly(BaseTestPlot, unittest.TestCase):
def _plotter(self, obs_space):
return PlotPlotly(obs_space)
if __name__ == "__main__":
unittest.main()
| 4,620 | 34.007576 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_RedispatchEnv.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
from grid2op.tests.helper_path_test import PATH_DATA_TEST_PP, PATH_DATA_TEST
from grid2op.Backend import PandaPowerBackend
from grid2op.tests.helper_path_test import HelperTests
from grid2op.tests.BaseRedispTest import (
BaseTestRedispatch,
BaseTestRedispatchChangeNothingEnvironment,
)
from grid2op.tests.BaseRedispTest import (
BaseTestRedispTooLowHigh,
BaseTestDispatchRampingIllegalETC,
)
from grid2op.tests.BaseRedispTest import BaseTestLoadingAcceptAlmostZeroSumRedisp
PATH_DATA_TEST_INIT = PATH_DATA_TEST
PATH_DATA_TEST = PATH_DATA_TEST_PP
import warnings
warnings.simplefilter("error")
class TestRedispatch(HelperTests, BaseTestRedispatch):
def setUp(self):
# TODO find something more elegant
BaseTestRedispatch.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestRedispatch.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST_PP
def get_casefile(self):
return "test_case14.json"
class TestRedispatchChangeNothingEnvironment(
HelperTests, BaseTestRedispatchChangeNothingEnvironment
):
def setUp(self):
# TODO find something more elegant
BaseTestRedispatchChangeNothingEnvironment.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestRedispatchChangeNothingEnvironment.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
def get_path(self):
return PATH_DATA_TEST_PP
def get_casefile(self):
return "test_case14.json"
class TestRedispTooLowHigh(HelperTests, BaseTestRedispTooLowHigh):
def setUp(self):
# TODO find something more elegant
BaseTestRedispTooLowHigh.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestRedispTooLowHigh.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestDispatchRampingIllegalETC(HelperTests, BaseTestDispatchRampingIllegalETC):
def setUp(self):
# TODO find something more elegant
BaseTestDispatchRampingIllegalETC.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestDispatchRampingIllegalETC.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
class TestLoadingAcceptAlmostZeroSumRedisp(
HelperTests, BaseTestLoadingAcceptAlmostZeroSumRedisp
):
def setUp(self):
# TODO find something more elegant
BaseTestLoadingAcceptAlmostZeroSumRedisp.setUp(self)
def tearDown(self):
# TODO find something more elegant
BaseTestLoadingAcceptAlmostZeroSumRedisp.tearDown(self)
def make_backend(self, detailed_infos_for_cascading_failures=False):
return PandaPowerBackend(
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
)
if __name__ == "__main__":
unittest.main()
| 4,045 | 31.111111 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Reward.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import pdb
import warnings
import numbers
from abc import ABC, abstractmethod
import grid2op
from grid2op.tests.helper_path_test import *
from grid2op.Reward import *
from grid2op.MakeEnv import make
from grid2op.Parameters import Parameters
from grid2op.Runner import Runner
from grid2op.Agent import BaseAgent
import warnings
class TestLoadingReward(ABC):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case5_example", test=True, reward_class=self._reward_type()
)
self.action = self.env.action_space()
self.has_error = False
self.is_done = False
self.is_illegal = False
self.is_ambiguous = False
def tearDown(self):
self.env.close()
@abstractmethod
def _reward_type(self):
pass
def test_reward(self):
_, r_, _, _ = self.env.step(self.action)
assert isinstance(r_, numbers.Number)
assert issubclass(self._reward_type(), BaseReward)
class TestLoadingConstantReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return ConstantReward
class TestLoadingEconomicReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return EconomicReward
class TestLoadingFlatReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return FlatReward
class TestLoadingL2RPNReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return L2RPNReward
class TestLoadingRedispReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return RedispReward
class TestLoadingBridgeReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return BridgeReward
class TestLoadingL2RPNSandBoxScore(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return L2RPNSandBoxScore
class TestLoadingLinesCapacityReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return LinesCapacityReward
class TestDistanceReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return DistanceReward
def test_do_nothing(self):
self.env.reset()
dn_action = self.env.action_space({})
obs, r, d, info = self.env.step(dn_action)
max_reward = self.env._reward_helper.range()[1]
assert r == max_reward
def test_disconnect(self):
self.env.reset()
set_status = self.env.action_space.get_set_line_status_vect()
set_status[1] = -1
disconnect_action = self.env.action_space({"set_line_status": set_status})
obs, r, d, info = self.env.step(disconnect_action)
assert r < 1.0
def test_setBus2(self):
self.env.reset()
set_action = self.env.action_space({"set_bus": {"lines_or_id": [(0, 2)]}})
obs, r, d, info = self.env.step(set_action)
assert r != 1.0
class TestLoadingGameplayReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return GameplayReward
class TestCombinedReward(TestLoadingReward, unittest.TestCase):
def _reward_type(self):
return CombinedReward
def test_add_reward(self):
cr = self.env._reward_helper.template_reward
assert cr is not None
cr.addReward("Gameplay", GameplayReward(), 1.0)
cr.addReward("Flat", FlatReward(), 1.0)
cr.initialize(self.env)
def test_remove_reward(self):
cr = self.env._reward_helper.template_reward
assert cr is not None
added = cr.addReward("Gameplay", GameplayReward(), 1.0)
assert added == True
removed = cr.removeReward("Gameplay")
assert removed == True
removed = cr.removeReward("Unknow")
assert removed == False
def test_update_reward_weight(self):
cr = self.env._reward_helper.template_reward
assert cr is not None
added = cr.addReward("Gameplay", GameplayReward(), 1.0)
assert added == True
updated = cr.updateRewardWeight("Gameplay", 0.5)
assert updated == True
updated = cr.updateRewardWeight("Unknow", 0.5)
assert updated == False
def test_combine_distance_gameplay(self):
cr = self.env._reward_helper.template_reward
assert cr is not None
added = cr.addReward("Gameplay", GameplayReward(), 0.5)
assert added == True
distance_reward = DistanceReward()
added = cr.addReward("Distance", distance_reward, 0.5)
assert added == True
self.env.reset()
cr.initialize(self.env)
set_action = self.env.action_space({"set_bus": {"lines_or_id": [(1, 2)]}})
obs, r, d, info = self.env.step(set_action)
assert r < 1.0
def test_combine_simulate(self):
cr = self.env._reward_helper.template_reward
assert cr is not None
gr = GameplayReward()
gr.set_range(-21.0, 21.0)
added = cr.addReward("Gameplay", gr, 2.0)
assert added is True
self.env.change_reward(cr)
obs = self.env.reset()
assert self.env.reward_range == (-42, 42)
_, reward, done, info = obs.simulate(self.env.action_space({}))
assert done is False
assert reward == 42.0
class TestIncreaseFlatReward(unittest.TestCase):
def test_ok(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"l2rpn_case14_sandbox", reward_class=IncreasingFlatReward, test=True
)
assert env.nb_time_step == 0
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 1
assert reward == 1
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 2
assert reward == 2
obs = env.reset()
assert env.nb_time_step == 0
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 1
assert reward == 1
class TestEpisodeDurationReward(unittest.TestCase):
def test_ok(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"l2rpn_case14_sandbox", reward_class=EpisodeDurationReward, test=True
)
assert env.nb_time_step == 0
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 1
assert reward == 0
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 2
assert reward == 0
obs, reward, done, info = env.step(
env.action_space({"set_bus": {"generators_id": [(0, -1)]}})
)
assert done
assert env.nb_time_step == 3
assert reward == 3.0 / 575.0
obs = env.reset()
assert env.nb_time_step == 0
obs, reward, done, info = env.step(env.action_space())
assert env.nb_time_step == 1
assert reward == 0
env.fast_forward_chronics(573)
obs, reward, done, info = env.step(env.action_space())
assert done
assert env.nb_time_step == 575
assert reward == 1.0
class TestN1Reward(unittest.TestCase):
def test_ok(self):
L_ID = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"l2rpn_case14_sandbox", reward_class=N1Reward(l_id=L_ID), test=True
)
obs = env.reset()
obs, reward, *_ = env.step(env.action_space())
# obs._obs_env._reward_helper.template_reward._DEBUG = True
obs_n1, *_ = obs.simulate(
env.action_space({"set_line_status": [(L_ID, -1)]}), time_step=0
)
assert obs_n1.rho[L_ID] == 0 # line should have been disconnected
assert (
abs(reward - obs_n1.rho.max()) <= 1e-5
), "the correct reward has not been computed"
env.close()
L_IDS = [0, 1]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"l2rpn_case14_sandbox",
other_rewards={f"line_{l_id}": N1Reward(l_id=l_id) for l_id in L_IDS},
test=True,
)
obs, reward, done, info = env.step(env.action_space())
for l_id in L_IDS:
obs_n1, *_ = obs.simulate(
env.action_space({"set_line_status": [(l_id, -1)]}), time_step=0
)
assert (
abs(info["rewards"][f"line_{l_id}"] - obs_n1.rho.max()) <= 1e-5
), f"the correct reward has not been computed for line {l_id}"
env.close()
class TMPRewardForTest(BaseReward):
def __call__(self, action, env, has_error, is_done, is_illegal, is_ambiguous):
if is_done:
assert not has_error
return super().__call__(action, env, has_error, is_done, is_illegal, is_ambiguous)
class ErrorAgent(BaseAgent):
def act(self, observation, reward, done=False):
if observation.current_step == 9:
return self.action_space({"set_bus": {"loads_id": [(0, -1)]}}) # force a game over
return super().act(observation, reward, done)
class TestEndOfEpisode(unittest.TestCase):
"""test the appropriate flags at the end of an episode"""
def setUp(self) -> None:
param = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True, reward_class=TMPRewardForTest)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_ok_end_of_episode(self):
# done = False
# i = 0
# while not done:
# obs, reward, done, info = self.env.step(self.env.action_space())
# i += 1
# assert i == 575, f"{i = } vs 575"
# above passed and took more than 30s
self.env.set_max_iter(10)
# episode goes until the end, no error is raised
self.env.reset()
done = False
i = 0
while not done:
obs, reward, done, info = self.env.step(self.env.action_space())
i += 1
assert i == 10, f"{i = } vs 10"
# agent does a game over, the reward should raise an error
self.env.reset()
done = False
i = 0
while i <= 1:
obs, reward, done, info = self.env.step(self.env.action_space())
i += 1
with self.assertRaises(AssertionError):
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"loads_id": [(0, -1)]}}))
# agent does a game over at last step, the reward should raise an error
self.env.reset()
done = False
i = 0
while i <= 8:
obs, reward, done, info = self.env.step(self.env.action_space())
i += 1
with self.assertRaises(AssertionError):
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"loads_id": [(0, -1)]}}))
def test_runner(self):
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1, max_iter=10)
assert res[0][3] == 10
runner = Runner(**self.env.get_params_for_runner(),
agentClass=ErrorAgent)
# error before last observation
with self.assertRaises(AssertionError):
res = runner.run(nb_episode=1, max_iter=11)
# error just at last observation
with self.assertRaises(AssertionError):
res = runner.run(nb_episode=1, max_iter=10)
# no error
res = runner.run(nb_episode=1, max_iter=9)
if __name__ == "__main__":
unittest.main()
| 12,476 | 32.272 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_RewardNewRenewableSourcesUsageScore.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import unittest
import grid2op
from grid2op.Reward import _NewRenewableSourcesUsageScore
from grid2op.Agent import DoNothingAgent, BaseAgent
class CurtailTrackerAgent(BaseAgent):
def __init__(self, action_space, gen_renewable, gen_pmax, curtail_level=1.):
super().__init__(action_space)
self.gen_renewable = gen_renewable
self.gen_pmax = gen_pmax[gen_renewable]
self.curtail_level = curtail_level
def act(self, obs, reward, done):
curtail_target = self.curtail_level * obs.gen_p_before_curtail[self.gen_renewable] / self.gen_pmax
act = self.action_space(
{"curtail": [(el, ratio) for el, ratio in zip(np.arange(len(self.gen_renewable))[self.gen_renewable], curtail_target)]}
)
return act
class DoNothingSimulatorAgent(DoNothingAgent):
def __init__(self, action_space, nres_id, gen_pmax):
super().__init__(action_space)
self.nres_id = nres_id
self.gen_pmax = gen_pmax
def act(self, obs, reward, done):
curtail_target = 0.5 * obs.gen_p_before_curtail[self.nres_id] / self.gen_pmax[self.nres_id]
act = self.action_space(
{"curtail": [(el, ratio) for el, ratio in zip(self.nres_id, curtail_target)]}
)
sim_obs_1, *_ = obs.simulate(act, time_step=1)
return super().act(obs, reward, done)
class TestNewRenewableSourcesUsageScore(unittest.TestCase):
def setUp(self) -> None:
env_name = "l2rpn_case14_sandbox"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(env_name,
reward_class = _NewRenewableSourcesUsageScore,
test=True
)
self.env.set_max_iter(20)
self.env.parameters.NO_OVERFLOW_DISCONNECTION = True
self.nres_id = np.arange(self.env.n_gen)[self.env.gen_renewable]
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_surlinear_function(self):
#for recalls, use nres_ratio percentages between 50 and 100
delta_x = 0.5
x = np.arange(start=50, stop=100, step=delta_x)
f_x = _NewRenewableSourcesUsageScore._surlinear_func_curtailment(x)
gradient_f = (f_x[1:] - f_x[:-1]) / delta_x
assert all(gradient_f > 1 / 50)
assert all(np.equal(np.argsort(gradient_f),np.arange(len(gradient_f), dtype=int)))
def test_capitalization_score(self):
my_agent = DoNothingAgent(self.env.action_space)
done = False
reward = self.env.reward_range[0]
gen_res_p_curtailed_array = np.zeros(self.env.chronics_handler.max_timestep())
gen_res_p_before_curtail_array = np.zeros(self.env.chronics_handler.max_timestep())
obs = self.env.reset()
while True:
gen_res_p_curtailed_array[self.env.nb_time_step] = np.sum(obs.gen_p[self.env.gen_renewable])
gen_res_p_before_curtail_array[self.env.nb_time_step] = np.sum(obs.gen_p_before_curtail[self.env.gen_renewable])
action = my_agent.act(obs, reward, done)
obs, reward, done, _ = self.env.step(action)
if done:
break
return all(
[
np.array_equal(self.env._reward_helper.template_reward.gen_res_p_curtailed_list, gen_res_p_curtailed_array),
np.array_equal(self.env._reward_helper.template_reward.gen_res_p_before_curtail_list, gen_res_p_before_curtail_array),
reward == _NewRenewableSourcesUsageScore._surlinear_func_curtailment(100 * np.sum(gen_res_p_curtailed_array[1:]) / np.sum(gen_res_p_before_curtail_array[1:]))
]
)
def test_reward_after_blackout(self):
for blackout_time_step in [1,3,10]:
my_agent = DoNothingAgent(self.env.action_space)
done = False
reward = self.env.reward_range[0]
obs = self.env.reset()
while True:
if self.env.nb_time_step + 1 > blackout_time_step:
blackout_act = {"set_bus": {"generators_id": (0,-1)}}
action = self.env.action_space(blackout_act)
else:
action = my_agent.act(obs, reward, done)
obs, reward, done, _ = self.env.step(action)
if done:
break
assert reward == 1.
def test_reward_value(self):
for curtail_target, ratio_curtail_expected in [
(0.5, 50.84402431116107),
(0.65, 66.09722918973647),
(0.8, 81.35044050770632),
(0.9, 91.51924150630187),
(1., 99.96623954270511)
]:
my_agent = CurtailTrackerAgent(self.env.action_space,
gen_renewable = self.env.gen_renewable,
gen_pmax=self.env.gen_pmax,
curtail_level = curtail_target)
self.env.seed(0)
self.env.set_id(0)
obs = self.env.reset()
done = False
reward = self.env.reward_range[0]
while True:
action = my_agent.act(obs, reward, done)
obs, reward, done, _ = self.env.step(action)
if done:
break
assert reward == _NewRenewableSourcesUsageScore._surlinear_func_curtailment(ratio_curtail_expected)
def test_simulate_ignored(self):
my_agent = DoNothingSimulatorAgent(self.env.action_space,
nres_id = np.arange(self.env.n_gen)[self.env.gen_renewable],
gen_pmax=self.env.gen_pmax,)
done = False
reward = self.env.reward_range[0]
obs = self.env.reset()
while True:
action = my_agent.act(obs, reward, done)
obs, reward, done, _ = self.env.step(action)
if done:
break
return reward == 1.
if __name__ == "__main__":
unittest.main()
| 6,782 | 42.76129 | 174 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Rules.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
from grid2op.tests.helper_path_test import *
from grid2op.dtypes import dt_int, dt_bool, dt_float
from grid2op.Exceptions import *
from grid2op.Environment import Environment
from grid2op.Backend import PandaPowerBackend
from grid2op.Parameters import Parameters
from grid2op.Chronics import ChronicsHandler, GridStateFromFile
from grid2op.Rules import *
from grid2op.MakeEnv import make
import warnings
warnings.simplefilter("error")
class TestLoadingBackendFunc(unittest.TestCase):
def setUp(self):
# powergrid
self.adn_backend = PandaPowerBackend()
self.path_matpower = PATH_DATA_TEST_PP
self.case_file = "test_case14.json"
# data
self.path_chron = os.path.join(PATH_CHRONICS, "chronics")
self.chronics_handler = ChronicsHandler(
chronicsClass=GridStateFromFile, path=self.path_chron
)
self.tolvect = 1e-2
self.tol_one = 1e-5
# force the verbose backend
self.adn_backend.detailed_infos_for_cascading_failures = True
# _parameters for the environment
self.env_params = Parameters()
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = Environment(
init_grid_path=os.path.join(self.path_matpower, self.case_file),
backend=self.adn_backend,
init_env_path=os.path.join(self.path_matpower, self.case_file),
chronics_handler=self.chronics_handler,
parameters=self.env_params,
names_chronics_to_backend=self.names_chronics_to_backend,
name="test_rules_env1",
)
self.helper_action = self.env._helper_action_env
def test_AlwaysLegal(self):
# build a random action acting on everything
new_vect = np.random.randn(self.helper_action.n_load)
new_vect2 = np.random.randn(self.helper_action.n_load)
change_status_orig = np.random.randint(0, 2, self.helper_action.n_line).astype(
dt_bool
)
set_status_orig = np.random.randint(-1, 2, self.helper_action.n_line)
set_status_orig[change_status_orig] = 0
change_topo_vect_orig = np.random.randint(
0, 2, self.helper_action.dim_topo
).astype(dt_bool)
# powerline that are set to be reconnected, can't be moved to another bus
change_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == 1]
] = False
change_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == 1]
] = False
# powerline that are disconnected, can't be moved to the other bus
change_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == -1]
] = False
change_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == -1]
] = False
set_topo_vect_orig = np.random.randint(0, 3, self.helper_action.dim_topo)
set_topo_vect_orig[change_topo_vect_orig] = 0 # don't both change and set
# I need to make sure powerlines that are reconnected are indeed reconnected to a bus
set_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == 1]
] = 1
set_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == 1]
] = 1
# I need to make sure powerlines that are disconnected are not assigned to a bus
set_topo_vect_orig[
self.helper_action.line_or_pos_topo_vect[set_status_orig == -1]
] = 0
set_topo_vect_orig[
self.helper_action.line_ex_pos_topo_vect[set_status_orig == -1]
] = 0
action = self.helper_action(
{
"change_bus": change_topo_vect_orig,
"set_bus": set_topo_vect_orig,
"injection": {"load_p": new_vect, "load_q": new_vect2},
"change_line_status": change_status_orig,
"set_line_status": set_status_orig,
}
)
# game rules
gr = RulesChecker()
assert gr.legal_action(action, self.env)
def test_LookParam(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=LookParam
).legal_action
self.env._parameters.MAX_SUB_CHANGED = 2
self.env._parameters.MAX_LINE_STATUS_CHANGED = 2
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
try:
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 2
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
try:
self.env._parameters.MAX_SUB_CHANGED = 2
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
def test_PreventReconection(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 2
act = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
_ = self.env.step(act)
try:
self.env._parameters.MAX_SUB_CHANGED = 2
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
self.env._times_before_line_status_actionable[id_line] = 1
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
self.env._times_before_line_status_actionable[:] = 0
self.env._parameters.MAX_SUB_CHANGED = 2
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
self.env._times_before_line_status_actionable[1] = 1
_ = self.helper_action(
{
"change_bus": {"substations_id": [(id_1, arr1)]},
"set_bus": {"substations_id": [(id_2, arr2)]},
"change_line_status": arr_line1,
"set_line_status": arr_line2,
},
env=self.env,
check_legal=True,
)
def test_linereactionnable_throw(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_line_status_deactivated = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
self.env.step(act)
try:
# i try to react on it, it should throw an IllegalAction exception.
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
def test_linereactionnable_nothrow(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_line_status_deactivated = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
self.env.step(act)
# i compute another time step without doing anything
self.env.step(self.helper_action({}))
# i try to react on it, it should NOT throw an IllegalAction exception, but
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
def test_linereactionnable_throw_longerperiod(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_line_status_deactivated = 2
self.env._parameters.NB_TIMESTEP_LINE_STATUS_REMODIF = 2
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
_ = self.env.step(act)
# i compute another time step without doing anything
_ = self.env.step(self.helper_action({}))
# i try to react on it, it should throw an IllegalAction exception because we ask the environment to wait
# at least 2 time steps
try:
# i try to react on it, it should throw an IllegalAction exception.
act = self.helper_action(
{"set_line_status": arr_line2}, env=self.env, check_legal=True
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
def test_toporeactionnable_throw(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_topology_deactivated = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
self.env.step(act)
try:
# i try to react on it, it should throw an IllegalAction exception.
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
def test_toporeactionnable_nothrow(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_topology_deactivated = 1
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
self.env.step(act)
# i compute another time step without doing anything
self.env.step(self.helper_action({}))
# i try to react on it, it should NOT throw an IllegalAction exception, but
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
def test_toporeactionnable_throw_longerperiod(self):
id_1 = 1
id_2 = 12
id_line = 17
id_line2 = 15
arr1 = np.array([False, False, False, True, True, True], dtype=dt_bool)
arr2 = np.array([1, 1, 2, 2], dtype=dt_int)
arr_line1 = np.full(self.helper_action.n_line, fill_value=False, dtype=dt_bool)
arr_line1[id_line] = True
arr_line2 = np.full(self.helper_action.n_line, fill_value=0, dtype=dt_int)
arr_line2[id_line2] = -1
self.env._max_timestep_topology_deactivated = 2
self.helper_action.legal_action = RulesChecker(
legalActClass=PreventReconnection
).legal_action
# i act a first time on powerline 15
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
self.env.step(act)
# i compute another time step without doing anything
self.env.step(self.helper_action({}))
# i try to react on it, it should throw an IllegalAction exception because we ask the environment to wait
# at least 2 time steps
try:
# i try to react on it, it should throw an IllegalAction exception.
act = self.helper_action(
{"set_bus": {"substations_id": [(id_2, arr2)]}},
env=self.env,
check_legal=True,
)
raise RuntimeError("This should have thrown an IllegalException")
except IllegalAction:
pass
class TestCooldown(unittest.TestCase):
def setUp(self):
params = Parameters()
params.NB_TIMESTEP_COOLDOWN_LINE = 5
params.NB_TIMESTEP_COOLDOWN_SUB = 15
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"rte_case5_example",
test=True,
gamerules_class=DefaultRules,
param=params,
)
def tearDown(self):
self.env.close()
def test_cooldown_sub(self):
sub_id = 2
act = self.env.action_space(
{"set_bus": {"substations_id": [(sub_id, [1, 1, 2, 2])]}}
)
obs, reward, done, info = self.env.step(act)
assert not done
assert obs.time_before_cooldown_sub[sub_id] == 15
# the next action is illegal because it consist in reconfiguring the same substation
act = self.env.action_space(
{"set_bus": {"substations_id": [(sub_id, [1, 1, 1, 1])]}}
)
obs, reward, done, info = self.env.step(act)
assert not done
assert info["is_illegal"]
assert obs.time_before_cooldown_sub[sub_id] == 14
def test_cooldown_line(self):
line_id = 1
act = self.env.action_space({"set_line_status": [(line_id, -1)]})
obs, reward, done, info = self.env.step(act)
assert not done
assert obs.time_before_cooldown_line[line_id] == 5
act = self.env.action_space({"set_line_status": [(line_id, +1)]})
obs, reward, done, info = self.env.step(act)
assert not done
assert info["is_illegal"]
assert obs.time_before_cooldown_line[line_id] == 4
class TestReconnectionsLegality(unittest.TestCase):
def test_reconnect_already_connected(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_case2 = make("rte_case5_example", test=True)
obs = env_case2.reset() # reset is good
obs, reward, done, info = env_case2.step(
env_case2.action_space()
) # do the action, it's valid
# powerline 5 is connected
# i fake a reconnection of it
act_case2 = env_case2.action_space.reconnect_powerline(
line_id=5, bus_or=2, bus_ex=1
)
obs_case2, reward_case2, done_case2, info_case2 = env_case2.step(act_case2)
# this was illegal before, but test it is still illegal
assert info_case2["is_illegal"], (
"action should be illegal as it consists of change both ends of a "
"powerline, while authorizing only 1 substations change"
)
def test_reconnect_disconnected(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
params = Parameters()
params.MAX_SUB_CHANGED = 0
params.NO_OVERFLOW_DISCONNECTION = True
env_case2 = make("rte_case5_example", test=True, param=params)
obs = env_case2.reset() # reset is good
line_id = 5
# Disconnect the line
disco_act = env_case2.action_space.disconnect_powerline(line_id=line_id)
obs, reward, done, info = env_case2.step(disco_act)
# Line has been disconnected
assert info["is_illegal"] == False
assert done == False
assert np.sum(obs.line_status) == (env_case2.n_line - 1)
# Reconnect the line
reco_act = env_case2.action_space.reconnect_powerline(
line_id=line_id, bus_or=1, bus_ex=2
)
obs, reward, done, info = env_case2.step(reco_act)
# Check reconnecting is legal
assert info["is_illegal"] == False
assert done == False
# Check line has been reconnected
assert np.sum(obs.line_status) == (env_case2.n_line)
def test_sub_dont_change(self):
"""test that i cannot reconect a powerline by acting on the substation"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
params = Parameters()
params.MAX_SUB_CHANGED = 1
params.MAX_LINE_STATUS_CHANGED = 1
params.NB_TIMESTEP_COOLDOWN_LINE = 3
params.NB_TIMESTEP_COOLDOWN_SUB = 3
params.NO_OVERFLOW_DISCONNECTION = True
env = make("rte_case5_example", test=True, param=params)
l_id = 2
# prepare the actions
disco_act = env.action_space.disconnect_powerline(line_id=l_id)
reco_act = env.action_space.reconnect_powerline(
line_id=l_id, bus_or=1, bus_ex=1
)
set_or_1_act = env.action_space({"set_bus": {"lines_or_id": [(l_id, 1)]}})
set_ex_1_act = env.action_space({"set_bus": {"lines_ex_id": [(l_id, 1)]}})
obs, reward, done, info = env.step(disco_act)
assert obs.rho[l_id] == 0.0
assert obs.time_before_cooldown_line[l_id] == 3
assert env.backend._grid.line.iloc[l_id]["in_service"] == False
# i have a cooldown to 2 so i cannot reconnect it
assert obs.time_before_cooldown_line[l_id] == 3
obs, reward, done, info = env.step(reco_act)
assert obs.rho[l_id] == 0.0
assert info["is_illegal"]
assert obs.time_before_cooldown_line[l_id] == 2
assert env.backend._grid.line.iloc[l_id]["in_service"] == False
# this is not supposed to reconnect it either (cooldown)
assert obs.time_before_cooldown_line[l_id] == 2
obs, reward, done, info = env.step(set_or_1_act)
# pdb.set_trace()
# assert info["is_illegal"]
assert env.backend._grid.line.iloc[l_id]["in_service"] == False
assert obs.rho[l_id] == 0.0
assert obs.time_before_cooldown_line[l_id] == 1
assert env.backend._grid.line.iloc[l_id]["in_service"] == False
# and neither is that (cooldown)
assert obs.time_before_cooldown_line[l_id] == 1
obs, reward, done, info = env.step(set_ex_1_act)
assert obs.rho[l_id] == 0.0
assert obs.time_before_cooldown_line[l_id] == 0
assert env.backend._grid.line.iloc[l_id]["in_service"] == False
# and now i can reconnect
obs, reward, done, info = env.step(reco_act)
assert obs.rho[l_id] != 0.0
assert obs.time_before_cooldown_line[l_id] == 3
assert env.backend._grid.line.iloc[l_id]["in_service"] == True
class TestSubstationImpactLegality(unittest.TestCase):
def setUp(self):
# Create env with custom params
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.params = Parameters()
self.env = make("rte_case5_example", test=True, param=self.params)
def tearDown(self):
self.env.close()
def test_setbus_line_no_sub_allowed_is_illegal(self):
# Set 0 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 0
# Make a setbus
LINE_ID = 4
bus_action = self.env.action_space({"set_bus": {"lines_ex_id": [(LINE_ID, 2)]}})
# Make sure its illegal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == True
def test_two_setbus_line_one_sub_allowed_is_illegal(self):
# Set 1 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 1
# Make a double setbus
LINE1_ID = 4
LINE2_ID = 5
bus_action = self.env.action_space(
{"set_bus": {"lines_ex_id": [(LINE1_ID, 2), (LINE2_ID, 2)]}}
)
# Make sure its illegal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == True
def test_one_setbus_line_one_sub_allowed_is_legal(self):
# Set 1 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 1
# Make a setbus
LINE1_ID = 4
bus_action = self.env.action_space(
{"set_bus": {"lines_ex_id": [(LINE1_ID, 2)]}}
)
# Make sure its legal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == False
def test_two_setbus_line_two_sub_allowed_is_legal(self):
# Set 2 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 2
# Make a double setbus
LINE1_ID = 4
LINE2_ID = 5
bus_action = self.env.action_space(
{"set_bus": {"lines_ex_id": [(LINE1_ID, 2), (LINE2_ID, 2)]}}
)
# Make sure its legal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == False
def test_changebus_line_no_sub_allowed_is_illegal(self):
# Set 0 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 0
# Make a changebus
LINE_ID = 4
bus_action = self.env.action_space({"change_bus": {"lines_ex_id": [LINE_ID]}})
# Make sure its illegal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == True
def test_changebus_line_one_sub_allowed_is_legal(self):
# Set 1 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 1
# Make a changebus
LINE_ID = 4
bus_action = self.env.action_space({"change_bus": {"lines_ex_id": [LINE_ID]}})
# Make sure its legal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == False
def test_changebus_two_line_one_sub_allowed_is_illegal(self):
# Set 1 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 1
# Make a changebus
LINE1_ID = 4
LINE2_ID = 5
bus_action = self.env.action_space(
{"change_bus": {"lines_ex_id": [LINE1_ID, LINE2_ID]}}
)
# Make sure its illegal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == True
def test_changebus_two_line_two_sub_allowed_is_legal(self):
# Set 2 allowed substation changes
self.env._parameters.MAX_SUB_CHANGED = 2
# Make a changebus
LINE1_ID = 4
LINE2_ID = 5
bus_action = self.env.action_space(
{"change_bus": {"lines_ex_id": [LINE1_ID, LINE2_ID]}}
)
# Make sure its legal
_, _, _, i = self.env.step(bus_action)
assert i["is_illegal"] == False
class TestLoadingFromInstance(unittest.TestCase):
def test_correct(self):
rules = AlwaysLegal()
rules.TOTO = 1
try:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("rte_case5_example", test=True, gamerules_class=rules)
assert hasattr(env._game_rules.legal_action, "TOTO")
assert env._game_rules.legal_action.TOTO == 1
finally:
env.close()
if __name__ == "__main__":
unittest.main()
| 30,314 | 36.752179 | 113 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_RulesByArea.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
from itertools import chain
from grid2op.tests.helper_path_test import *
from grid2op.Exceptions import *
from grid2op.Parameters import Parameters
from grid2op.Rules.rulesByArea import *
from grid2op.MakeEnv import make
from grid2op.Agent import OneChangeThenNothing
from grid2op.Runner import Runner
import warnings
class TestDefaultRulesByArea(unittest.TestCase):
def setUp(self):
n_sub = 14
self.rules_1area = RulesByArea([[int(k) for k in range(n_sub)]])
self.rules_2areas = RulesByArea([[k for k in np.arange(n_sub,dtype=int)[:8]],[k for k in np.arange(n_sub,dtype=int)[8:]]])
self.rules_3areas = RulesByArea([[k for k in np.arange(n_sub,dtype=int)[:4]],[k for k in np.arange(n_sub,dtype=int)[4:9]],[k for k in np.arange(n_sub,dtype=int)[9:]]])
def test_legal_when_islegal(self):
params = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
#noaction
self.env = make(
"l2rpn_case14_sandbox",
test=True,
param=params,
gamerules_class = self.rules_1area
)
self.helper_action = self.env._helper_action_env
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
act = {}
_ = self.helper_action(
act,
env=self.env,
check_legal=True,
)
#test allowance max action in all areas over the grid
for rules in [self.rules_2areas, self.rules_3areas]:
self.env = make(
"l2rpn_case14_sandbox",
test=True,
param=params,
gamerules_class = rules
)
self.helper_action = self.env._helper_action_env
lines_by_area = self.env._game_rules.legal_action.lines_id_by_area
line_select = [[int(k) for k in np.random.choice(list_ids, size=3, replace=False)] for list_ids in lines_by_area.values()]
#one line one sub with one action per area per item per area
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
act = {
"set_line_status": [(LINE_ID, -1) for LINE_ID in list(chain(*[list_ids[:1] for list_ids in line_select]))],
"change_bus" : {"lines_or_id":[LINE_ID for LINE_ID in list(chain(*[list_ids[1:2] for list_ids in line_select]))]}
}
_ = self.helper_action(
act,
env=self.env,
check_legal=True,
)
#two lines one sub with two actions per line one per sub per area
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 2
act = {
"set_line_status": [(LINE_ID, -1) for LINE_ID in list(chain(*[list_ids[:2] for list_ids in line_select]))],
"change_bus" : {"lines_or_id":[LINE_ID for LINE_ID in list(chain(*[list_ids[2:] for list_ids in line_select]))]}
}
_ = self.helper_action(
act,
env=self.env,
check_legal=True,
)
#one line two sub with one action per line two per sub per area
self.env._parameters.MAX_SUB_CHANGED = 2
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
act = {
"set_line_status": [(LINE_ID, -1) for LINE_ID in list(chain(*[list_ids[:1] for list_ids in line_select]))],
"change_bus" : {"lines_or_id":[LINE_ID for LINE_ID in list(chain(*[list_ids[1:] for list_ids in line_select]))]}
}
_ = self.helper_action(
act,
env=self.env,
check_legal=True,
)
self.env.close()
def test_illegal_when_illegal(self):
params = Parameters()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"l2rpn_case14_sandbox",
test=True,
param=params,
gamerules_class = self.rules_3areas
)
self.env._parameters.MAX_SUB_CHANGED = 1
self.env._parameters.MAX_LINE_STATUS_CHANGED = 1
self.helper_action = self.env._helper_action_env
lines_by_area = [list_ids for list_ids in self.env._game_rules.legal_action.lines_id_by_area.values()]
#illegal action in one area due to lines
with self.assertRaises(IllegalAction):
act= {
"set_line_status": [(LINE_ID, -1) for LINE_ID in lines_by_area[0][:2]] + \
[(LINE_ID, -1) for LINE_ID in [lines_by_area[1][2], lines_by_area[2][2]]],
}
i = self.helper_action(
act,
env=self.env,
check_legal=True,
)
#illegal action in one area due to substations
with self.assertRaises(IllegalAction):
area0_sorted_ids = np.argsort(self.env.line_or_to_subid[lines_by_area[0]])
aff_2subs_lines_ids = np.array(lines_by_area[0])[area0_sorted_ids][[0,-1]]
act= {
"change_bus" : {"lines_or_id":[LINE_ID for LINE_ID in aff_2subs_lines_ids] + \
[LINE_ID for LINE_ID in [lines_by_area[1][2], lines_by_area[2][2]]]},
}
i = self.helper_action(
act,
env=self.env,
check_legal=True,
)
#illegal action in one area but still do action another area
self.env.close()
def test_catch_runner_area_action_illegality(self):
params = Parameters()
nn_episode = 1
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(
"l2rpn_case14_sandbox",
test=True,
param=params,
gamerules_class = self.rules_3areas
)
lines_by_area = [list_ids for list_ids in self.env._game_rules.legal_action.lines_id_by_area.values()]
illegal_act= {
"set_line_status": [(LINE_ID, -1) for LINE_ID in lines_by_area[0][:2]] + \
[(LINE_ID, -1) for LINE_ID in [lines_by_area[1][2], lines_by_area[2][2]]],
}
agent_class = OneChangeThenNothing.gen_next(illegal_act)
runner = Runner(**self.env.get_params_for_runner(), agentClass=agent_class)
res, *_ = runner.run(nb_episode=nn_episode, add_detailed_output=True)
ep_data = res[-1]
assert not ep_data.legal[0] #first act illegal
assert ep_data.legal[1]
if __name__ == "__main__":
unittest.main() | 7,970 | 44.810345 | 175 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Runner.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import tempfile
import json
import pdb
from grid2op.tests.helper_path_test import *
PATH_ADN_CHRONICS_FOLDER = os.path.abspath(
os.path.join(PATH_CHRONICS, "test_multi_chronics")
)
PATH_PREVIOUS_RUNNER = os.path.join(data_test_dir, "runner_data")
import grid2op
from grid2op.Agent import BaseAgent
from grid2op.Chronics import Multifolder, ChangeNothing
from grid2op.Reward import L2RPNReward, N1Reward
from grid2op.Backend import PandaPowerBackend
from grid2op.MakeEnv import make
from grid2op.Runner.aux_fun import _aux_one_process_parrallel
from grid2op.Runner import Runner
from grid2op.dtypes import dt_float
from grid2op.Agent import RandomAgent
from grid2op.Episode import EpisodeData
from grid2op.Observation import BaseObservation, CompleteObservation
class AgentTestLegalAmbiguous(BaseAgent):
def act(self, observation: BaseObservation, reward: float, done: bool = False):
if observation.current_step == 1:
return self.action_space({"set_line_status": [(0, -1)], "change_line_status": [0]}) # ambiguous
if observation.current_step == 2:
return self.action_space({"set_line_status": [(0, -1), (1, -1)]}) # illegal
return super().act(observation, reward, done)
class TestRunner(HelperTests):
def setUp(self):
self.init_grid_path = os.path.join(PATH_DATA_TEST_PP, "test_case14.json")
self.path_chron = PATH_ADN_CHRONICS_FOLDER
self.parameters_path = None
self.max_iter = 10
# self.real_reward = dt_float(199.99800)
self.real_reward = dt_float(179.99818)
self.all_real_rewards = [
19.999783,
19.999786,
19.999784,
19.999794,
19.9998,
19.999804,
19.999804,
19.999817,
19.999823,
0.0,
]
self.names_chronics_to_backend = {
"loads": {
"2_C-10.61": "load_1_0",
"3_C151.15": "load_2_1",
"14_C63.6": "load_13_2",
"4_C-9.47": "load_3_3",
"5_C201.84": "load_4_4",
"6_C-6.27": "load_5_5",
"9_C130.49": "load_8_6",
"10_C228.66": "load_9_7",
"11_C-138.89": "load_10_8",
"12_C-27.88": "load_11_9",
"13_C-13.33": "load_12_10",
},
"lines": {
"1_2_1": "0_1_0",
"1_5_2": "0_4_1",
"9_10_16": "8_9_2",
"9_14_17": "8_13_3",
"10_11_18": "9_10_4",
"12_13_19": "11_12_5",
"13_14_20": "12_13_6",
"2_3_3": "1_2_7",
"2_4_4": "1_3_8",
"2_5_5": "1_4_9",
"3_4_6": "2_3_10",
"4_5_7": "3_4_11",
"6_11_11": "5_10_12",
"6_12_12": "5_11_13",
"6_13_13": "5_12_14",
"4_7_8": "3_6_15",
"4_9_9": "3_8_16",
"5_6_10": "4_5_17",
"7_8_14": "6_7_18",
"7_9_15": "6_8_19",
},
"prods": {
"1_G137.1": "gen_0_4",
"3_G36.31": "gen_2_1",
"6_G63.29": "gen_5_2",
"2_G-56.47": "gen_1_0",
"8_G40.43": "gen_7_3",
},
}
self.gridStateclass = Multifolder
self.backendClass = PandaPowerBackend
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore"
) # silence the warning about missing layout
self.runner = Runner(
init_grid_path=self.init_grid_path,
init_env_path=self.init_grid_path,
path_chron=self.path_chron,
parameters_path=self.parameters_path,
names_chronics_to_backend=self.names_chronics_to_backend,
gridStateclass=self.gridStateclass,
backendClass=self.backendClass,
rewardClass=L2RPNReward,
max_iter=self.max_iter,
name_env="test_runner_env",
)
# def test_one_episode(self): # tested in the runner fast
# def test_one_episode_detailed(self): # tested in the runner fast
# def test_2episode(self): # tested in the runner fast
# def test_init_from_env(self): # tested in the runner fast
# def test_seed_seq(self): # tested in the runner fast
# def test_seed_par(self): # tested in the runner fast
def test_one_process_par(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = _aux_one_process_parrallel(
self.runner,
[0],
0,
env_seeds=None,
agent_seeds=None,
max_iter=self.max_iter,
)
assert len(res) == 1
_, el1, el2, el3, el4 = res[0]
assert el1 == "1"
assert np.abs(el2 - self.real_reward) <= self.tol_one
assert el3 == 10
assert el4 == 10
def test_2episode_2process(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = self.runner._run_parrallel(
nb_episode=2, nb_process=2, max_iter=self.max_iter
)
assert len(res) == 2
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == self.max_iter
assert np.abs(cum_reward - self.real_reward) <= self.tol_one
def test_2episode_2process_with_id(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_1 = self.runner._run_parrallel(
nb_episode=2, nb_process=2, episode_id=[0, 1], max_iter=self.max_iter
)
assert len(res_1) == 2
assert res_1[0][1] == "1"
assert res_1[1][1] == "2"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_2 = self.runner._run_parrallel(
nb_episode=2, nb_process=2, episode_id=[1, 0], max_iter=self.max_iter
)
assert len(res_2) == 2
assert res_2[0][1] == "2"
assert res_2[1][1] == "1"
def test_2episodes_with_id(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_1 = self.runner.run(
nb_episode=2, episode_id=[0, 1], max_iter=self.max_iter
)
assert len(res_1) == 2
assert res_1[0][1] == "1"
assert res_1[1][1] == "2"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_2 = self.runner.run(
nb_episode=2, episode_id=[1, 0], max_iter=self.max_iter
)
assert len(res_2) == 2
assert res_2[0][1] == "2"
assert res_2[1][1] == "1"
def test_2episodes_with_id_str(self):
env = self.runner.init_env()
subpaths = env.chronics_handler.subpaths
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_1 = self.runner.run(
nb_episode=2,
episode_id=[subpaths[0], subpaths[1]],
max_iter=self.max_iter,
)
assert len(res_1) == 2
assert res_1[0][1] == "1"
assert res_1[1][1] == "2"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res_2 = self.runner.run(
nb_episode=2,
episode_id=[subpaths[1], subpaths[0]],
max_iter=self.max_iter,
)
assert len(res_2) == 2
assert res_2[0][1] == "2"
assert res_2[1][1] == "1"
def test_2episode_2process_detailed(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = self.runner.run(
nb_episode=2,
nb_process=2,
max_iter=self.max_iter,
add_detailed_output=True,
)
assert len(res) == 2
for i, _, cum_reward, timestep, total_ts, episode_data in res:
assert int(timestep) == self.max_iter
assert np.abs(cum_reward - self.real_reward) <= self.tol_one
for j in range(len(self.all_real_rewards)):
assert (
np.abs(episode_data.rewards[j] - self.all_real_rewards[j])
<= self.tol_one
)
def test_add_detailed_output_first_obs(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = self.runner.run(
nb_episode=1,
nb_process=1,
max_iter=self.max_iter,
add_detailed_output=True,
)
assert res[0][-1].observations[0] is not None
def test_multiprocess_windows_no_fail(self):
"""test that i can run multiple times parallel run of the same env (breaks on windows)"""
nb_episode = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
f = tempfile.mkdtemp()
runner_params = env.get_params_for_runner()
runner = Runner(**runner_params)
res1 = runner.run(
path_save=f,
nb_episode=nb_episode,
nb_process=2,
max_iter=self.max_iter,
)
res2 = runner.run(
path_save=f,
nb_episode=nb_episode,
nb_process=1,
max_iter=self.max_iter,
)
res3 = runner.run(
path_save=f,
nb_episode=nb_episode,
nb_process=2,
max_iter=self.max_iter,
)
test_ = set()
for id_chron, name_chron, cum_reward, nb_time_step, max_ts in res1:
test_.add(name_chron)
assert len(test_) == nb_episode
test_ = set()
for id_chron, name_chron, cum_reward, nb_time_step, max_ts in res2:
test_.add(name_chron)
assert len(test_) == nb_episode
test_ = set()
for id_chron, name_chron, cum_reward, nb_time_step, max_ts in res3:
test_.add(name_chron)
assert len(test_) == nb_episode
def test_complex_agent(self):
nb_episode = 4
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
f = tempfile.mkdtemp()
runner_params = env.get_params_for_runner()
runner = Runner(**runner_params)
res = runner.run(
path_save=f,
nb_episode=nb_episode,
nb_process=2,
max_iter=self.max_iter,
)
test_ = set()
for id_chron, name_chron, cum_reward, nb_time_step, max_ts in res:
test_.add(name_chron)
assert len(test_) == nb_episode
def test_init_from_env_with_other_reward(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case14_test", test=True, other_rewards={"test": L2RPNReward}
) as env:
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=1, max_iter=self.max_iter)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == self.max_iter
def test_seed_properly_set(self):
class TestSuitAgent(RandomAgent):
def __init__(self, *args, **kwargs):
RandomAgent.__init__(self, *args, **kwargs)
self.seeds = []
def seed(self, seed):
super().seed(seed)
self.seeds.append(seed)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
my_agent = TestSuitAgent(env.action_space)
runner = Runner(
**env.get_params_for_runner(),
agentClass=None,
agentInstance=my_agent,
)
# test that the right seeds are assigned to the agent
res = runner.run(
nb_episode=3,
max_iter=self.max_iter,
env_seeds=[1, 2, 3],
agent_seeds=[5, 6, 7],
)
assert np.all(my_agent.seeds == [5, 6, 7])
# test that is no seeds are set, then the "seed" function of the agent is not called.
my_agent.seeds = []
res = runner.run(nb_episode=3, max_iter=self.max_iter, env_seeds=[1, 2, 3])
assert my_agent.seeds == []
def test_always_same_order(self):
# test that a call to "run" will do always the same chronics in the same order
# regardless of the seed or the parallelism or the number of call to runner.run
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
runner = Runner(**env.get_params_for_runner())
res = runner.run(
nb_episode=2,
nb_process=2,
max_iter=self.max_iter,
env_seeds=[1, 2],
agent_seeds=[3, 4],
)
first_ = [el[0] for el in res]
res = runner.run(
nb_episode=2,
nb_process=1,
max_iter=self.max_iter,
env_seeds=[1, 2],
agent_seeds=[3, 4],
)
second_ = [el[0] for el in res]
res = runner.run(
nb_episode=2, nb_process=1, max_iter=self.max_iter, env_seeds=[9, 10]
)
third_ = [el[0] for el in res]
res = runner.run(
nb_episode=2,
nb_process=2,
max_iter=self.max_iter,
env_seeds=[1, 2],
agent_seeds=[3, 4],
)
fourth_ = [el[0] for el in res]
assert np.all(first_ == second_)
assert np.all(first_ == third_)
assert np.all(first_ == fourth_)
def test_nomaxiter(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
runner = Runner(**env.get_params_for_runner())
runner.gridStateclass_kwargs["max_iter"] = 2 * self.max_iter
runner.chronics_handler.set_max_iter(2 * self.max_iter)
res = runner.run(nb_episode=1)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == 2 * self.max_iter
def test_nomaxiter_par(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
dict_ = env.get_params_for_runner()
dict_["max_iter"] = -1
sub_dict = dict_["gridStateclass_kwargs"]
sub_dict["max_iter"] = 2 * self.max_iter
runner = Runner(**dict_)
res = runner.run(nb_episode=2, nb_process=2)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == 2 * self.max_iter
def _aux_backward(self, base_path, g2op_version_txt, g2op_version):
episode_studied = EpisodeData.list_episode(
os.path.join(base_path, g2op_version_txt)
)
for base_path, episode_path in episode_studied:
assert "curtailment" in CompleteObservation.attr_list_vect, (
f"error after the legacy version " f"{g2op_version}"
)
this_episode = EpisodeData.from_disk(base_path, episode_path)
assert "curtailment" in CompleteObservation.attr_list_vect, (
f"error after the legacy version " f"{g2op_version}"
)
full_episode_path = os.path.join(base_path, episode_path)
with open(
os.path.join(full_episode_path, "episode_meta.json"),
"r",
encoding="utf-8",
) as f:
meta_data = json.load(f)
nb_ts = int(meta_data["nb_timestep_played"])
try:
assert len(this_episode.actions) == nb_ts, (
f"wrong number of elements for actions for version "
f"{g2op_version_txt}: {len(this_episode.actions)} vs {nb_ts}"
)
assert len(this_episode.observations) == nb_ts + 1, (
f"wrong number of elements for observations "
f"for version {g2op_version_txt}: "
f"{len(this_episode.observations)} vs {nb_ts}"
)
assert len(this_episode.env_actions) == nb_ts, (
f"wrong number of elements for env_actions for "
f"version {g2op_version_txt}: "
f"{len(this_episode.env_actions)} vs {nb_ts}"
)
except Exception as exc_:
raise exc_
if g2op_version <= "1.4.0":
assert (
EpisodeData.get_grid2op_version(full_episode_path) == "<=1.4.0"
), "wrong grid2op version stored (grid2op version <= 1.4.0)"
elif g2op_version == "test_version":
assert (
EpisodeData.get_grid2op_version(full_episode_path)
== grid2op.__version__
), "wrong grid2op version stored (test_version)"
else:
assert (
EpisodeData.get_grid2op_version(full_episode_path) == g2op_version
), "wrong grid2op version stored (>=1.5.0)"
def test_backward_compatibility(self):
backward_comp_version = [
"1.0.0",
"1.1.0",
"1.1.1",
"1.2.0",
"1.2.1",
"1.2.2",
"1.2.3",
"1.3.0",
"1.3.1",
"1.4.0",
"1.5.0",
"1.5.1",
"1.5.1.post1",
"1.5.2",
"1.6.0",
"1.6.0.post1",
"1.6.1",
"1.6.2",
"1.6.2.post1",
"1.6.3",
"1.6.4",
"1.6.5",
"1.7.0",
"1.7.1",
"1.7.2",
"1.8.1",
]
curr_version = "test_version"
assert (
"curtailment" in CompleteObservation.attr_list_vect
), "error at the beginning"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make(
"rte_case5_example", test=True
) as env, tempfile.TemporaryDirectory() as path:
runner = Runner(**env.get_params_for_runner(), agentClass=RandomAgent)
runner.run(
nb_episode=2,
path_save=os.path.join(path, curr_version),
pbar=False,
max_iter=100,
env_seeds=[1, 0],
agent_seeds=[42, 69],
)
# check that i can read this data generate for this runner
self._aux_backward(path, curr_version, curr_version)
assert (
"curtailment" in CompleteObservation.attr_list_vect
), "error after the first runner"
# check that it raises a warning if loaded on the compatibility version
grid2op_version = backward_comp_version[0]
with self.assertWarns(UserWarning, msg=f"error for {grid2op_version}"):
self._aux_backward(
PATH_PREVIOUS_RUNNER, f"res_agent_{grid2op_version}", grid2op_version
)
for grid2op_version in backward_comp_version:
# check that i can read previous data stored from previous grid2Op version
# can be loaded properly
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self._aux_backward(
PATH_PREVIOUS_RUNNER,
f"res_agent_{grid2op_version}",
grid2op_version,
)
assert "curtailment" in CompleteObservation.attr_list_vect, (
f"error after the legacy version " f"{grid2op_version}"
)
def test_reward_as_object(self):
L_ID = 2
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(
"l2rpn_case14_sandbox", reward_class=N1Reward(l_id=L_ID), test=True
)
runner = Runner(**env.get_params_for_runner())
runner.run(nb_episode=1, max_iter=10)
env.close()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"l2rpn_case14_sandbox",
other_rewards={f"line_{l_id}": N1Reward(l_id=l_id) for l_id in [0, 1]},
test=True,
)
runner = Runner(**env.get_params_for_runner())
runner.run(nb_episode=1, max_iter=10)
env.close()
def test_legal_ambiguous_regular(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_case14_sandbox", test=True)
runner = Runner(**env.get_params_for_runner(), agentClass=AgentTestLegalAmbiguous)
env.close()
res, *_ = runner.run(nb_episode=1, max_iter=10, add_detailed_output=True)
ep_data = res[-1]
# test the "legal" part
assert ep_data.legal[0]
assert ep_data.legal[1]
assert not ep_data.legal[2]
assert ep_data.legal[3]
# test the ambiguous part
assert not ep_data.ambiguous[0]
assert ep_data.ambiguous[1]
assert not ep_data.ambiguous[2]
assert not ep_data.ambiguous[3]
def test_legal_ambiguous_nofaststorage(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make("l2rpn_case14_sandbox", test=True, chronics_class=ChangeNothing)
runner = Runner(**env.get_params_for_runner(), agentClass=AgentTestLegalAmbiguous)
env.close()
res, *_ = runner.run(nb_episode=1, max_iter=10, add_detailed_output=True)
ep_data = res[-1]
# test the "legal" part
assert ep_data.legal[0]
assert ep_data.legal[1]
assert not ep_data.legal[2]
assert ep_data.legal[3]
# test the ambiguous part
assert not ep_data.ambiguous[0]
assert ep_data.ambiguous[1]
assert not ep_data.ambiguous[2]
assert not ep_data.ambiguous[3]
if __name__ == "__main__":
unittest.main()
| 23,652 | 37.585644 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_RunnerFast.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
from grid2op.tests.helper_path_test import *
PATH_ADN_CHRONICS_FOLDER = os.path.abspath(
os.path.join(PATH_CHRONICS, "test_multi_chronics")
)
PATH_PREVIOUS_RUNNER = os.path.join(data_test_dir, "runner_data")
import grid2op
from grid2op.MakeEnv import make
from grid2op.Runner import Runner
from grid2op.dtypes import dt_float
warnings.simplefilter("error")
class TestRunner(HelperTests):
def setUp(self):
self.init_grid_path = os.path.join(PATH_DATA_TEST_PP, "test_case14.json")
self.path_chron = PATH_ADN_CHRONICS_FOLDER
self.parameters_path = None
self.max_iter = 10
self.real_reward = dt_float(7748.425 / 12.)
self.real_reward_li = [self.real_reward, dt_float(7786.8955 / 12.)] # 7786.89599609375
self.all_real_rewards = [
dt_float(el / 12.)
for el in [
761.3295,
768.10144,
770.2673,
767.767,
768.69,
768.71246,
779.1029,
783.2737,
788.7833,
792.39764,
]
]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
self.runner = Runner(**self.env.get_params_for_runner())
def test_one_episode(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
_, cum_reward, timestep, max_ts = self.runner.run_one_episode(
max_iter=self.max_iter
)
assert int(timestep) == self.max_iter
assert np.abs(cum_reward - self.real_reward) <= self.tol_one, f"{cum_reward} != {self.real_reward}"
def test_one_episode_detailed(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
_, cum_reward, timestep, max_ts, episode_data = self.runner.run_one_episode(
max_iter=self.max_iter, detailed_output=True
)
assert int(timestep) == self.max_iter
assert np.abs(cum_reward - self.real_reward) <= self.tol_one
for j in range(len(self.all_real_rewards)):
assert (
np.abs(episode_data.rewards[j] - self.all_real_rewards[j])
<= self.tol_one
), f"{episode_data.rewards[j]} != {self.all_real_rewards[j]}"
def test_2episode(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = self.runner._run_sequential(nb_episode=2, max_iter=self.max_iter)
assert len(res) == 2
for i, (stuff, _, cum_reward, timestep, total_ts) in enumerate(res):
assert int(timestep) == self.max_iter
assert np.abs(cum_reward - self.real_reward_li[i]) <= self.tol_one, f"for iter {i}: {cum_reward} != {self.real_reward_li[i]}"
def test_init_from_env(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=1, max_iter=self.max_iter)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == self.max_iter, f"{timestep} != {self.max_iter}"
def test_seed_seq(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
runner = Runner(**env.get_params_for_runner())
res = runner.run(
nb_episode=1, max_iter=self.max_iter, env_seeds=[1], agent_seeds=[2]
)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == self.max_iter, f"{timestep} != {self.max_iter}"
def test_seed_par(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case14_test", test=True) as env:
runner = Runner(**env.get_params_for_runner())
res = runner.run(
nb_episode=2,
nb_process=2,
max_iter=self.max_iter,
env_seeds=[1, 2],
agent_seeds=[3, 4],
)
for i, _, cum_reward, timestep, total_ts in res:
assert int(timestep) == self.max_iter
if __name__ == "__main__":
unittest.main()
| 4,992 | 38.944 | 137 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_Storage.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import pdb
import time
import warnings
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.Parameters import Parameters
from grid2op.dtypes import dt_float
from grid2op.Action import CompleteAction
import warnings
# TODO check when there is also redispatching
class TestStorageEnv(HelperTests):
"""test the env part of the storage functionality"""
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("educ_case14_storage", test=True)
def tearDown(self) -> None:
self.env.close()
def test_init_storage_ok(self):
"""
test the right storage is given at the init of an environment
it tests the param.INIT_STORAGE_CAPACITY parameter
"""
obs = self.env.get_obs()
assert np.all(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one
)
obs = self.env.reset()
assert np.all(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one
)
param = Parameters()
param.INIT_STORAGE_CAPACITY = 0.0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
obs = env.reset()
assert np.all(np.abs(obs.storage_charge) <= self.tol_one)
param = Parameters()
param.INIT_STORAGE_CAPACITY = 1.0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
obs = env.reset()
assert np.all(np.abs(obs.storage_charge - obs.storage_Emax) <= self.tol_one)
# now test the reset works
act = self.env.action_space({"set_storage": [(0, 1), (1, 5)]})
obs, reward, done, info = self.env.step(act)
assert np.any(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) > self.tol_one
)
obs = self.env.reset()
assert np.all(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one
)
def test_action_ok(self):
"""test a storage action is supported (basic test)"""
act = self.env.action_space({"set_storage": [(0, 1)]})
str_ = act.__str__()
real_str = (
"This action will:\n"
"\t - NOT change anything to the injections\n"
"\t - NOT perform any redispatching action\n"
"\t - Modify the storage units in the following way:\n"
'\t \t - Ask unit "storage_5_0" to absorb 1.00 MW (setpoint: 1.00 MW)\n'
"\t - NOT perform any curtailment\n"
"\t - NOT force any line status\n"
"\t - NOT switch any line status\n\t - NOT switch anything in the topology\n"
"\t - NOT force any particular bus configuration"
)
assert str_ == real_str
def test_env_storage_ok(self):
"""
test i can perform normal storage actions (no trick here) just normal actions
this test the proper computing of the charge of the storage units, the proper computing of the
redispatching etc.
"""
# first test the storage loss
act = self.env.action_space()
loss = 1.0 * self.env.storage_loss
loss /= 12.0 # i have 12 steps per hour (ts = (mins), losses are given in MW and capacity in MWh
for nb_ts in range(5):
obs, reward, done, info = self.env.step(act)
assert np.all(
np.abs(
obs.storage_charge - (0.5 * obs.storage_Emax - (nb_ts + 1) * loss)
)
<= self.tol_one
), f"wrong value computed for time step {nb_ts}"
# now modify the storage capacity (charge a battery, with efficiency != 1.)
# storage value is [7.4583335, 3.4583333]
act = self.env.action_space(
{"set_storage": [(0, 3)]}
) # ask the first storage to absorb 3MW (during 5 mins)
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.4583335, 3.4583333] - loss
# modif adds [3 / 12, 0.] # 3/12 is because i ask to absorb 3 MW during 5 mins
# but storage efficiency of battery 0 is 0.95, so i don't store 3/12. but 0.95 * 3/12
# result is [7.70000017, 3.44999997]
assert np.all(
np.abs(obs.storage_charge - [7.68750017, 3.44999997]) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I asked to absorb 3MW, so dispatch should produce 3MW more
assert np.abs(np.sum(obs.actual_dispatch) - (+3.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [3.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [3.0, 0.0]) <= self.tol_one)
# second action (battery produces something, with efficiency != 1.)
act = self.env.action_space(
{"set_storage": [(1, -5)]}
) # ask the second storage to produce 3MW (during 5 mins)
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.68750017, 3.44999997] - loss
# modif adds [0., -5/12.] # -5/12 is because i ask to produce 5 MW during 5 mins
# but second battery discharging efficiency is 0.9 so the actual charge will decrease of -5/12 * (1/0.9)
# final result is [7.67916684, 2.97870367]
assert np.all(
np.abs(obs.storage_charge - [7.67916684, 2.97870367]) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I asked to produce 5MW, so dispatch should produce 5MW more
assert np.abs(np.sum(obs.actual_dispatch) - (-5.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, -5.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, -5.0]) <= self.tol_one)
# third modify the storage capacity (charge a battery, with efficiency == 1.)
act = self.env.action_space({"set_storage": [(0, -1)]})
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.67916684, 2.97870367] - loss
# modif adds [-1/12., 0.] # -1/12 is because i ask to produce 1 MW during 5 mins
# final result is [7.58750017, 2.97037034]
assert np.all(
np.abs(obs.storage_charge - [7.58750017, 2.97037034]) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I asked to produce 5MW, so dispatch should produce 5MW more
assert np.abs(np.sum(obs.actual_dispatch) - (-1.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [-1.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [-1, 0.0]) <= self.tol_one)
# fourth modify the storage capacity (discharge a battery, with efficiency == 1.)
act = self.env.action_space({"set_storage": [(1, 2)]})
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.58750017, 2.97037034] - loss
# modif adds [0., 2/12.] # 2/12 is because i ask to produce 2 MW during 5 mins
# final result is [7.57916684, 3.12870367] => rounded to [7.579168 , 3.1287026]
assert np.all(
np.abs(obs.storage_charge - [7.57916684, 3.12870367]) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I asked to produce 5MW, so dispatch should produce 5MW more
assert np.abs(np.sum(obs.actual_dispatch) - (2.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 2.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 2.0]) <= self.tol_one)
# fifth i do nothing and make sure everything is reset
act = (
self.env.action_space()
) # ask the second storage to produce 3MW (during 5 mins)
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.579168 , 3.1287026]- loss
assert np.all(
np.abs(obs.storage_charge - ([7.57083467, 3.12036927])) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I did not modify the battery, so i should not modify the dispatch
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
# sixth i do nothing and make sure everything is reset
act = (
self.env.action_space()
) # ask the second storage to produce 3MW (during 5 mins)
obs, reward, done, info = self.env.step(act)
assert not info["exception"] # there should be no exception here
# without modif it's [7.57083467, 3.12036927] - loss
assert np.all(
np.abs(obs.storage_charge - ([7.56250134, 3.11203594])) <= self.tol_one
)
assert np.all(
np.abs(obs.target_dispatch) <= self.tol_one
) # i did not do any dispatch
# I did not modify the battery, so i should not modify the dispatch
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
def test_activate_storage_loss(self):
"""
test that the parameters param.ACTIVATE_STORAGE_LOSS properly deactivate the loss in the storage
units
"""
# first test the storage loss
act = self.env.action_space()
loss = 1.0 * self.env.storage_loss
loss /= 12.0 # i have 12 steps per hour (ts = (mins), losses are given in MW and capacity in MWh
for nb_ts in range(5):
obs, reward, done, info = self.env.step(act)
assert np.all(
np.abs(
obs.storage_charge - (0.5 * obs.storage_Emax - (nb_ts + 1) * loss)
)
<= self.tol_one
), f"wrong value computed for time step {nb_ts}"
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = False
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
obs = env.get_obs()
assert np.all(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one
), "wrong initial capacity"
for nb_ts in range(5):
obs, reward, done, info = env.step(act)
assert np.all(
np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one
), f"wrong value computed for time step {nb_ts} (no loss in storage)"
def test_storage_loss_dont_make_negative(self):
"""
test that the storage loss dont make negative capacity
or in other words that loss don't apply when storage are empty
"""
init_coeff = 0.01
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = True
param.INIT_STORAGE_CAPACITY = init_coeff
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
obs = env.get_obs()
init_charge = init_coeff * obs.storage_Emax
loss = 1.0 * env.storage_loss
loss /= 12.0 # i have 12 steps per hour (ts = 5mins, losses are given in MW and capacity in MWh
act = env.action_space()
assert np.all(
np.abs(obs.storage_charge - init_charge) <= self.tol_one
), "wrong initial capacity"
for nb_ts in range(8):
obs, reward, done, info = env.step(act)
assert np.all(
np.abs(obs.storage_charge - (init_charge - (nb_ts + 1) * loss))
<= self.tol_one
), f"wrong value computed for time step {nb_ts} (with loss in storage)"
# now a loss should 'cap' the second battery
obs, reward, done, info = env.step(act)
th_storage = init_charge - (nb_ts + 1) * loss
th_storage[0] -= loss[0]
th_storage[1] = 0.0
assert np.all(np.abs(obs.storage_charge - th_storage) <= self.tol_one)
for nb_ts in range(9):
obs, reward, done, info = env.step(act)
th_storage[0] -= loss[0]
assert np.all(
np.abs(obs.storage_charge - th_storage) <= self.tol_one
), f"capacity error for time step {nb_ts}"
# all storages are empty
obs, reward, done, info = env.step(act)
assert np.all(
np.abs(obs.storage_charge) <= self.tol_one
), "error battery should be empty - 0"
obs, reward, done, info = env.step(act)
assert np.all(
np.abs(obs.storage_charge) <= self.tol_one
), "error, battery should be empty - 1"
obs, reward, done, info = env.step(act)
assert np.all(
np.abs(obs.storage_charge) <= self.tol_one
), "error, battery should be empty - 2"
def test_env_storage_ambiguous(self):
"""test i can detect ambiguous storage actions"""
# above the maximum flow you can absorb (max is 5)
act = self.env.action_space({"set_storage": [(0, 5.1)]})
obs, reward, done, info = self.env.step(act)
assert info["exception"]
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
# lower the maximum flow you can produce (max is 10)
act = self.env.action_space({"set_storage": [(1, -10.1)]})
obs, reward, done, info = self.env.step(act)
assert info["exception"]
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
# wrong number of storage
with self.assertRaises(Exception):
act = self.env.action_space({"set_storage": np.zeros(3)})
obs, reward, done, info = self.env.step(act)
if info["exception"]:
raise info["exception"][
0
] # test should pass: if action can be done, it should be ambiguous
# if info["exception"] is [] then i don't raise anything, and the test fails
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
with self.assertRaises(Exception):
act = self.env.action_space({"set_storage": np.zeros(1)})
obs, reward, done, info = self.env.step(act)
if info["exception"]:
raise info["exception"][
0
] # test should pass: if action can be done, it should be ambiguous
# if info["exception"] is [] then i don't raise anything, and the test fails
assert np.abs(np.sum(obs.actual_dispatch) - (0.0)) <= self.tol_one
assert np.all(np.abs(obs.storage_power_target - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(obs.storage_power - [0.0, 0.0]) <= self.tol_one)
def test_env_storage_cut_because_too_high_noloss(self):
"""
test the correct behaviour is met when storage energy would be too high (need to cut DOWN the action)
and we don't take into account the loss and inefficiencies
"""
init_coeff = 0.99
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = (
False # to simplify the computation, in this first test
)
param.INIT_STORAGE_CAPACITY = init_coeff
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
self.env.close()
self.env = env
obs = self.env.reset()
init_storage = np.array([14.85, 6.9300003], dtype=dt_float)
assert np.all(np.abs(obs.storage_charge - init_storage) <= self.tol_one)
# too high in second battery, ok for first step
array_modif = np.array([1.5, 10.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + init_storage))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# now both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
assert (
np.abs(obs.storage_power[1]) <= self.tol_one
) # second battery cannot charge anymore
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# now both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
assert np.all(
np.abs(obs.storage_power) <= self.tol_one
) # all batteries cannot charge anymore
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge))
<= self.tol_one
)
def test_env_storage_cut_because_too_high_withloss(self):
"""test the correct behaviour is met when storage energy would be too high (need to cut DOWN the action)"""
init_coeff = 0.99
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = True
param.INIT_STORAGE_CAPACITY = init_coeff
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
self.env.close()
self.env = env
obs = self.env.reset()
init_storage = np.array([14.85, 6.9300003], dtype=dt_float)
assert np.all(np.abs(obs.storage_charge - init_storage) <= self.tol_one)
loss = 1.0 * env.storage_loss
loss /= 12.0 # i have 12 steps per hour (ts = 5mins, losses are given in MW and capacity in MWh)
# too high in second battery, ok for first step
array_modif = np.array([1.5, 10.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
bat_energy_added *= obs.storage_charging_efficiency # there are inefficiencies
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + init_storage - loss))
<= self.tol_one
)
# only the loss makes the second storage unit not full
assert (
np.abs(obs.storage_charge[1] - (self.env.storage_Emax[1] - loss[1]))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# after this action both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
# second battery cannot charge more than the loss
val = env.storage_loss[1] / self.env.storage_charging_efficiency[1]
assert np.abs(obs.storage_power[1] - val) <= self.tol_one
# all batteries are charged at maximum now
assert np.all(
np.abs(obs.storage_charge - (self.env.storage_Emax - loss)) <= self.tol_one
)
bat_energy_added = (
1.0 * obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
bat_energy_added *= obs.storage_charging_efficiency # there are inefficiencies
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge - loss))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# both batteries are at maximum, i can only charge them of the losses
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge <= self.env.storage_Emax)
# second battery cannot charge more than the loss
val = env.storage_loss / self.env.storage_charging_efficiency
assert np.all(np.abs(obs.storage_power - val) <= self.tol_one)
# all batteries are charged at maximum now
assert np.all(
np.abs(obs.storage_charge - (self.env.storage_Emax - loss)) <= self.tol_one
)
bat_energy_added = (
1.0 * obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
bat_energy_added *= obs.storage_charging_efficiency # there are inefficiencies
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge - loss))
<= self.tol_one
)
def test_env_storage_cut_because_too_low_noloss(self):
"""
test the correct behaviour is met when storage energy would be too low (need to cut the action)
and we don't take into account the loss and inefficiencies
"""
init_coeff = 0.01
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = (
False # to simplify the computation, in this first test
)
param.INIT_STORAGE_CAPACITY = init_coeff
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
self.env.close()
self.env = env
obs = self.env.reset()
init_storage = np.array([0.14999999, 0.07], dtype=dt_float)
assert np.all(np.abs(obs.storage_charge - init_storage) <= self.tol_one)
# too high in second battery, ok for first step
array_modif = np.array([-1.5, -10.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + init_storage))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# now both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
assert (
np.abs(obs.storage_power[1]) <= self.tol_one
) # second battery cannot charge anymore
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge))
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# now both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
assert np.all(
np.abs(obs.storage_power) <= self.tol_one
) # all batteries cannot charge anymore
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
assert np.all(
np.abs(obs.storage_charge - (bat_energy_added + state_of_charge))
<= self.tol_one
)
def test_env_storage_cut_because_too_low_withloss(self):
"""test the correct behaviour is met when storage energy would be too low (need to cut the action)"""
init_coeff = 0.01
param = Parameters()
param.ACTIVATE_STORAGE_LOSS = True
param.INIT_STORAGE_CAPACITY = init_coeff
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_storage", test=True, param=param)
self.env.close()
self.env = env
obs = self.env.reset()
init_storage = np.array([0.14999999, 0.07], dtype=dt_float)
assert np.all(np.abs(obs.storage_charge - init_storage) <= self.tol_one)
loss = 1.0 * env.storage_loss
loss /= 12.0 # i have 12 steps per hour (ts = 5mins, losses are given in MW and capacity in MWh)
# too high in second battery, ok for first step
array_modif = np.array([-1.5, -10.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
assert np.all(obs.storage_power <= 0.0) # I emptied the battery
bat_energy_added = (
obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
# there are inefficiencies (I remove MORE energy from the battery than what i get in the grid)
bat_energy_added /= obs.storage_discharging_efficiency
# below i said [loss[0], 0.] because i don't have loss on an empty battery
assert np.all(
np.abs(
obs.storage_charge - (bat_energy_added + init_storage - [loss[0], 0.0])
)
<= self.tol_one
)
# only the loss makes the second storage unit not full
assert (
np.abs(obs.storage_charge[1] - (self.env.storage_Emin[1])) <= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# after this action both batteries are capped
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
assert np.all(obs.storage_power <= 0.0) # I emptied the battery
# second battery cannot be discharged more
assert np.abs(obs.storage_power[1] - 0.0) <= self.tol_one
# all batteries are charged at minimum now (only because Emin is 0.)
assert np.all(
np.abs(obs.storage_charge - self.env.storage_Emin) <= self.tol_one
)
bat_energy_added = (
1.0 * obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
# there are inefficiencies (I remove MORE energy from the battery than what i get in the grid)
bat_energy_added /= (
obs.storage_discharging_efficiency
) # there are inefficiencies
# below i said [0., 0.] because i don't have loss on an empty battery
assert np.all(
np.abs(
obs.storage_charge - (bat_energy_added + state_of_charge - [0.0, 0.0])
)
<= self.tol_one
)
state_of_charge = 1.0 * obs.storage_charge
# both batteries are at maximum, i can only charge them of the losses
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
assert np.all(np.abs(obs.storage_power_target - array_modif) <= self.tol_one)
assert (
np.abs(np.sum(obs.actual_dispatch) - np.sum(obs.storage_power))
<= self.tol_one
)
assert np.all(obs.storage_charge >= self.env.storage_Emin)
assert np.all(obs.storage_power <= 0.0) # I emptied the battery
# second battery cannot be discharged more than it is
assert np.all(np.abs(obs.storage_power - 0.0) <= self.tol_one)
# all batteries are charged at maximum now
assert np.all(
np.abs(obs.storage_charge - self.env.storage_Emin) <= self.tol_one
)
bat_energy_added = (
1.0 * obs.storage_power / 12.0
) # amount of energy if the power is maintained for 5mins
# there are inefficiencies (I remove MORE energy from the battery than what i get in the grid)
bat_energy_added /= (
obs.storage_discharging_efficiency
) # there are inefficiencies
# below i said [0., 0.] because i don't have loss on an empty battery
assert np.all(
np.abs(
obs.storage_charge - (bat_energy_added + state_of_charge - [0.0, 0.0])
)
<= self.tol_one
)
def _aux_test_kirchoff(self):
p_subs, q_subs, p_bus, q_bus, diff_v_bus = self.env.backend.check_kirchoff()
assert np.all(
np.abs(p_subs) <= self.tol_one
), "error with active value at some substations"
assert np.all(
np.abs(q_subs) <= self.tol_one
), "error with reactive value at some substations"
assert np.all(
np.abs(p_bus) <= self.tol_one
), "error with active value at some bus"
assert np.all(
np.abs(q_bus) <= self.tol_one
), "error with reactive value at some bus"
assert np.all(diff_v_bus <= self.tol_one), "error with voltage discrepency"
def test_storage_action_mw(self):
"""test the actions are properly implemented in the backend"""
array_modif = np.array([-1.5, -10.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(np.abs(storage_p - array_modif) <= self.tol_one)
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
self._aux_test_kirchoff()
array_modif = np.array([2, 8], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(np.abs(storage_p - array_modif) <= self.tol_one)
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
self._aux_test_kirchoff()
# illegal action
array_modif = np.array([2, 12], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(np.abs(storage_p - [0.0, 0.0]) <= self.tol_one)
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
self._aux_test_kirchoff()
# full discharge now
array_modif = np.array([-1.5, -10.0], dtype=dt_float)
for nb_ts in range(3):
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(
np.abs(storage_p - array_modif) <= self.tol_one
), f"error for P for time step {nb_ts}"
assert np.all(
np.abs(storage_q - 0.0) <= self.tol_one
), f"error for Q for time step {nb_ts}"
self._aux_test_kirchoff()
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
# i have emptied second battery
assert np.all(
np.abs(self.env.backend._grid.storage["p_mw"].values - [-1.5, -4.4599934])
<= self.tol_one
)
assert np.all(np.abs(obs.storage_charge[1] - 0.0) <= self.tol_one)
self._aux_test_kirchoff()
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
# i have emptied second battery
assert np.all(
np.abs(self.env.backend._grid.storage["p_mw"].values - [-1.5, 0.0])
<= self.tol_one
)
assert np.all(np.abs(obs.storage_charge[1] - 0.0) <= self.tol_one)
self._aux_test_kirchoff()
def test_storage_action_topo(self):
"""test the modification of the bus of a storage unit"""
param = Parameters()
param.NB_TIMESTEP_COOLDOWN_SUB = 0
param.NB_TIMESTEP_COOLDOWN_LINE = 0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"educ_case14_storage",
test=True,
action_class=CompleteAction,
param=param,
)
self.env.close()
self.env = env
obs = self.env.reset()
# first case, standard modification
array_modif = np.array([-1.5, -10.0], dtype=dt_float)
act = self.env.action_space(
{
"set_storage": array_modif,
"set_bus": {
"storages_id": [(0, 2)],
"lines_or_id": [(8, 2)],
"generators_id": [(3, 2)],
},
}
)
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(np.abs(storage_p - array_modif) <= self.tol_one)
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
assert obs.storage_bus[0] == 2
assert obs.line_or_bus[8] == 2
assert obs.gen_bus[3] == 2
self._aux_test_kirchoff()
# second case, still standard modification (set to orig)
array_modif = np.array([1.5, 10.0], dtype=dt_float)
act = self.env.action_space(
{
"set_storage": array_modif,
"set_bus": {
"storages_id": [(0, 1)],
"lines_or_id": [(8, 1)],
"generators_id": [(3, 1)],
},
}
)
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(np.abs(storage_p - array_modif) <= self.tol_one)
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
assert obs.storage_bus[0] == 1
assert obs.line_or_bus[8] == 1
assert obs.gen_bus[3] == 1
self._aux_test_kirchoff()
# fourth case: isolated storage on a busbar (so it is disconnected, but with 0. production => so thats fine)
array_modif = np.array([0.0, 7.0], dtype=dt_float)
act = self.env.action_space(
{
"set_storage": array_modif,
"set_bus": {
"storages_id": [(0, 2)],
"lines_or_id": [(8, 1)],
"generators_id": [(3, 1)],
},
}
)
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(
np.abs(storage_p - [0.0, array_modif[1]]) <= self.tol_one
), "storage is not disconnected, yet alone on its busbar"
assert np.all(np.abs(storage_q - 0.0) <= self.tol_one)
assert obs.storage_bus[0] == -1, "storage should be disconnected"
assert storage_v[0] == 0.0, "storage 0 should be disconnected"
assert obs.line_or_bus[8] == 1
assert obs.gen_bus[3] == 1
self._aux_test_kirchoff()
# check that if i don't touch it it's set to 0
act = self.env.action_space()
obs, reward, done, info = self.env.step(act)
assert not info["exception"]
storage_p, storage_q, storage_v = self.env.backend.storages_info()
assert np.all(
np.abs(storage_p - 0.0) <= self.tol_one
), "storage should produce 0"
assert np.all(
np.abs(storage_q - 0.0) <= self.tol_one
), "storage should produce 0"
assert obs.storage_bus[0] == -1, "storage should be disconnected"
assert storage_v[0] == 0.0, "storage 0 should be disconnected"
assert obs.line_or_bus[8] == 1
assert obs.gen_bus[3] == 1
self._aux_test_kirchoff()
# trying to act on a disconnected storage => illegal)
array_modif = np.array([2.0, 7.0], dtype=dt_float)
act = self.env.action_space({"set_storage": array_modif})
obs, reward, done, info = self.env.step(act)
assert info["exception"] # action should be illegal
assert not done # this is fine, as it's illegal it's replaced by do nothing
self._aux_test_kirchoff()
# trying to reconnect a storage alone on a bus => game over, not connected bus
array_modif = np.array([1.0, 7.0], dtype=dt_float)
act = self.env.action_space(
{
"set_storage": array_modif,
"set_bus": {
"storages_id": [(0, 2)],
"lines_or_id": [(8, 1)],
"generators_id": [(3, 1)],
},
}
)
obs, reward, done, info = self.env.step(act)
assert info["exception"] # this is a game over
assert done
if __name__ == "__main__":
unittest.main()
| 42,193 | 43.555438 | 116 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_VoltageControler.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
from grid2op.tests.helper_path_test import *
from grid2op.VoltageControler import ControlVoltageFromFile
from grid2op.MakeEnv import make
import warnings
warnings.simplefilter("error")
class TestLoadingVoltageControl(unittest.TestCase):
def test_creation_ControlVoltage(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
volt_cont = ControlVoltageFromFile(
controler_backend=env.backend,
gridobj=env.backend,
actionSpace_cls=env._helper_action_class,
)
def test_copy(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with make("rte_case5_example", test=True) as env:
volt_cont = ControlVoltageFromFile(
controler_backend=env.backend,
gridobj=env.backend,
actionSpace_cls=env._helper_action_class,
)
res = volt_cont.copy()
assert isinstance(res, ControlVoltageFromFile)
if __name__ == "__main__":
unittest.main()
| 1,697 | 35.12766 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_act_as_serializable_dict.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import numpy as np
import warnings
import grid2op
from grid2op.dtypes import dt_int
from grid2op.Exceptions import *
from grid2op.Action import BaseAction, ActionSpace, PlayableAction, BaseAction
from grid2op.Rules import RulesChecker
from grid2op.Space import GridObjects
import json
import tempfile
import pdb
def _get_action_grid_class():
GridObjects.env_name = "test_action_serial_dict"
GridObjects.n_gen = 5
GridObjects.name_gen = np.array(["gen_{}".format(i) for i in range(5)])
GridObjects.n_load = 11
GridObjects.name_load = np.array(["load_{}".format(i) for i in range(11)])
GridObjects.n_line = 20
GridObjects.name_line = np.array(["line_{}".format(i) for i in range(20)])
GridObjects.n_sub = 14
GridObjects.name_sub = np.array(["sub_{}".format(i) for i in range(14)])
GridObjects.sub_info = np.array(
[3, 7, 5, 6, 5, 6, 3, 2, 5, 3, 3, 3, 4, 3], dtype=dt_int
)
GridObjects.load_to_subid = np.array([1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13])
GridObjects.gen_to_subid = np.array([0, 1, 2, 5, 7])
GridObjects.line_or_to_subid = np.array(
[0, 0, 1, 1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 8, 8, 9, 11, 12]
)
GridObjects.line_ex_to_subid = np.array(
[1, 4, 2, 3, 4, 3, 4, 6, 8, 5, 10, 11, 12, 7, 8, 9, 13, 10, 12, 13]
)
GridObjects.load_to_sub_pos = np.array([4, 2, 5, 4, 4, 4, 1, 1, 1, 2, 1])
GridObjects.gen_to_sub_pos = np.array([2, 5, 3, 5, 1])
GridObjects.line_or_to_sub_pos = np.array(
[0, 1, 1, 2, 3, 1, 2, 3, 4, 3, 1, 2, 3, 1, 2, 2, 3, 0, 0, 1]
)
GridObjects.line_ex_to_sub_pos = np.array(
[0, 0, 0, 0, 1, 1, 2, 0, 0, 0, 2, 2, 3, 0, 1, 2, 2, 0, 0, 0]
)
GridObjects.load_pos_topo_vect = np.array(
[7, 12, 20, 25, 30, 41, 43, 46, 49, 53, 56]
)
GridObjects.gen_pos_topo_vect = np.array([2, 8, 13, 31, 36])
GridObjects.line_or_pos_topo_vect = np.array(
[0, 1, 4, 5, 6, 11, 17, 18, 19, 24, 27, 28, 29, 33, 34, 39, 40, 42, 48, 52]
)
GridObjects.line_ex_pos_topo_vect = np.array(
[3, 21, 10, 15, 22, 16, 23, 32, 37, 26, 47, 50, 54, 35, 38, 44, 57, 45, 51, 55]
)
GridObjects.redispatching_unit_commitment_availble = True
GridObjects.gen_type = np.array(["thermal"] * 3 + ["wind"] * 2)
GridObjects.gen_pmin = np.array([0.0] * 5)
GridObjects.gen_pmax = np.array([100.0] * 5)
GridObjects.gen_min_uptime = np.array([0] * 5)
GridObjects.gen_min_downtime = np.array([0] * 5)
GridObjects.gen_cost_per_MW = np.array([70.0] * 5)
GridObjects.gen_startup_cost = np.array([0.0] * 5)
GridObjects.gen_shutdown_cost = np.array([0.0] * 5)
GridObjects.gen_redispatchable = np.array([True, True, True, False, False])
GridObjects.gen_max_ramp_up = np.array([10.0, 5.0, 15.0, 7.0, 8.0])
GridObjects.gen_max_ramp_down = np.array([11.0, 6.0, 16.0, 8.0, 9.0])
GridObjects.gen_renewable = ~GridObjects.gen_redispatchable
GridObjects.n_storage = 2
GridObjects.name_storage = np.array(["storage_0", "storage_1"])
GridObjects.storage_to_subid = np.array([1, 2])
GridObjects.storage_to_sub_pos = np.array([6, 4])
GridObjects.storage_pos_topo_vect = np.array([9, 14])
GridObjects.storage_type = np.array(["battery"] * 2)
GridObjects.storage_Emax = np.array([100.0, 100.0])
GridObjects.storage_Emin = np.array([0.0, 0.0])
GridObjects.storage_max_p_prod = np.array([10.0, 10.0])
GridObjects.storage_max_p_absorb = np.array([15.0, 15.0])
GridObjects.storage_marginal_cost = np.array([0.0, 0.0])
GridObjects.storage_loss = np.array([0.0, 0.0])
GridObjects.storage_discharging_efficiency = np.array([1.0, 1.0])
GridObjects.storage_charging_efficiency = np.array([1.0, 1.0])
GridObjects._topo_vect_to_sub = np.repeat(
np.arange(GridObjects.n_sub), repeats=GridObjects.sub_info
)
GridObjects.glop_version = grid2op.__version__
GridObjects._PATH_ENV = None
GridObjects.shunts_data_available = True
GridObjects.n_shunt = 2
GridObjects.shunt_to_subid = np.array([0, 1])
GridObjects.name_shunt = np.array(["shunt_1", "shunt_2"])
GridObjects.alarms_area_lines = [[el for el in GridObjects.name_line]]
GridObjects.alarms_area_names = ["all"]
GridObjects.alarms_lines_area = {el: ["all"] for el in GridObjects.name_line}
GridObjects.dim_alarms = 1
my_cls = GridObjects.init_grid(GridObjects, force=True)
return my_cls
class TestActionSerialDict(unittest.TestCase):
def _action_setup(self):
# return self.ActionSpaceClass(self.gridobj, legal_action=self.game_rules.legal_action, actionClass=BaseAction)
return BaseAction
def tearDown(self):
self.authorized_keys = {}
self.gridobj._clear_class_attribute()
ActionSpace._clear_class_attribute()
def setUp(self):
"""
The case file is a representation of the case14 as found in the ieee14 powergrid.
:return:
"""
self.tolvect = 1e-2
self.tol_one = 1e-5
self.game_rules = RulesChecker()
GridObjects_cls = _get_action_grid_class()
self.gridobj = GridObjects_cls()
self.n_line = self.gridobj.n_line
self.ActionSpaceClass = ActionSpace.init_grid(GridObjects_cls)
act_cls = self._action_setup()
self.helper_action = self.ActionSpaceClass(
GridObjects_cls,
legal_action=self.game_rules.legal_action,
actionClass=act_cls,
)
self.helper_action.seed(42)
self.authorized_keys = self.helper_action().authorized_keys
self.size_act = self.helper_action.size()
def test_set_line_status(self):
act = self.helper_action(
{
"set_line_status": [
(l_id, status) for l_id, status in zip([2, 4, 5], [1, -1, 1])
]
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_change_status(self):
act = self.helper_action({"change_line_status": [l_id for l_id in [2, 4, 5]]})
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_set_bus(self):
act = self.helper_action(
{
"set_bus": [
(el_id, status)
for el_id, status in zip([2, 4, 5, 8, 9, 10], [1, -1, 1, 2, 2, 1])
]
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_change_bus(self):
act = self.helper_action(
{"change_bus": [el_id for el_id in [2, 4, 5, 8, 9, 10]]}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_redispatch(self):
act = self.helper_action(
{
"redispatch": [
(el_id, amount) for el_id, amount in zip([0, 2], [-3.0, 28.9])
]
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_curtail(self):
act = self.helper_action(
{"curtail": [(el_id, amount) for el_id, amount in zip([3, 4], [0.5, 0.7])]}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_set_storage(self):
act = self.helper_action(
{
"set_storage": [
(el_id, amount) for el_id, amount in zip([0, 1], [-0.5, 0.7])
]
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_raise_alarm(self):
act = self.helper_action({"raise_alarm": [0]})
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_injection(self):
np.random.seed(0)
act = self.helper_action(
{
"injection": {
"prod_p": np.random.uniform(size=self.helper_action.n_gen),
"prod_v": np.random.normal(size=self.helper_action.n_gen),
"load_p": np.random.lognormal(size=self.helper_action.n_load),
"load_q": np.random.logistic(size=self.helper_action.n_load),
}
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_shunt(self):
np.random.seed(0)
act = self.helper_action(
{
"shunt": {
"shunt_p": np.random.uniform(size=self.helper_action.n_shunt),
"shunt_q": np.random.normal(size=self.helper_action.n_shunt),
"shunt_bus": [(0, 1), (1, 2)],
}
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
def test_iadd(self):
"""I add a bug when += a change_bus after a set bus"""
act = self.helper_action(
{
"set_bus": [
(el_id, status)
for el_id, status in zip([2, 4, 5, 8, 9, 10], [1, -1, 1, 2, 2, 1])
]
}
)
act += self.helper_action(
{"change_bus": [el_id for el_id in [2, 4, 5, 8, 9, 10]]}
)
assert np.all(act._set_topo_vect <= 4)
def test_all_at_once(self):
np.random.seed(1)
act = self.helper_action(
{
"set_line_status": [
(l_id, status) for l_id, status in zip([2, 4, 5], [1, -1, 1])
]
}
)
act += self.helper_action({"change_line_status": [l_id for l_id in [2, 4, 5]]})
act += self.helper_action(
{
"set_bus": [
(el_id, status)
for el_id, status in zip([2, 4, 5, 8, 9, 10], [1, -1, 1, 2, 2, 1])
]
}
)
act += self.helper_action(
{"change_bus": [el_id for el_id in [2, 3, 5, 11, 12, 15]]}
)
act += self.helper_action(
{
"redispatch": [
(el_id, amount) for el_id, amount in zip([0, 2], [-3.0, 28.9])
]
}
)
act += self.helper_action(
{"curtail": [(el_id, amount) for el_id, amount in zip([3, 4], [0.5, 0.7])]}
)
act += self.helper_action(
{
"set_storage": [
(el_id, amount) for el_id, amount in zip([0, 1], [-0.5, 0.7])
]
}
)
act += self.helper_action({"raise_alarm": [0]})
act += self.helper_action(
{
"injection": {
"prod_p": np.random.uniform(size=self.helper_action.n_gen),
"prod_v": np.random.normal(size=self.helper_action.n_gen),
"load_p": np.random.lognormal(size=self.helper_action.n_load),
"load_q": np.random.logistic(size=self.helper_action.n_load),
}
}
)
act += self.helper_action(
{
"shunt": {
"shunt_p": np.random.uniform(size=self.helper_action.n_shunt),
"shunt_q": np.random.normal(size=self.helper_action.n_shunt),
"shunt_bus": [(0, 1), (1, 2)],
}
}
)
dict_ = act.as_serializable_dict()
act2 = self.helper_action(dict_)
assert act == act2
dict_2 = act.as_serializable_dict()
assert dict_ == dict_2
with tempfile.TemporaryFile(mode="w") as f:
json.dump(fp=f, obj=dict_)
class TestMultiGrid(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env1 = grid2op.make("l2rpn_case14_sandbox",
test=True,
action_class=PlayableAction,
_add_to_name="_TestMultiGrid")
self.env2 = grid2op.make("educ_case14_storage",
test=True,
action_class=PlayableAction,
_add_to_name="_TestMultiGrid")
return super().setUp()
def tearDown(self) -> None:
self.env1.close()
self.env2.close()
return super().tearDown()
def test_can_make_lineor(self):
act : BaseAction = self.env1.action_space({"set_bus": {"lines_or_id": [(0, 2), (5, 1), (15, 2)]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'set_bus': {'lines_or_id': [(0, 2), (5, 1), (15, 2)]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
act : BaseAction = self.env1.action_space({"change_bus": {"lines_or_id": [0, 5, 15]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'change_bus': {'lines_or_id': [0, 5, 15]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
def test_can_make_lineex(self):
act : BaseAction = self.env1.action_space({"set_bus": {"lines_ex_id": [(0, 2), (5, 1), (15, 2)]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'set_bus': {'lines_ex_id': [(0, 2), (5, 1), (15, 2)]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
act : BaseAction = self.env1.action_space({"change_bus": {"lines_ex_id": [0, 5, 15]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'change_bus': {'lines_ex_id': [0, 5, 15]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
def test_can_make_gen(self):
act : BaseAction = self.env1.action_space({"set_bus": {"generators_id": [(0, 2), (5, 1)]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'set_bus': {'generators_id': [(0, 2), (5, 1)]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
act : BaseAction = self.env1.action_space({"change_bus": {"generators_id": [0, 5]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'change_bus': {'generators_id': [0, 5]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
def test_can_make_load(self):
act : BaseAction = self.env1.action_space({"set_bus": {"loads_id": [(0, 2), (5, 1)]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'set_bus': {'loads_id': [(0, 2), (5, 1)]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
act : BaseAction = self.env1.action_space({"change_bus": {"loads_id": [0, 5]}})
dict_ = act.as_serializable_dict()
assert dict_ == {'change_bus': {'loads_id': [0, 5]}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
def test_with_gen_load_lineor_lineex(self):
act : BaseAction = self.env1.action_space({"set_bus": {"loads_id": [(0, 2), (5, 1)],
"generators_id": [(0, 2), (5, 1)],
"lines_ex_id": [(0, 2), (5, 1), (15, 2)],
"lines_or_id": [(0, 2), (5, 1), (15, 2)]
}})
dict_ = act.as_serializable_dict()
assert dict_ == {'set_bus': {'loads_id': [(0, 2), (5, 1)],
'generators_id': [(0, 2), (5, 1)],
'lines_ex_id': [(0, 2), (5, 1), (15, 2)],
'lines_or_id': [(0, 2), (5, 1), (15, 2)]
}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
act : BaseAction = self.env1.action_space({"change_bus": {'loads_id': [0, 5],
'generators_id': [0, 5],
'lines_ex_id': [0, 5, 15],
'lines_or_id': [0, 5, 15]
}})
dict_ = act.as_serializable_dict()
assert dict_ == {'change_bus': {'loads_id': [0, 5],
'generators_id': [0, 5],
'lines_ex_id': [0, 5, 15],
'lines_or_id': [0, 5, 15]
}}
act2 = self.env2.action_space(dict_)
dict_2 = act2.as_serializable_dict()
assert dict_ == dict_2
if __name__ == "__main__":
unittest.main()
| 19,764 | 39.336735 | 119 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_action_space.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import os
import sys
import unittest
import warnings
import time
import numpy as np
import pdb
import grid2op
class BasicTestActSpace(unittest.TestCase):
def test_is_legal_None(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_case14_sandbox", test=True)
is_legal, reason = env.action_space._is_legal(None, None)
assert reason is None
assert is_legal
if __name__ == "__main__":
unittest.main()
| 987 | 29.875 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_alert_feature.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import unittest
import os
import copy
import tempfile
from grid2op.Observation import BaseObservation
from grid2op.tests.helper_path_test import *
from grid2op import make
from grid2op.Reward import AlertReward
from grid2op.Parameters import Parameters
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner # TODO
from grid2op.Opponent import BaseOpponent, GeometricOpponent
from grid2op.Action import BaseAction, PlayableAction
from grid2op.Agent import BaseAgent
from grid2op.Episode import EpisodeData
ALL_ATTACKABLE_LINES = [
"62_58_180",
"62_63_160",
"48_50_136",
"48_53_141",
"41_48_131",
"39_41_121",
"43_44_125",
"44_45_126",
"34_35_110",
"54_58_154",
]
def _get_steps_attack(kwargs_opponent, multi=False):
"""computes the steps for which there will be attacks"""
ts_attack = np.array(kwargs_opponent["steps_attack"])
res = []
for i, ts in enumerate(ts_attack):
if not multi:
res.append(ts + np.arange(kwargs_opponent["duration"]))
else:
res.append(ts + np.arange(kwargs_opponent["duration"][i]))
return np.unique(np.concatenate(res).flatten())
class OpponentForTestAlert(BaseOpponent):
"""An opponent that can select the line attack, the time and duration of the attack."""
def __init__(self, action_space):
super().__init__(action_space)
self.env = None
self.lines_attacked = None
self.custom_attack = None
self.attack_duration = None
self.attack_steps = None
self.attack_id = None
def _custom_deepcopy_for_copy(self, new_obj, dict_=None):
new_obj.env = dict_["partial_env"]
new_obj.lines_attacked = copy.deepcopy(self.lines_attacked)
new_obj.custom_attack = [act.copy() for act in self.custom_attack]
new_obj.attack_duration = copy.deepcopy(self.attack_duration)
new_obj.attack_steps = copy.deepcopy(self.attack_steps)
new_obj.attack_id = copy.deepcopy(self.attack_id)
return super()._custom_deepcopy_for_copy(new_obj, dict_)
def init(self,
partial_env,
lines_attacked=ALL_ATTACKABLE_LINES,
attack_duration=[],
attack_steps=[],
attack_id=[]):
self.lines_attacked = lines_attacked
self.custom_attack = [ self.action_space({"set_line_status" : [(l, -1)]}) for l in attack_id]
self.attack_duration = attack_duration
self.attack_steps = attack_steps
self.attack_id = attack_id
self.env = partial_env
def attack(self, observation, agent_action, env_action, budget, previous_fails):
if observation is None:
return None, None
current_step = self.env.nb_time_step
if current_step not in self.attack_steps:
return None, None
index = self.attack_steps.index(current_step)
return self.custom_attack[index], self.attack_duration[index]
# Test alert blackout / tets alert no blackout
class TestAction(unittest.TestCase):
"""test the basic bahavior of the assistant alert feature when no attack occur """
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
kwargs_opponent = dict(lines_attacked=ALL_ATTACKABLE_LINES)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=OpponentForTestAlert,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tafta")
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_init_default_param(self) -> None :
env = self.env
assert isinstance(env.parameters.ALERT_TIME_WINDOW, np.int32)
assert env.parameters.ALERT_TIME_WINDOW > 0
param = env.parameters
param.init_from_dict({"ALERT_TIME_WINDOW": -1})
negative_value_invalid = False
try:
env.change_parameters(param)
env.reset()
except Exception as exc_:
negative_value_invalid = True
assert negative_value_invalid
# test observations for this env also
true_alertable_lines = ALL_ATTACKABLE_LINES
assert isinstance(env.alertable_line_names, list)
assert sorted(env.alertable_line_names) == sorted(true_alertable_lines)
assert env.dim_alerts == len(true_alertable_lines)
def test_raise_alert_action(self) -> None :
"""test i can raise an alert on all attackable lines"""
env = self.env
for attackable_line_id in range(env.dim_alerts):
# raise alert on line number line_id
act = env.action_space()
act.raise_alert = [attackable_line_id]
act_2 = env.action_space({"raise_alert": [attackable_line_id]})
assert act == act_2, f"error for line {attackable_line_id}"
for attackable_line_id in range(env.dim_alerts):
for attackable_line_id2 in range(env.dim_alerts):
if attackable_line_id2 == attackable_line_id:
continue
act = env.action_space()
act.raise_alert = [attackable_line_id, attackable_line_id2]
act_2 = env.action_space({"raise_alert": [attackable_line_id2, attackable_line_id]})
assert act == act_2, f"error for line {attackable_line_id}"
assert act._raise_alert[attackable_line_id]
assert act._raise_alert[attackable_line_id2]
assert np.sum(act._raise_alert) == 2
assert act._modif_alert
def test_print_alert_action(self) -> None :
"""test i can print an alert on all attackable lines"""
attackable_line_id = 0
# raise alert on line number line_id
act = self.env.action_space()
act.raise_alert = [attackable_line_id]
assert act.__str__() == 'This action will:\n\t - NOT change anything to the injections\n\t - NOT perform any redispatching action\n\t - NOT modify any storage capacity\n\t - NOT perform any curtailment\n\t - NOT force any line status\n\t - NOT switch any line status\n\t - NOT switch anything in the topology\n\t - NOT force any particular bus configuration\n\t - Raise alert(s) : 0 (on line 62_58_180)'
def test_sample_a_random_alert_action(self) -> None :
"""test i can sample an alert on a set of attackable lines"""
random_action = self.env.action_space.sample()
assert random_action.raise_alert.shape == (self.env.dim_alerts,)
assert isinstance(random_action.raise_alert, np.ndarray)
assert random_action.raise_alert.dtype == bool
def test_ambiguous_illicit_alert_action(self) -> None :
"""test an alert is ambiguous or not """
attackable_line_id = 0
# raise alert on line number line_id
act = self.env.action_space()
act.raise_alert = [attackable_line_id]
assert not act.is_ambiguous()[0]
attackable_line_id = 0
# raise alert on line number line_id
act2 = self.env.action_space()
try:
act2.raise_alert = [self.env.dim_alerts]
except Exception as e:
assert e.args[0] == 'Impossible to modify the alert with your input. Please consult the documentation. The error was:\n"Grid2OpException IllegalAction "Impossible to change a raise alert id 10 because there are only 10 on the grid (and in python id starts at 0)""'
# TODO : is it really illicit or rather ambiguous ?
#assert act.is_ambiguous()[0]
# Test alert blackout / tets alert no blackout
class TestObservation(unittest.TestCase):
"""test the basic bahavior of the assistant alert feature when no attack occur """
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
kwargs_opponent = dict(lines_attacked=ALL_ATTACKABLE_LINES)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=OpponentForTestAlert,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tafto")
param = self.env.parameters
param.ALERT_TIME_WINDOW = 2
self.env.change_parameters(param)
assert type(self.env).dim_alerts == len(ALL_ATTACKABLE_LINES)
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def _aux_obs_init(self, obs):
assert np.all(obs.active_alert == False)
assert np.all(obs.time_since_last_alert == -1)
assert np.all(obs.time_since_last_attack == -1)
assert np.all(obs.alert_duration == 0)
assert obs.total_number_of_alert == 0
assert np.all(obs.was_alert_used_after_attack == False)
def test_init_observation(self) -> None :
obs : BaseObservation = self.env.reset()
self._aux_obs_init(obs)
def _aux_alert_0(self, obs):
assert obs.active_alert[0]
assert obs.active_alert.sum() == 1
assert obs.time_since_last_alert[0] == 0
assert np.all(obs.time_since_last_alert[1:] == -1)
assert np.all(obs.time_since_last_attack == -1)
assert np.all(obs.alert_duration[1:] == 0)
assert obs.alert_duration[0] == 1
assert obs.total_number_of_alert == 1
assert np.all(obs.was_alert_used_after_attack == False)
def test_after_action(self):
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
self._aux_alert_0(obs)
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0, 1]}))
assert np.all(obs.active_alert[:2])
assert obs.active_alert.sum() == 2
assert obs.time_since_last_alert[0] == 0
assert obs.time_since_last_alert[1] == 0
assert np.all(obs.time_since_last_alert[2:] == -1)
assert np.all(obs.time_since_last_attack == -1)
assert obs.alert_duration[0] == 2
assert obs.alert_duration[1] == 1
assert np.all(obs.alert_duration[2:] == 0)
assert obs.total_number_of_alert == 3
assert np.all(obs.was_alert_used_after_attack == False)
obs : BaseObservation = self.env.reset()
self._aux_obs_init(obs)
def test_illegal_action(self):
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0],
"set_bus": {"lines_or_id": [(0, 2), (19, 2)]}}))
assert info["is_illegal"]
self._aux_alert_0(obs)
def test_ambiguous_action_nonalert(self):
obs : BaseObservation = self.env.reset()
act = self.env.action_space({"raise_alert": [0]})
# now create an ambiguous action that is accepted by grid2op (which is not that easy)
act._set_topo_vect[0] = 2 # ambiguous because the flag has not been modified !
obs, reward, done, info = self.env.step(act)
assert info["is_ambiguous"]
self._aux_alert_0(obs)
def test_ambiguous_action_alert(self):
obs : BaseObservation = self.env.reset()
act = self.env.action_space({"raise_alert": [0]})
# now create an ambiguous action that is accepted by grid2op (which is not that easy)
act._modif_alert = False # ambiguous because the flag has not been modified !
obs, reward, done, info = self.env.step(act)
assert info["is_ambiguous"]
self._aux_obs_init(obs)
def test_env_cpy(self):
obs : BaseObservation = self.env.reset()
env_cpy = self.env.copy()
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
self._aux_alert_0(obs)
obs_cpy, *_ = env_cpy.step(self.env.action_space())
self._aux_obs_init(obs_cpy)
def test_attack_under_alert(self):
obs : BaseObservation = self.env.reset()
attack_id = np.where(self.env.name_line == ALL_ATTACKABLE_LINES[0])[0][0]
opp = self.env._oppSpace.opponent
opp.custom_attack = [opp.action_space({"set_line_status" : [(l, -1)]}) for l in [attack_id]]
opp.attack_duration = [3]
opp.attack_steps = [2]
opp.attack_id = [attack_id]
# wrong alert is sent
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [1]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]})) # I cannot change the past
assert reward == 1., f"{reward} vs 1."
assert obs.time_since_last_attack[0] == 2
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space())
assert reward == 0., f"{reward} vs 0."
assert obs.time_since_last_attack[0] == 3
assert obs.attack_under_alert[0] == 0
# right alert is sent
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.attack_under_alert[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert reward == -1., f"{reward} vs -1."
assert obs.time_since_last_attack[0] == 2
assert obs.attack_under_alert[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space())
assert reward == 0., f"{reward} vs 0."
assert obs.time_since_last_attack[0] == 3
assert obs.attack_under_alert[0] == 0
def test_alert_duration(self):
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert obs.alert_duration[0] == 1
assert np.all(obs.alert_duration[1:] == 0)
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.alert_duration[0] == 0
assert np.all(obs.alert_duration[1:] == 0)
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert obs.alert_duration[0] == 1
assert np.all(obs.alert_duration[1:] == 0)
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert obs.alert_duration[0] == 2
assert np.all(obs.alert_duration[1:] == 0)
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert obs.alert_duration[0] == 3
assert np.all(obs.alert_duration[1:] == 0)
def test_time_since_last_attack(self):
obs : BaseObservation = self.env.reset()
# tell the opponent to make 2 attacks
attack_id = np.where(self.env.name_line == ALL_ATTACKABLE_LINES[0])[0][0]
opp = self.env._oppSpace.opponent
opp.custom_attack = [opp.action_space({"set_line_status" : [(l, -1)]}) for l in [attack_id, attack_id]]
opp.attack_duration = [1, 2]
opp.attack_steps = [2, 4]
opp.attack_id = [attack_id, attack_id]
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is None
assert obs.time_since_last_attack[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is not None
assert obs.time_since_last_attack[0] == 1
def test_alert_used_after_attack(self):
obs : BaseObservation = self.env.reset()
assert obs.was_alert_used_after_attack.shape == (10,)
assert obs.was_alert_used_after_attack.dtype == np.int32
assert obs.was_alert_used_after_attack.sum() == 0
# tell the opponent to make 2 attacks
attack_id = np.where(self.env.name_line == ALL_ATTACKABLE_LINES[0])[0][0]
opp = self.env._oppSpace.opponent
opp.custom_attack = [opp.action_space({"set_line_status" : [(l, -1)]}) for l in [attack_id, attack_id]]
opp.attack_duration = [1, 2]
opp.attack_steps = [2, 4]
opp.attack_id = [attack_id, attack_id]
obs : BaseObservation = self.env.reset()
act = self.env.action_space()
act.raise_alert = [0]
obs, reward, done, info = self.env.step(act)
assert obs.time_since_last_attack[0] == -1
assert obs.was_alert_used_after_attack[0] == 0
assert obs.was_alert_used_after_attack[1:].sum() == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 0
assert obs.was_alert_used_after_attack[0] == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.was_alert_used_after_attack[0] == 0
assert obs.was_alert_used_after_attack[1:].sum() == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 0
assert obs.was_alert_used_after_attack[0] == 1
assert obs.was_alert_used_after_attack[1:].sum() == 0
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.was_alert_used_after_attack[0] == 0
assert obs.was_alert_used_after_attack[1:].sum() == 0
def test_when_attacks(self):
obs : BaseObservation = self.env.reset()
# tell the opponent to make an attack
attack_id = np.where(self.env.name_line == ALL_ATTACKABLE_LINES[0])[0][0]
opp = self.env._oppSpace.opponent
opp.custom_attack = [opp.action_space({"set_line_status" : [(l, -1)]}) for l in [attack_id]]
opp.attack_duration = [1]
opp.attack_steps = [2]
opp.attack_id = [attack_id]
# 1 no game over
# 1a alert on the wrong line, the was_alert_used_after_attack[0] should be 1
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [1]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space())
assert reward == 1., f"{reward} vs 1."
assert obs.time_since_last_attack[0] == 2
assert obs.attack_under_alert[0] == -1
assert obs.was_alert_used_after_attack[1] == 0
assert obs.was_alert_used_after_attack[0] == 1 # used (even if I did not sent an alarm, which by default means 'no alarm')
assert np.all(obs.was_alert_used_after_attack[2:] == 0)
# 1b alert on the right line (which is wrong), the was_alert_used_after_attack[0] should be -1
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == 1
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 1
assert obs.attack_under_alert[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.time_since_last_attack[0] == 2
assert obs.attack_under_alert[0] == 1
assert reward == -1., f"{reward} vs -1."
assert obs.was_alert_used_after_attack[0] == -1
assert np.all(obs.was_alert_used_after_attack[1:] == 0)
# 2 game over
# 2a no alert on the line
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [1]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == -1
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}}))
assert done
assert reward == -10., f"{reward} vs -10."
assert obs.was_alert_used_after_attack[1] == 0
assert obs.was_alert_used_after_attack[0] == -1, f"{obs.was_alert_used_after_attack[0]} vs -1" # used (even if I did not sent an alarm, which by default means 'no alarm')
assert np.all(obs.was_alert_used_after_attack[2:] == 0)
# 2b alert on the line (game over in window)
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
assert obs.time_since_last_attack[0] == 0
assert obs.attack_under_alert[0] == 1
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}}))
assert done
assert reward == 2., f"{reward} vs 2."
assert obs.was_alert_used_after_attack[1] == 0
assert obs.was_alert_used_after_attack[0] == 1, f"{obs.was_alert_used_after_attack[0]} vs 1"
assert np.all(obs.was_alert_used_after_attack[2:] == 0)
# 2c alert on the line (game over still in window)
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}}))
assert done
assert reward == 2., f"{reward} vs 2."
assert obs.was_alert_used_after_attack[1] == 0
assert obs.was_alert_used_after_attack[0] == 1, f"{obs.was_alert_used_after_attack[0]} vs 1"
assert np.all(obs.was_alert_used_after_attack[2:] == 0)
# 2c alert on the line (game over out of the window)
obs : BaseObservation = self.env.reset()
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"raise_alert": [0]}))
assert info["opponent_attack_line"] is not None
assert info["opponent_attack_line"][attack_id]
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space())
obs, reward, done, info = self.env.step(self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}}))
assert done
assert reward == 0., f"{reward} vs 2."
assert obs.was_alert_used_after_attack[1] == 0
assert obs.was_alert_used_after_attack[0] == 0, f"{obs.was_alert_used_after_attack[0]} vs 0"
assert np.all(obs.was_alert_used_after_attack[2:] == 0)
# TODO test the update_obs_after_reward in the runner !
# TODO test "as_dict" and "as_json"
if __name__ == "__main__":
unittest.main()
| 27,413 | 46.184165 | 411 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_alert_gym_compat.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.dtypes import dt_bool, dt_int
from grid2op.tests.helper_path_test import *
from grid2op.Action import PlayableAction
try:
from grid2op.gym_compat import (GymEnv, GYM_AVAILABLE, GYMNASIUM_AVAILABLE)
from grid2op.gym_compat import MultiToTupleConverter
from grid2op.gym_compat import (
BoxGymObsSpace,
BoxGymActSpace,
MultiDiscreteActSpace,
DiscreteActSpace,
)
CAN_DO_TEST = True
except ImportError:
CAN_DO_TEST = False
if CAN_DO_TEST:
if GYMNASIUM_AVAILABLE:
import gymnasium as gym_for_test_agc
else:
import gym as gym_for_test_agc
import pdb
import warnings
warnings.simplefilter("error")
class TestGymAlertCompat(unittest.TestCase):
def _skip_if_no_gym(self):
if not CAN_DO_TEST:
self.skipTest("Gym is not available")
def setUp(self) -> None:
self._skip_if_no_gym()
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
self.env_nm, test=True, _add_to_name="TestGymAlertCompat"
)
self.env.seed(0)
self.env.reset() # seed part !
def tearDown(self) -> None:
self.env.close()
def test_print_alert(self):
env_gym = GymEnv(self.env)
str_ = env_gym.action_space.__str__()
assert str_ == ("Dict('change_bus': MultiBinary(177), 'change_line_status': MultiBinary(59), "
"'curtail': Box([-1. 0. -1. -1. -1. 0. 0. 0. 0. 0. -1. 0. 0. -1. 0. 0. -1. "
"0.\n 0. -1. -1. -1.], [-1. 1. -1. -1. -1. 1. 1. 1. 1. 1. -1. 1. 1. -1. 1. "
"1. -1. 1.\n 1. -1. -1. -1.], (22,), float32), 'raise_alert': MultiBinary(10), "
"'redispatch': Box([ -1.4 0. -1.4 -10.4 -1.4 0. 0. 0. 0. 0. -2.8 "
"0.\n 0. -2.8 0. 0. -4.3 0. 0. -2.8 -8.5 -9.9], [ 1.4 0. 1.4 10.4 "
"1.4 0. 0. 0. 0. 0. 2.8 0. 0. 2.8\n 0. 0. 4.3 0. 0. 2.8 8.5 9.9], "
"(22,), float32), 'set_bus': Box(-1, 2, (177,), int32), 'set_line_status': Box(-1, 1, (59,), int32))")
str_ = env_gym.observation_space.__str__()
assert str_ == ("Dict('_shunt_bus': Box(-2147483648, 2147483647, (6,), int32), '_shunt_p': Box(-inf, inf, (6,), float32), "
"'_shunt_q': Box(-inf, inf, (6,), float32), '_shunt_v': Box(-inf, inf, (6,), float32), "
"'a_ex': Box(0.0, inf, (59,), float32), 'a_or': Box(0.0, inf, (59,), float32), 'active_alert': MultiBinary(10), "
"'actual_dispatch': Box([ -50. -67.2 -50. -250. -50. -33.6 -37.3 -37.3 -33.6 -74.7\n -100. -37.3 -37.3 "
"-100. -74.7 -74.7 -150. -67.2 -74.7 -400.\n -300. -350. ], [ 50. 67.2 50. 250. 50. 33.6 37.3 37.3 "
"33.6 74.7 100. 37.3\n 37.3 100. 74.7 74.7 150. 67.2 74.7 400. 300. 350. ], (22,), float32), "
"'alert_duration': Box(0, 2147483647, (10,), int32), 'attack_under_alert': Box(-1, 1, (10,), int32), "
"'attention_budget': Box(0.0, inf, (1,), float32), 'current_step': Box(-2147483648, 2147483647, (1,), int32), "
"'curtailment': Box(0.0, 1.0, (22,), float32), 'curtailment_limit': Box(0.0, 1.0, (22,), float32), "
"'curtailment_limit_effective': Box(0.0, 1.0, (22,), float32), 'day': Discrete(32), 'day_of_week': Discrete(8), "
"'delta_time': Box(0.0, inf, (1,), float32), 'duration_next_maintenance': Box(-1, 2147483647, (59,), int32), "
"'gen_margin_down': Box(0.0, [ 1.4 0. 1.4 10.4 1.4 0. 0. 0. 0. 0. 2.8 0. 0. 2.8\n 0. 0. "
"4.3 0. 0. 2.8 8.5 9.9], (22,), float32), 'gen_margin_up': Box(0.0, [ 1.4 0. 1.4 10.4 1.4 0. "
"0. 0. 0. 0. 2.8 0. 0. 2.8\n 0. 0. 4.3 0. 0. 2.8 8.5 9.9], (22,), float32), "
"'gen_p': Box(-734.88995, [ 784.88995 802.08997 784.88995 984.88995 784.88995 768.4899\n "
"772.18994 772.18994 768.4899 809.58997 834.88995 772.18994\n 772.18994 834.88995 "
"809.58997 809.58997 884.88995 802.08997\n 809.58997 1134.8899 1034.8899 1084.8899 ], "
"(22,), float32), 'gen_p_before_curtail': Box(-734.88995, [ 784.88995 802.08997 784.88995 "
"984.88995 784.88995 768.4899\n 772.18994 772.18994 768.4899 809.58997 834.88995 "
"772.18994\n 772.18994 834.88995 809.58997 809.58997 884.88995 802.08997\n 809.58997 "
"1134.8899 1034.8899 1084.8899 ], (22,), float32), 'gen_q': Box(-inf, inf, (22,), float32), "
"'gen_theta': Box(-180.0, 180.0, (22,), float32), 'gen_v': Box(0.0, inf, (22,), float32), "
"'hour_of_day': Discrete(24), 'is_alarm_illegal': Discrete(2), 'line_status': MultiBinary(59), "
"'load_p': Box(-inf, inf, (37,), float32), 'load_q': Box(-inf, inf, (37,), float32), "
"'load_theta': Box(-180.0, 180.0, (37,), float32), 'load_v': Box(0.0, inf, (37,), float32), "
"'max_step': Box(-2147483648, 2147483647, (1,), int32), 'minute_of_hour': Discrete(60), "
"'month': Discrete(13), 'p_ex': Box(-inf, inf, (59,), float32), 'p_or': Box(-inf, inf, (59,), float32), "
"'q_ex': Box(-inf, inf, (59,), float32), 'q_or': Box(-inf, inf, (59,), float32), 'rho': Box(0.0, inf, (59,), float32), "
"'target_dispatch': Box([ -50. -67.2 -50. -250. -50. -33.6 -37.3 -37.3 -33.6 -74.7\n -100. "
"-37.3 -37.3 -100. -74.7 -74.7 -150. -67.2 -74.7 -400.\n -300. -350. ], [ 50. 67.2 50. 250. 50. "
"33.6 37.3 37.3 33.6 74.7 100. 37.3\n 37.3 100. 74.7 74.7 150. 67.2 74.7 400. 300. 350. ], "
"(22,), float32), 'thermal_limit': Box(0.0, inf, (59,), float32), 'theta_ex': Box(-180.0, 180.0, (59,), "
"float32), 'theta_or': Box(-180.0, 180.0, (59,), float32), 'time_before_cooldown_line': Box(0, 96, (59,), int32), "
"'time_before_cooldown_sub': Box(0, 3, (36,), int32), 'time_next_maintenance': Box(-1, 2147483647, (59,), int32), "
"'time_since_last_alarm': Box(-1, 2147483647, (1,), int32), 'time_since_last_alert': Box(-1, 2147483647, (10,), int32), "
"'time_since_last_attack': Box(-1, 2147483647, (10,), int32), 'timestep_overflow': Box(-2147483648, 2147483647, (59,), int32), "
"'topo_vect': Box(-1, 2, (177,), int32), 'total_number_of_alert': Box(0, 2147483647, (1,), int32), 'v_ex': Box(0.0, inf, "
"(59,), float32), 'v_or': Box(0.0, inf, (59,), float32), 'was_alarm_used_after_game_over': Discrete(2), "
"'was_alert_used_after_attack': Box(-1, 1, (10,), int32), 'year': Discrete(2100))")
act = self.env.action_space()
act.raise_alert = [2]
act_gym = env_gym.action_space.to_gym(act)
act_str = act_gym.__str__()
assert act_str == ("OrderedDict([('change_bus', array([False, False, False, False, False, False, False, False, False,"
"\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, "
"False, False, False, False, False, False,\n False, False, False, False, False, False, False, "
"False, False,\n False, False, False, False, False, False, False, False, False,\n False, "
"False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, "
"False, False, False,\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False])), ('change_line_status', array([False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n "
"False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, "
"False, False, False, False,\n False, False, False, False, False])), ('curtail', array([-1., -1., -1., "
"-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.,\n -1., -1., -1., -1., -1., -1., -1., -1., -1.], "
"dtype=float32)), ('raise_alert', array([False, False, True, False, False, False, False, False, False,\n "
"False])), ('redispatch', array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n "
"0., 0., 0., 0., 0.], dtype=float32)), ('set_bus', array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0], dtype=int32)), "
"('set_line_status', array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32))])")
def test_convert_alert_to_gym(self):
"""test i can create the env"""
env_gym = GymEnv(self.env)
dim_act_space = np.sum(
[
np.sum(env_gym.action_space[el].shape)
for el in env_gym.action_space.spaces
]
)
assert dim_act_space == 526, f"{dim_act_space} != 526"
dim_obs_space = np.sum(
[
np.sum(env_gym.observation_space[el].shape).astype(int)
for el in env_gym.observation_space.spaces
]
)
size_th = 1718 # as of grid2Op 1.9.1 (where alerts are added)
assert (
dim_obs_space == size_th
), f"Size should be {size_th} but is {dim_obs_space}"
# test that i can do basic stuff there
obs, info = env_gym.reset()
for k in env_gym.observation_space.spaces.keys():
assert obs[k] in env_gym.observation_space[k], f"error for key: {k}"
act = env_gym.action_space.sample()
obs2, reward2, done2, truncated, info2 = env_gym.step(act)
assert obs2 in env_gym.observation_space
# test for the __str__ method (it could crash)
str_ = self.env.action_space.__str__()
str_ = self.env.observation_space.__str__()
def test_ignore_some_alert_attributes(self):
"""test the ignore_attr method"""
env_gym = GymEnv(self.env)
env_gym.action_space = env_gym.action_space.ignore_attr("last_alert").ignore_attr(
"was_alert_used_after_attack"
)
dim_act_space = np.sum(
[
np.sum(env_gym.action_space[el].shape)
for el in env_gym.action_space.spaces
]
)
assert dim_act_space == 526, f"{dim_act_space=} != 526"
def test_keep_only_2_alert_attr(self):
"""test the keep_only_attr method"""
env_gym = GymEnv(self.env)
env_gym.observation_space = env_gym.observation_space.keep_only_attr(
["last_alert",
"was_alert_used_after_attack"
]
)
new_dim_obs_space = np.sum(
[
np.sum(env_gym.observation_space[el].shape).astype(int)
for el in env_gym.observation_space.spaces
]
)
assert new_dim_obs_space == 10, f"{new_dim_obs_space=} != 10"
def test_all_together_in_alert(self):
"""combine all test above (for the action space)"""
env_gym = GymEnv(self.env)
env_gym.action_space = env_gym.action_space.reencode_space(
"raise_alert", MultiToTupleConverter()
)
assert isinstance(env_gym.action_space["raise_alert"], gym_for_test_agc.spaces.Tuple)
act_gym = env_gym.action_space.sample()
act_glop = env_gym.action_space.from_gym(act_gym)
act_gym2 = env_gym.action_space.to_gym(act_glop)
act_glop2 = env_gym.action_space.from_gym(act_gym2)
assert act_gym in env_gym.action_space
assert act_gym2 in env_gym.action_space
assert isinstance(act_gym["raise_alert"], tuple)
# check the gym actions are the same
for k in act_gym.keys():
assert np.array_equal(act_gym[k], act_gym2[k]), f"error for {k}"
for k in act_gym2.keys():
assert np.array_equal(act_gym[k], act_gym2[k]), f"error for {k}"
# check grid2op action are the same
assert act_glop == act_glop2
def test_low_high_alert_obs_space(self):
"""test the observation space, by default, is properly converted"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"l2rpn_idf_2023", test=True, _add_to_name="TestGymCompatModule"
)
env.seed(0)
env.reset() # seed part !
env_gym = GymEnv(env)
for key, low, high in zip(["attack_under_alert",
"time_since_last_alert",
"alert_duration",
"time_since_last_attack",
"was_alert_used_after_attack"],
[np.zeros(env.dim_alerts, dtype=dt_int) - 1,
np.zeros(env.dim_alerts, dtype=dt_int) - 1,
np.zeros(env.dim_alerts, dtype=dt_int),
np.zeros(env.dim_alerts, dtype=dt_int) - 1,
np.zeros(env.dim_alerts, dtype=dt_int) - 1],
[np.zeros(env.dim_alerts, dtype=dt_int) + 1,
np.zeros(env.dim_alerts, dtype=dt_int) + 2147483647,
np.zeros(env.dim_alerts, dtype=dt_int) + 2147483647,
np.zeros(env.dim_alerts, dtype=dt_int) + 2147483647,
np.zeros(env.dim_alerts, dtype=dt_int) + 1]):
assert key in env_gym.observation_space.spaces
assert isinstance(env_gym.observation_space[key], gym_for_test_agc.spaces.Box)
assert env_gym.observation_space[key].shape == (env.dim_alerts, )
assert env_gym.observation_space[key].dtype == dt_int
assert np.array_equal(
env_gym.observation_space[key].low, low
), f"issue for {key}"
assert np.array_equal(
env_gym.observation_space[key].high, high
), f"issue for {key}"
key = "total_number_of_alert"
assert key in env_gym.observation_space.spaces
assert isinstance(env_gym.observation_space[key], gym_for_test_agc.spaces.Box)
assert env_gym.observation_space[key].dtype == dt_int
assert env_gym.observation_space[key].shape == (1, )
assert env_gym.observation_space.spaces[key].low == [0]
assert env_gym.observation_space.spaces[key].high == [2147483647]
key = "active_alert"
assert key in env_gym.observation_space.spaces
assert isinstance(env_gym.observation_space[key], gym_for_test_agc.spaces.MultiBinary)
assert env_gym.observation_space[key].shape == (22, )
class TestBoxGymObsSpaceWithAlert(unittest.TestCase):
def _skip_if_no_gym(self):
if not CAN_DO_TEST:
self.skipTest("Gym is not available")
def setUp(self) -> None:
self._skip_if_no_gym()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"l2rpn_idf_2023",
test=True
)
self.env.seed(0)
self.env.reset() # seed part !
self.obs_env = self.env.reset()
self.env_gym = GymEnv(self.env)
def test_can_create(self):
kept_attr = [
"active_alert",
"alert_duration",
"attack_under_alert",
"time_since_last_alert",
"time_since_last_attack",
"total_number_of_alert",
"was_alert_used_after_attack"
]
self.env_gym.observation_space = BoxGymObsSpace(
self.env.observation_space,
attr_to_keep=kept_attr,
)
obs_gym, info = self.env_gym.reset()
assert self.env_gym.observation_space._attr_to_keep == sorted(kept_attr)
assert len(obs_gym) == 133, f"{len(obs_gym)} vs 133"
assert self.env_gym.observation_space.dtype == dt_int
assert obs_gym in self.env_gym.observation_space
class TestAllGymActSpaceWithAlert(unittest.TestCase):
def _skip_if_no_gym(self):
if not CAN_DO_TEST:
self.skipTest("Gym is not available")
def setUp(self) -> None:
self._skip_if_no_gym()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
os.path.join(PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"),
test=True,
action_class=PlayableAction,
_add_to_name="TestAllGymActSpaceWithAlert",
)
self.env.seed(0)
self.env.reset() # seed part !
self.obs_env = self.env.reset()
self.env_gym = GymEnv(self.env)
def test_supported_keys_box(self):
"""test all the attribute of the action can be modified when the action is converted to a float"""
all_attr = {
"raise_alert": len(self.env.alertable_line_ids),
}
func_check = {
"raise_alert": lambda act: np.any(act.raise_alert)
and ~np.all(act.raise_alert),
}
for attr_nm in sorted(all_attr.keys()):
kept_attr = [attr_nm]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env_gym.action_space = BoxGymActSpace(
self.env.action_space, attr_to_keep=kept_attr
)
self.env_gym.action_space.seed(0)
gym_act = self.env_gym.action_space.sample()
grid2op_act = self.env_gym.action_space.from_gym(gym_act)
assert isinstance(grid2op_act, PlayableAction)
assert self.env_gym.action_space._attr_to_keep == kept_attr
assert (
len(self.env_gym.action_space.sample()) == all_attr[attr_nm]
), f"wrong size for {attr_nm}"
# check that all types
ok_ = func_check[attr_nm](grid2op_act)
if not ok_ and attr_nm != "set_storage":
# NB for "set_storage" as there are no storage unit on this grid, then this test is doomed to fail
# this is why i don't perform it in this case
raise RuntimeError(
f"Some property of the actions are not modified for attr {attr_nm}"
)
def test_supported_keys_multidiscrete(self):
"""test that i can modify every action with the keys"""
dims = {
"raise_alert": len(self.env.alertable_line_ids),
}
func_check = {
"raise_alert": lambda act: np.any(act.raise_alert)
and ~np.all(act.raise_alert),
}
for attr_nm in sorted(dims.keys()):
kept_attr = [attr_nm]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env_gym.action_space = MultiDiscreteActSpace(
self.env.action_space, attr_to_keep=kept_attr
)
assert self.env_gym.action_space._attr_to_keep == kept_attr
self.env_gym.action_space.seed(0)
assert (
len(self.env_gym.action_space.sample()) == dims[attr_nm]
), f"wrong size for {attr_nm}"
grid2op_act = self.env_gym.action_space.from_gym(
self.env_gym.action_space.sample()
)
assert isinstance(grid2op_act, PlayableAction)
# check that all types
ok_ = func_check[attr_nm](grid2op_act)
if not ok_ and attr_nm != "set_storage":
# NB for "set_storage" as there are no storage unit on this grid, then this test is doomed to fail
# this is why i don't perform it in this case
raise RuntimeError(
f"Some property of the actions are not modified for attr {attr_nm}"
)
class ObsAlertAttr(unittest.TestCase):
def test_alert_attr_in_obs(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_idf_2023", test=True,
action_class=PlayableAction,
_add_to_name="ObsAlertAttr")
gym_env = GymEnv(env)
obs, info = gym_env.reset()
alert_attrs = [
"active_alert",
"alert_duration",
"attack_under_alert",
"time_since_last_alert",
"time_since_last_attack",
"total_number_of_alert",
"was_alert_used_after_attack"
]
for el in alert_attrs:
assert el in obs.keys(), f"\"{el}\" not in obs.keys()"
if __name__ == "__main__":
unittest.main()
| 24,553 | 53.564444 | 152 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_alert_score.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import unittest
import os
import tempfile
from grid2op.Observation import BaseObservation
from grid2op.tests.helper_path_test import *
from grid2op import make
from grid2op.Reward import AlertReward
from grid2op.Parameters import Parameters
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner # TODO
from grid2op.Opponent import BaseOpponent, GeometricOpponent
from grid2op.Action import BaseAction, PlayableAction
from grid2op.Agent import BaseAgent
from grid2op.Episode import EpisodeData
ALL_ATTACKABLE_LINES= [
"62_58_180",
"62_63_160",
"48_50_136",
"48_53_141",
"41_48_131",
"39_41_121",
"43_44_125",
"44_45_126",
"34_35_110",
"54_58_154",
]
ATTACKED_LINE = "48_50_136"
def _get_steps_attack(kwargs_opponent, multi=False):
"""computes the steps for which there will be attacks"""
ts_attack = np.array(kwargs_opponent["steps_attack"])
res = []
for i, ts in enumerate(ts_attack):
if not multi:
res.append(ts + np.arange(kwargs_opponent["duration"]))
else:
res.append(ts + np.arange(kwargs_opponent["duration"][i]))
return np.unique(np.concatenate(res).flatten())
class TestOpponent(BaseOpponent):
"""An opponent that can select the line attack, the time and duration of the attack."""
def __init__(self, action_space):
super().__init__(action_space)
self.custom_attack = None
self.duration = None
self.steps_attack = None
def init(self, partial_env, lines_attacked=[ATTACKED_LINE], duration=10, steps_attack=[0,1]):
attacked_line = lines_attacked[0]
self.custom_attack = self.action_space({"set_line_status" : [(l, -1) for l in lines_attacked]})
self.duration = duration
self.steps_attack = steps_attack
self.env = partial_env
def attack(self, observation, agent_action, env_action, budget, previous_fails):
if observation is None:
return None, None
current_step = self.env.nb_time_step
if current_step not in self.steps_attack:
return None, None
return self.custom_attack, self.duration
class TestOpponentMultiLines(BaseOpponent):
"""An opponent that can select the line attack, the time and duration of the attack."""
def __init__(self, action_space):
super().__init__(action_space)
self.custom_attack = None
self.duration = None
self.steps_attack = None
def init(self, partial_env, lines_attacked=[ATTACKED_LINE], duration=[10,10], steps_attack=[0,1]):
attacked_line = lines_attacked[0]
self.custom_attack = [ self.action_space({"set_line_status" : [(l, -1)]}) for l in lines_attacked]
self.duration = duration
self.steps_attack = steps_attack
self.env = partial_env
def attack(self, observation, agent_action, env_action, budget, previous_fails):
if observation is None:
return None, None
current_step = self.env.nb_time_step
if current_step not in self.steps_attack:
return None, None
index = self.steps_attack.index(current_step)
return self.custom_attack[index], self.duration[index]
# Test alert blackout / tets alert no blackout
class TestAlertNoBlackout(unittest.TestCase):
"""test the basic bahavior of the assistant alert feature when no attack occur """
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
def test_assistant_reward_value_no_blackout_no_attack_no_alert(self) -> None :
""" When no blackout and no attack occur, and no alert is raised we expect a reward of 0
until the end of the episode where we have a bonus (here artificially 42)
Raises:
Grid2OpException: raise an exception if an attack occur
"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
obs, reward, done, info = env.step(env.action_space())
if info["opponent_attack_line"] is None :
if i == env.max_episode_duration()-1:
assert reward == 42
else :
assert reward == 0
else :
raise Grid2OpException('No attack expected')
assert done
def test_assistant_reward_value_no_blackout_no_attack_alert(self) -> None :
""" When an alert is raised while no attack / nor blackout occur, we expect a reward of 0
until the end of the episode where we have a bonus (here artificially 42)
Raises:
Grid2OpException: raise an exception if an attack occur
"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
attackable_line_id=0
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if info["opponent_attack_line"] is None :
if step == env.max_episode_duration():
assert reward == 42
else :
assert reward == 0
else :
raise Grid2OpException('No attack expected')
assert done
# If attack
def test_assistant_reward_value_no_blackout_attack_no_alert(self) -> None :
""" When we don't raise an alert for an attack (at step 1)
but no blackout occur, we expect a reward of 1
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[1])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnbana"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 3 :
assert reward == 1
elif step == env.max_episode_duration():
assert reward == 42
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_attack_alert(self) -> None :
"""When an alert occur at step 2, we raise an alert at step 1
We expect a reward -1 at step 3 (with a window size of 2)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnba"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if i == 1 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == -1
elif step == env.max_episode_duration():
assert reward == 42
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_attack_alert_too_late(self) -> None :
""" When we raise an alert too late for an attack (at step 2) but no blackout occur,
we expect a reward of 1
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvnbaatl"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 2 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == 1
elif step == env.max_episode_duration():
assert reward == 1
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_attack_alert_too_early(self)-> None :
""" When we raise an alert too early for an attack (at step 2)
but no blackout occur, we expect a reward of 1
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvnbaate"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 0 :
# An alert is raised at step 0
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == 1
elif step == env.max_episode_duration():
assert reward == 1
else :
assert reward == 0
# 2 ligne attaquées
def test_assistant_reward_value_no_blackout_2_attack_same_time_no_alert(self) -> None :
""" When we don't raise an alert for 2 attacks at the same time (step 1)
but no blackout occur, we expect a reward of 1
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[1])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnb2astna"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 3 :
assert reward == 1
elif step == env.max_episode_duration():
assert reward == 42
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_2_attack_same_time_1_alert(self) -> None :
""" When we raise only 1 alert for 2 attacks at the same time (step 2)
but no blackout occur, we expect a reward of 0
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvnb2ast1a"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == 0
elif step == env.max_episode_duration():
assert reward == 1
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_2_attack_same_time_2_alert(self) -> None :
""" When we raise 2 alerts for 2 attacks at the same time (step 2)
but no blackout occur, we expect a reward of -1
at step 3 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvnb2ast2a"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_ids = [0, 1]
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": attackable_line_ids})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == -1
elif step == env.max_episode_duration():
assert reward == 1
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_2_attack_diff_time_no_alert(self) -> None :
""" When we don't raise an alert for 2 attacks at two times resp. (steps 1 and 2)
but no blackout occur, we expect a reward of 1
at step 3 and 4 (here with a window size of 2)
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1, 1],
steps_attack=[1, 2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnb2dtna"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True) :
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 3 :
assert reward == 1
elif step == 4 :
assert reward == 1
elif step == env.max_episode_duration():
assert reward == 42
else :
assert reward == 0
def test_assistant_reward_value_no_blackout_2_attack_diff_time_2_alert(self) -> None :
""" When we raise 2 alert for 2 attacks at two times (step 2 and 3)
but no blackout occur, we expect a reward of -1
at step 4 (here with a window size of 2) and step 5
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnb2dt2a"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [0]})
elif step == 2 :
act = env.action_space({"raise_alert": [1]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == -1, f"error for step {step}: {reward} instead of -1."
elif step == 5:
assert reward == -1
elif step == env.max_episode_duration():
assert reward == 42, f"error for step {step}: {reward} instead of -1."
else :
assert reward == 0, f"error for step {step}: {reward} instead of 0."
def test_assistant_reward_value_no_blackout_2_attack_diff_time_alert_first_attack(self) -> None :
""" When we raise 1 alert on the first attack while we have 2 attacks at two times (steps 2 and 3)
but no blackout occur, we expect a reward of -1
at step 4 (here with a window size of 2) and 1 at step 5
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnb2dtafa"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [0]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == -1, f"error for step {step}: {reward} vs -1"
elif step == 5 :
assert reward == 1, f"error for step {step}: {reward} vs 1"
elif step == env.max_episode_duration():
assert reward == 42, f"error for step {step}: {reward} vs 42"
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
def test_assistant_reward_value_no_blackout_2_attack_diff_time_alert_second_attack(self) -> None :
""" When we raise 1 alert on the second attack while we have 2 attacks at two times (steps 2 and 3)
but no blackout occur, we expect a reward of 1
at step 4 (here with a window size of 2) and -1 step 5
otherwise 0 at other time steps
until the end of the episode where we have a bonus (here artificially 42)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvnb2dtasa"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if i == 2 :
act = env.action_space({"raise_alert": [1]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert reward == 1, f"error for step {step}: {reward} vs 1"
elif step == 5 :
assert reward == -1, f"error for step {step}: {reward} vs -1"
elif step == env.max_episode_duration():
assert reward == 42, f"error for step {step}: {reward} vs 42"
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
def test_raise_illicit_alert(self) -> None:
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
assert type(env).dim_alerts == 10, f"dim_alerts: {type(env).dim_alerts} instead of 10"
attackable_line_id = 10
try :
act = env.action_space({"raise_alert": [attackable_line_id]})
except Grid2OpException as exc_ :
assert exc_.args[0] == ('Impossible to modify the alert with your input. Please consult the '
'documentation. The error was:\n"Grid2OpException IllegalAction '
'"Impossible to change a raise alert id 10 because there are only '
'10 on the grid (and in python id starts at 0)""')
class TestAlertBlackout(unittest.TestCase):
"""test the basic bahavior of the assistant alert feature when a blackout occur"""
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
def get_dn(self, env):
return env.action_space({})
def get_blackout(self, env):
blackout_action = env.action_space({})
blackout_action.gen_set_bus = [(0, -1)]
return blackout_action
# Cas avec blackout 1 ligne attaquée
# return -10
def test_assistant_reward_value_blackout_attack_no_alert(self) -> None :
"""
When 1 line is attacked at step 3 and we don't raise any alert
and a blackout occur at step 4
we expect a reward of -10 at step 4
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvbana"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if step == 3 :
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
# When the blackout occurs, reward is -10 because we didn't raise an attack
assert reward == -10, f"error for step {step}: {reward} vs -10"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return 2
def test_assistant_reward_value_blackout_attack_raise_good_alert(self) -> None :
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvbarga"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 2:
# I raise the alert (on the right line) just before the opponent attack
# opp attack at step = 3, so i = 2
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == 2, f"error for step {step}: {reward} vs 2"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return -10
def test_assistant_reward_value_blackout_attack_raise_alert_just_before_blackout(self) -> None :
"""
When 1 line is attacked at step 3 and we raise 1 alert too late
we expect a reward of -10 at step 4 when the blackout occur
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvbarajbb"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 1:
# opponent attack at step 3, so when i = 2
# i raise the alert BEFORE that (so when i = 1)
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == -10, f"error for step {step}: {reward} vs -10"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
def test_assistant_reward_value_blackout_attack_raise_alert_too_early(self) -> None :
"""
When 1 line is attacked at step 3 and we raise 1 alert too early
we expect a reward of -10 at step 4 when the blackout occur
"""
# return -10
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvbarate"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 1:
# opp attacks at step = 3, so i = 2, I raise an alert just before
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == -10, f"error for step {step}: {reward} vs -10"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return 2
def test_assistant_reward_value_blackout_2_lines_same_step_in_window_good_alerts(self) -> None :
"""
When 2 lines are attacked simustaneously at step 2 and we raise 2 alert
we expect a reward of 2 at the blackout (step 4)
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[3, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvb2lssiwga"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 2:
# attack at step 3, so when i = 2 (which is the right time to send an alert)
act = env.action_space({"raise_alert": [0,1]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert done
assert reward == 2, f"error for step {step}: {reward} vs 2"
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return -4
def test_assistant_reward_value_blackout_2_lines_attacked_simulaneous_only_1_alert(self) -> None:
"""
When 2 lines are attacked simustaneously at step 2 and we raise only 1 alert
we expect a reward of -4 when the blackout occur at step 4
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[3, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tarvb2laso1a"
) as env :
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 2:
# attack at step 3, so i = 2, which is the
# right time to send an alert
act = env.action_space({"raise_alert": [0]})
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4:
assert reward == -4, f"error for step {step}: {reward} vs -4"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return 2
def test_assistant_reward_value_blackout_2_lines_different_step_in_window_good_alerts(self) -> None :
"""
When 2 lines are attacked at different steps 3 and 4 and we raise 2 alert
we expect a reward of 2 when the blackout occur at step 5
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[3, 4])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvb2ldsiwga"
) as env :
env.seed(0)
obs = env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 2 :
# opp attack "line 0" at step 3 so i = 2 => good alert
act = env.action_space({"raise_alert": [0]})
elif i == 3 :
# opp attack "line 1" at step 4 so i = 3 => good alert
act = env.action_space({"raise_alert": [1]})
elif i == 4 :
# trigger blackout
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 5 :
assert done # blackout
assert reward == 2, f"error for step {step}: {reward} vs 2"
break
elif step == env.max_episode_duration():
assert reward == 42, f"error for step {step}: {reward} vs 42"
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
def test_assistant_reward_value_blackout_2_lines_attacked_different_step_in_window_only_1_alert_on_first_attacked_line(self) -> None:
"""
When 2 lines are attacked at different steps 3 and 4 and we raise 1 alert on the first attack
we expect a reward of -4 on blackout at step 4
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[3, 4])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvb2ladsiwo1aofal"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 2 :
# opp attack "line 0" at step 3 so i = 2 => good alert
act = env.action_space({"raise_alert": [0]})
elif i == 3 :
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
step += 1 # i = step - 1 at this stage
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 4 :
assert done # blackout
assert reward == -4, f"error for step {step}: {reward} vs -4" # bug in Laure too
break
elif step == env.max_episode_duration():
assert reward == 42, f"error for step {step}: {reward} vs 42"
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return -4
def test_assistant_reward_value_blackout_2_lines_attacked_different_step_in_window_only_1_alert_on_second_attacked_line(self) -> None:
"""
When 2 lines are attacked at different steps 2 and 3 and we raise 1 alert on the second attack
we expect a reward of -4 at step 5 when the blackout occur
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[3, 4])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvb2ladsiwo1aosal"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3 :
# opp attack "line 1" at step 4 so i = 3 => good alert
act = env.action_space({"raise_alert": [1]})
elif i == 4 :
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 5 :
assert reward == -4., f"error for step {step}: {reward} vs -4"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return 2
def test_assistant_reward_value_blackout_2_lines_attacked_different_1_in_window_1_good_alert(self) -> None:
"""
When 2 lines are attacked at different steps 3 and 6 and we raise 1 alert on the second attack
we expect a reward of 1 at step 5 and 2 at step 7 when the blackout happen
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1, 1],
steps_attack=[3, 6])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name="_tarvb2lad1iw1ga"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 5 :
# opp attack "line 1" at step 6 so i = 5 => good alert
act = env.action_space({"raise_alert": [1]})
elif i == 6 :
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if step == 5:
assert reward == 1, f"error for step {step}: {reward} vs 1" # no blackout here
elif step == 7 :
assert reward == 2, f"error for step {step}: {reward} vs 2"
assert done
break
else :
assert reward == 0, f"error for step {step}: {reward} vs 0"
# return 0
def test_assistant_reward_value_blackout_no_attack_alert(self) -> None :
"""Even if there is a blackout, an we raise an alert
we expect a reward of 0 because there is no attack"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 1:
act = env.action_space({"raise_alert": [0]})
obs, reward, done, info = env.step(act)
if info["opponent_attack_line"] is None :
assert reward == 0.
else :
raise Grid2OpException('No attack expected')
if done :
break
assert done
# return 0
def test_assistant_reward_value_blackout_no_attack_no_alert(self) -> None :
"""Even if there is a blackout, an we don't raise an alert
we expect a reward of 0 because there is no attack"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
obs, reward, done, info = env.step(act)
if info["opponent_attack_line"] is None :
assert reward == 0.
else :
raise Grid2OpException('No attack expected')
if done :
break
assert done
# return 0
def test_assistant_reward_value_blackout_attack_before_window_alert(self) -> None :
"""Even if there is a blackout, an we raise an alert too early
we expect a reward of 0 because there is no attack"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i in [0, 1, 2]:
act = env.action_space({"raise_alert": [0]})
obs, reward, done, info = env.step(act)
if info["opponent_attack_line"] is None :
assert reward == 0.
else :
raise Grid2OpException('No attack expected')
if done :
break
assert done
# return 0
def test_assistant_reward_value_blackout_attack_before_window_no_alert(self) -> None :
"""Even if there is a blackout, an we raise an alert too late
we expect a reward of 0 because there is no attack"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3 :
act = self.get_blackout(env)
elif i == 4:
# we never go here ...
act = env.action_space({"raise_alert": [0]})
obs, reward, done, info = env.step(act)
if info["opponent_attack_line"] is None :
assert reward == 0.
else :
raise Grid2OpException('No attack expected')
if done :
break
assert done
class TestSimulate(unittest.TestCase):
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
self.env = make(self.env_nm, test=True, difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42))
self.env.seed(0)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_simulate(self):
obs = self.env.reset()
simO, simr, simd, simi = obs.simulate(self.env.action_space())
assert simr == 0.
assert not simd
go_act = self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}})
simO, simr, simd, simi = obs.simulate(go_act)
assert simr == 0., f"{simr} vs 0."
assert simd
def test_simulated_env(self):
obs = self.env.reset()
f_env = obs.get_forecast_env()
forD = False
while not forD:
forO, forR, forD, forI = f_env.step(self.env.action_space())
assert forR == 0.
f_env = obs.get_forecast_env()
forD = False
go_act = self.env.action_space({"set_bus": {"generators_id": [(0, -1)]}})
while not forD:
forO, forR, forD, forI = f_env.step(go_act)
assert forR == 0.
class TestRunner(unittest.TestCase):
def setUp(self) -> None:
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
self.env = make(self.env_nm, test=True, difficulty="1",
reward_class=AlertReward(reward_end_episode_bonus=42))
self.env.seed(0)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_dn_agent(self):
obs = self.env.reset()
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0])
assert res[0][2] == 42
def test_simagent(self):
obs = self.env.reset()
class SimAgent(BaseAgent):
def act(self, observation: BaseObservation, reward: float, done: bool = False) -> BaseAction:
go_act = self.action_space({"set_bus": {"generators_id": [(0, -1)]}})
simO, simr, simd, simi = obs.simulate(go_act)
simO, simr, simd, simi = obs.simulate(self.action_space())
return super().act(observation, reward, done)
runner = Runner(**self.env.get_params_for_runner(),
agentClass=SimAgent)
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0])
assert res[0][2] == 42
def test_episodeData(self):
obs = self.env.reset()
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0], add_detailed_output=True)
assert res[0][2] == 42
assert res[0][5].rewards[8] == 42
def test_with_save(self):
obs = self.env.reset()
runner = Runner(**self.env.get_params_for_runner())
with tempfile.TemporaryDirectory() as f:
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0],
path_save=f)
assert res[0][2] == 42
ep0, *_ = EpisodeData.list_episode(f)
ep = EpisodeData.from_disk(*ep0)
assert ep.rewards[8] == 42
def test_with_opp(self):
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
env = make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=AlertReward(reward_end_episode_bonus=42),
_add_to_name = "_test_with_opp")
# without alert
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0])
assert res[0][2] == 43, f"{res[0][2]} vs 43"
class AlertAgent(BaseAgent):
def act(self, observation: BaseObservation, reward: float, done: bool = False) -> BaseAction:
if observation.current_step == 2:
return self.action_space({"raise_alert": [0]})
return super().act(observation, reward, done)
# with a wrong alert
runner = Runner(**env.get_params_for_runner(), agentClass=AlertAgent)
res = runner.run(nb_episode=1, episode_id=[0], max_iter=10, env_seeds=[0])
assert res[0][2] == 41, f"{res[0][2]} vs 41"
if __name__ == "__main__":
unittest.main()
| 64,336 | 42.707201 | 138 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_attached_envs.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import unittest
import grid2op
from grid2op.Action.PowerlineSetAction import PowerlineSetAction
from grid2op.Action.PlayableAction import PlayableAction
from grid2op.Observation.completeObservation import CompleteObservation
from grid2op.Action.DontAct import DontAct
from grid2op.Opponent import GeometricOpponent
import pdb
# TODO refactor to have 1 base class, maybe
class TestL2RPNNEURIPS2020_Track1(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_neurips_2020_track1", test=True)
self.env.seed(0)
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 36
assert self.env.n_line == 59
assert self.env.n_load == 37
assert self.env.n_gen == 22
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, PowerlineSetAction)
assert self.env._opponent_action_space.n == self.env.n_line
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 494, f"{self.env.action_space.n} instead of 494"
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 1266
assert self.env.observation_space.n == size_th, (
f"obs space size is {self.env.observation_space.n}, should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestL2RPNICAPS2021(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_icaps_2021", test=True)
self.env.seed(0)
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 36
assert self.env.n_line == 59
assert self.env.n_load == 37
assert self.env.n_gen == 22
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, PowerlineSetAction)
assert isinstance(self.env._opponent, GeometricOpponent)
assert self.env._opponent_action_space.n == self.env.n_line
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 519, (
f"act space size is {self.env.action_space.n}, should be {519}"
)
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 1363
assert self.env.observation_space.n == size_th, (
f"obs space size is "
f"{self.env.observation_space.n}, "
f"should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestL2RPNNEURIPS2020_Track2(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_neurips_2020_track2", test=True)
self.env.seed(2) # 0 or 1 breaks the test `test_random_action`
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 118
assert self.env.n_line == 186
assert self.env.n_load == 99
assert self.env.n_gen == 62
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 1500, f"{self.env.action_space.n} instead of 1500"
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 3868
assert self.env.observation_space.n == size_th, (
f"obs space size is {self.env.observation_space.n}, should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first 10 steps. "
"Please fix the test and try again"
)
class TestL2RPN_CASE14_SANDBOX(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
self.env.seed(42)
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 166, f"{self.env.action_space.n} instead of 166"
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 467
assert self.env.observation_space.n == size_th, (
f"obs space size is {self.env.observation_space.n}," f"should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestEDUC_CASE14_REDISP(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("educ_case14_redisp", test=True)
self.env.seed(0)
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 26, f"{self.env.action_space.n} instead of 26"
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 467
assert self.env.observation_space.n == size_th, (
f"obs space size is {self.env.observation_space.n}," f"should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestEDUC_STORAGE(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("educ_case14_storage", test=True)
self.env.seed(0)
_ = self.env.reset()
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 2
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 28, f"{self.env.action_space.n} instead of 28"
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
size_th = 475
assert self.env.observation_space.n == size_th, (
f"obs space size is {self.env.observation_space.n}," f"should be {size_th}"
)
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
if __name__ == "__main__":
unittest.main()
| 10,855 | 35.8 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_attached_envs_compat.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import unittest
import grid2op
import numpy as np
from grid2op.Space import GridObjects
from grid2op.Action.PowerlineSetAction import PowerlineSetAction
from grid2op.Action.PlayableAction import PlayableAction
from grid2op.Observation.completeObservation import CompleteObservation
from grid2op.Action.DontAct import DontAct
import pdb
# TODO refactor to have 1 base class, maybe
class TestL2RPNNEURIPS2020_Track1Compat(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"l2rpn_neurips_2020_track1",
test=True,
_compat_glop_version=GridObjects.BEFORE_COMPAT_VERSION,
_add_to_name="test_attached_compat_0",
)
self.env.seed(0)
def test_elements(self):
assert self.env.n_sub == 36
assert self.env.n_line == 59
assert self.env.n_load == 37
assert self.env.n_gen == 22
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, PowerlineSetAction)
assert self.env._opponent_action_space.n == self.env.n_line
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 494
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
assert self.env.observation_space.n == 1266
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestL2RPNNEURIPS2020_Track2Compat(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"l2rpn_neurips_2020_track2",
test=True,
_compat_glop_version=GridObjects.BEFORE_COMPAT_VERSION,
_add_to_name="test_attached_compat_1",
)
self.env.seed(0)
def test_elements(self):
assert self.env.n_sub == 118
assert self.env.n_line == 186
assert self.env.n_load == 99
assert self.env.n_gen == 62
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 1500
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
assert (
"curtailment" not in self.env.observation_space.subtype.attr_list_vect
), "curtailment should not be there"
assert self.env.observation_space.n == 3868
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestL2RPN_CASE14_SANDBOXCompat(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"l2rpn_case14_sandbox",
test=True,
_compat_glop_version=GridObjects.BEFORE_COMPAT_VERSION,
_add_to_name="test_attached_compat_2",
)
self.env.seed(42)
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 160
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
assert self.env.observation_space.n == 420
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestEDUC_CASE14_REDISPCompat(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_redisp",
test=True,
_compat_glop_version=GridObjects.BEFORE_COMPAT_VERSION,
_add_to_name="test_attached_compat_3",
)
self.env.seed(0)
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 26
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
assert self.env.observation_space.n == 420
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
class TestCompatMode_WhenStorage(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_storage",
test=True,
_compat_glop_version=GridObjects.BEFORE_COMPAT_VERSION,
_add_to_name="test_attached_compat_4",
)
self.env.seed(0)
def test_elements(self):
assert self.env.n_sub == 14
assert self.env.n_line == 20
assert self.env.n_load == 11
assert self.env.n_gen == 6
assert self.env.n_storage == 0
def test_opponent(self):
assert issubclass(self.env._opponent_action_class, DontAct)
assert self.env._opponent_action_space.n == 0
def test_action_space(self):
assert issubclass(self.env.action_space.subtype, PlayableAction)
assert self.env.action_space.n == 26
def test_observation_space(self):
assert issubclass(self.env.observation_space.subtype, CompleteObservation)
assert self.env.observation_space.n == 420
def test_same_env_as_no_storage(self):
res = 0
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("educ_case14_redisp", test=True)
for attr in self.env.observation_space.attr_list_vect:
tmp = getattr(self.env.observation_space._template_obj, attr).shape
tmp2 = getattr(env.observation_space._template_obj, attr).shape
if tmp:
res += tmp[0]
else:
res += 1
assert tmp == tmp2, f"error for {attr}"
# TODO for all the other attributes too (maybe they are, i'm not sure)...
for type_ in ["load", "gen", "line_or", "line_ex"]:
for el in [
f"{type_}_pos_topo_vect",
f"{type_}_to_sub_pos",
f"{type_}_to_subid",
]:
assert np.array_equal(
getattr(type(env), el), getattr(type(self.env), el)
), f"error for {el}"
for el in ["sub_info", "grid_objects_types", "_topo_vect_to_sub"]:
assert np.array_equal(
getattr(type(env), el), getattr(type(self.env), el)
), f"error for {el}"
def test_random_action(self):
"""test i can perform some step (random)"""
i = 0
for i in range(10):
act = self.env.action_space.sample()
obs, reward, done, info = self.env.step(act)
if done:
pdb.set_trace()
break
assert i >= 1, (
"could not perform the random action test because it games over first time step. "
"Please fix the test and try again"
)
if __name__ == "__main__":
unittest.main()
| 10,340 | 35.157343 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_back_to_orig.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
# do some generic tests that can be implemented directly to test if a backend implementation can work out of the box
# with grid2op.
# see an example of test_Pandapower for how to use this suit.
import unittest
import numpy as np
import warnings
import grid2op
from grid2op.Parameters import Parameters
from grid2op.Action import BaseAction
import pdb
class Test_BackToOrig(unittest.TestCase):
def setUp(self) -> None:
self.env_name = "educ_case14_storage"
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_LINE = 0
param.NB_TIMESTEP_COOLDOWN_SUB = 0
param.ACTIVATE_STORAGE_LOSS = False
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
self.env_name, test=True, action_class=BaseAction, param=param
)
def tearDown(self) -> None:
self.env.close()
def test_substation(self):
obs, reward, done, info = self.env.step(
self.env.action_space({"set_bus": {"substations_id": [(2, (1, 2, 2, 1))]}})
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{"set_bus": {"substations_id": [(5, (1, 2, 2, 1, 2, 1, 1, 2))]}}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "substation" in res
assert len(res["substation"]) == 2
for act in res["substation"]:
lines_impacted, subs_impacted = act.get_topological_impact()
assert subs_impacted[2] ^ subs_impacted[5] # xor
assert np.sum(lines_impacted) == 0
for act in res["substation"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
def test_line(self):
obs = self.env.reset()
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 0
obs, reward, done, info = self.env.step(
self.env.action_space({"set_line_status": [(12, -1)]})
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space({"set_line_status": [(15, -1)]})
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "powerline" in res
assert len(res["powerline"]) == 2
for act in res["powerline"]:
lines_impacted, subs_impacted = act.get_topological_impact()
assert lines_impacted[12] ^ lines_impacted[15] # xor
assert np.sum(subs_impacted) == 0
for act in res["powerline"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
def test_redisp(self):
obs = self.env.reset()
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 0
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"redispatch": [
(0, self.env.gen_max_ramp_up[0]),
(1, -self.env.gen_max_ramp_down[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "redispatching" in res
assert len(res["redispatching"]) == 1 # one action is enough
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"redispatch": [
(0, self.env.gen_max_ramp_up[0]),
(1, -self.env.gen_max_ramp_down[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "redispatching" in res
assert len(res["redispatching"]) == 2 # one action is NOT enough
for act in res["redispatching"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
np.max(np.abs(obs.target_dispatch)) <= 1e-6
) # I am in the original topology
assert len(self.env.action_space.get_back_to_ref_state(obs)) == 0
# now try with "non integer" stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"redispatch": [
(0, self.env.gen_max_ramp_up[0]),
(1, -self.env.gen_max_ramp_down[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"redispatch": [
(0, 0.5 * self.env.gen_max_ramp_up[0]),
(1, -0.5 * self.env.gen_max_ramp_down[1]),
]
}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "redispatching" in res
assert len(res["redispatching"]) == 2 # one action is NOT enough
for act in res["redispatching"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
np.max(np.abs(obs.target_dispatch)) <= 1e-6
) # I am in the original topology
# try with non integer, non symmetric stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"redispatch": [
(0, self.env.gen_max_ramp_up[0]),
(1, -self.env.gen_max_ramp_down[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{"redispatch": [(0, 0.5 * self.env.gen_max_ramp_up[0])]}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "redispatching" in res
assert len(res["redispatching"]) == 2 # one action is NOT enough
for act in res["redispatching"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
np.max(np.abs(obs.target_dispatch)) <= 1e-6
) # I am in the original topology
assert len(self.env.action_space.get_back_to_ref_state(obs)) == 0
def test_storage_no_loss(self):
obs = self.env.reset()
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 0
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 1 # one action is enough (no losses)
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
# now try with "non integer" stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, 0.5 * self.env.storage_max_p_absorb[0]),
(1, -0.5 * self.env.storage_max_p_prod[1]),
]
}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert np.max(np.abs(obs.target_dispatch)) <= 1e-6
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
# try with non integer, non symmetric stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{"set_storage": [(0, 0.5 * self.env.storage_max_p_absorb[0])]}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
def test_storage_with_loss(self):
param = self.env.parameters
param.ACTIVATE_STORAGE_LOSS = True
self.env.change_parameters(param)
obs = self.env.reset()
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 0
# check i get the right power if i do nothing
obs, reward, done, info = self.env.step(self.env.action_space())
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 1 # one action is enough to compensate the losses
assert np.all(
np.abs(res["storage"][0].storage_p - self.env.storage_loss) <= 1e-5
)
# now do some action
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough (no losses)
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 3 # two actions are NOT enough (losses)
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
dict_ = self.env.action_space.get_back_to_ref_state(obs)
assert len(dict_) == 1
assert "storage" in dict_
assert np.all(
np.abs(dict_["storage"][0].storage_p - 3.0 * self.env.storage_loss) <= 1e-5
) # I am in the original topology (up to the storage losses)
# now try with "non integer" stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, 0.5 * self.env.storage_max_p_absorb[0]),
(1, -0.5 * self.env.storage_max_p_prod[1]),
]
}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
dict_ = self.env.action_space.get_back_to_ref_state(obs)
assert len(dict_) == 1
assert "storage" in dict_
assert np.all(
np.abs(dict_["storage"][0].storage_p - 2.0 * self.env.storage_loss) <= 1e-5
) # I am in the original topology (up to the storage losses)
# try with non integer, non symmetric stuff
obs, reward, done, info = self.env.step(
self.env.action_space(
{
"set_storage": [
(0, self.env.storage_max_p_absorb[0]),
(1, -self.env.storage_max_p_prod[1]),
]
}
)
)
assert not done
obs, reward, done, info = self.env.step(
self.env.action_space(
{"set_storage": [(0, 0.5 * self.env.storage_max_p_absorb[0])]}
)
)
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "storage" in res
assert len(res["storage"]) == 2 # one action is NOT enough
for act in res["storage"]:
obs, reward, done, info = self.env.step(act)
assert not done
dict_ = self.env.action_space.get_back_to_ref_state(obs)
assert len(dict_) == 1
assert "storage" in dict_
assert np.all(
np.abs(dict_["storage"][0].storage_p - 2.0 * self.env.storage_loss) <= 1e-5
) # I am in the original topology (up to the storage losses)
def test_curtailment(self):
obs, reward, done, info = self.env.step(
self.env.action_space({"curtail": [(3, 0.05)]})
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "curtailment" in res
assert len(res["curtailment"]) == 1
for act in res["curtailment"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert np.all(obs.curtailment_limit == 1.0)
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
obs, reward, done, info = self.env.step(
self.env.action_space({"curtail": [(3, 0.05)]})
)
obs, reward, done, info = self.env.step(
self.env.action_space({"curtail": [(4, 0.5)]})
)
assert not done
res = self.env.action_space.get_back_to_ref_state(obs)
assert len(res) == 1
assert "curtailment" in res
assert len(res["curtailment"]) == 1
for act in res["curtailment"]:
obs, reward, done, info = self.env.step(act)
assert not done
assert np.all(obs.curtailment_limit == 1.0)
assert (
len(self.env.action_space.get_back_to_ref_state(obs)) == 0
) # I am in the original topology
# TODO test when not all action types are enable (typically the change / set part)
if __name__ == "__main__":
unittest.main()
| 17,595 | 36.200846 | 116 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_change_param_from_obs.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
import pdb
class TestChangeParamFromObs(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_change_param_simulate(self):
l_id = 3
params = self.env.parameters
params.HARD_OVERFLOW_THRESHOLD = 1.
th_lim = self.env.get_thermal_limit()
th_lim[l_id] = 170
self.env.set_thermal_limit(th_lim)
self.env.change_parameters(params)
self.env.change_forecast_parameters(params)
obs = self.env.reset()
# line 0 is connected
assert obs.rho[l_id] > 0
assert obs.line_status[0]
# changes not done
assert not obs._obs_env.parameters.NO_OVERFLOW_DISCONNECTION
# sim_obs sees line 0 disconnected (flow above the hard threshold)
sim_obs, *_ = obs.simulate(self.env.action_space())
assert sim_obs.rho[l_id] == 0
assert not sim_obs.line_status[0]
# now do the change
params.NO_OVERFLOW_DISCONNECTION = True
obs.change_forecast_parameters(params)
sim_obs, *_ = obs.simulate(self.env.action_space())
assert obs._obs_env.parameters.NO_OVERFLOW_DISCONNECTION
assert sim_obs.rho[l_id] > 1.
assert sim_obs.line_status[0]
def test_change_param_get_f_env(self):
obs = self.env.reset()
params = self.env.parameters
params.NO_OVERFLOW_DISCONNECTION = True
# before changing the parameters
f_env = obs.get_forecast_env()
assert not f_env.parameters.NO_OVERFLOW_DISCONNECTION
# now change the parameters
obs.change_forecast_parameters(params)
f_env2 = obs.get_forecast_env()
assert f_env2.parameters.NO_OVERFLOW_DISCONNECTION
# check with simulate now
sim_obs, *_ = obs.simulate(self.env.action_space())
f_env3 = obs.get_forecast_env()
assert f_env3.parameters.NO_OVERFLOW_DISCONNECTION
if __name__ == "__main__":
unittest.main()
| 2,799 | 34.897436 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_chronics_npy.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
import copy
from grid2op.Parameters import Parameters
from grid2op.Chronics import FromNPY
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner
import numpy as np
import pdb
from grid2op.tests.helper_path_test import *
class TestNPYChronics(unittest.TestCase):
"""
This class tests the possibility in grid2op to limit the number of call to "obs.simulate"
"""
def setUp(self):
self.env_name = "l2rpn_case14_sandbox"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env_ref = grid2op.make(self.env_name, test=True)
self.load_p = 1.0 * self.env_ref.chronics_handler.real_data.data.load_p
self.load_q = 1.0 * self.env_ref.chronics_handler.real_data.data.load_q
self.prod_p = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_p
self.prod_v = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_v
def tearDown(self) -> None:
self.env_ref.close()
def test_proper_start_end(self):
"""test i can create an environment with the FromNPY class"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 18, # excluded
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
for ts in range(10):
obs_ref, *_ = self.env_ref.step(env.action_space())
assert np.all(
obs_ref.gen_p[:-1] == self.prod_p[1 + ts, :-1]
), f"error at iteration {ts}"
obs, *_ = env.step(env.action_space())
assert np.all(obs_ref.gen_p == obs.gen_p), f"error at iteration {ts}"
# test the "end"
for ts in range(7):
obs, *_ = env.step(env.action_space())
obs, reward, done, info = env.step(env.action_space())
assert done
assert obs.max_step == 18
with self.assertRaises(Grid2OpException):
env.step(env.action_space()) # raises a Grid2OpException
env.close()
def test_proper_start_end_2(self):
"""test i can do as if the start was "later" """
LAG = 5
END = 18
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": LAG,
"i_end": END,
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
for ts in range(LAG):
obs_ref, *_ = self.env_ref.step(env.action_space())
for ts in range(END - LAG):
obs_ref, *_ = self.env_ref.step(env.action_space())
assert np.all(
obs_ref.gen_p[:-1] == self.prod_p[1 + ts + LAG, :-1]
), f"error at iteration {ts}"
obs, *_ = env.step(env.action_space())
assert np.all(obs_ref.gen_p == obs.gen_p), f"error at iteration {ts}"
assert obs.max_step == END
with self.assertRaises(Grid2OpException):
env.step(
env.action_space()
) # raises a Grid2OpException because the env is done
env.close()
def test_iend_bigger_dim(self):
max_step = 5
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": self.load_p[:max_step, :],
"load_q": self.load_q[:max_step, :],
"prod_p": self.prod_p[:max_step, :],
"prod_v": self.prod_v[:max_step, :],
},
)
assert env.chronics_handler.real_data._load_p.shape[0] == max_step
for ts in range(
max_step - 1
): # -1 because one ts is "burnt" for the initialization
obs, reward, done, info = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
obs, reward, done, info = env.step(env.action_space())
assert done
assert obs.max_step == max_step
with self.assertRaises(Grid2OpException):
env.step(
env.action_space()
) # raises a Grid2OpException because the env is done
env.close()
def test_change_iend(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
assert env.chronics_handler.real_data._i_end == self.load_p.shape[0]
env.chronics_handler.real_data.change_i_end(15)
env.reset()
assert env.chronics_handler.real_data._i_end == 15
env.reset()
assert env.chronics_handler.real_data._i_end == 15
env.chronics_handler.real_data.change_i_end(25)
assert env.chronics_handler.real_data._i_end == 15
env.reset()
assert env.chronics_handler.real_data._i_end == 25
env.chronics_handler.real_data.change_i_end(None) # reset default value
env.reset()
assert env.chronics_handler.real_data._i_end == self.load_p.shape[0]
# now make sure it recomputes the maximum even if i change the size of the input arrays
env.chronics_handler.real_data.change_chronics(
self.load_p[:10], self.load_q[:10], self.prod_p[:10], self.prod_v[:10]
)
env.reset()
assert env.chronics_handler.real_data._i_end == 10
env.chronics_handler.real_data.change_chronics(
self.load_p, self.load_q, self.prod_p, self.prod_v
)
env.reset()
assert env.chronics_handler.real_data._i_end == self.load_p.shape[0]
env.close()
def test_change_istart(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
assert env.chronics_handler.real_data._i_start == 0
env.chronics_handler.real_data.change_i_start(5)
env.reset()
assert env.chronics_handler.real_data._i_start == 5
env.reset()
assert env.chronics_handler.real_data._i_start == 5
env.chronics_handler.real_data.change_i_start(10)
assert env.chronics_handler.real_data._i_start == 5
env.reset()
assert env.chronics_handler.real_data._i_start == 10
env.chronics_handler.real_data.change_i_start(None) # reset default value
env.reset()
assert env.chronics_handler.real_data._i_start == 0
env.close()
def test_runner(self):
max_step = 10
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": self.load_p[:max_step, :],
"load_q": self.load_q[:max_step, :],
"prod_p": self.prod_p[:max_step, :],
"prod_v": self.prod_v[:max_step, :],
},
)
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore"
) # silence the UserWarning: Class FromNPY doesn't handle different input folder. "tell_id" method has no impact.
# warnings.warn("Class {} doesn't handle different input folder. \"tell_id\" method has no impact."
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=1)
assert res[0][3] == 10 # number of time step selected
env.close()
def test_change_chronics(self):
"""test i can change the chronics"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 18, # excluded
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
self.env_ref.reset()
load_p = 1.0 * self.env_ref.chronics_handler.real_data.data.load_p
load_q = 1.0 * self.env_ref.chronics_handler.real_data.data.load_q
prod_p = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_p
prod_v = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_v
env.chronics_handler.real_data.change_chronics(load_p, load_q, prod_p, prod_v)
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
env.reset()
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
env.close()
def test_with_env_copy(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
},
)
env_cpy = env.copy()
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
for ts in range(10):
obs_cpy, *_ = env_cpy.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs_cpy.gen_p[:-1]
), f"error at iteration {ts}"
self.env_ref.reset()
load_p = 1.0 * self.env_ref.chronics_handler.real_data.data.load_p
load_q = 1.0 * self.env_ref.chronics_handler.real_data.data.load_q
prod_p = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_p
prod_v = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_v
env.chronics_handler.real_data.change_chronics(load_p, load_q, prod_p, prod_v)
env.reset()
env_cpy.reset()
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
for ts in range(10):
obs_cpy, *_ = env_cpy.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs_cpy.gen_p[:-1]
), f"error at iteration {ts}"
env.close()
def test_forecast(self):
load_p_f = 1.0 * self.env_ref.chronics_handler.real_data.data.load_p_forecast
load_q_f = 1.0 * self.env_ref.chronics_handler.real_data.data.load_q_forecast
prod_p_f = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_p_forecast
prod_v_f = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_v_forecast
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
"load_p_forecast": load_p_f,
"load_q_forecast": load_q_f,
"prod_p_forecast": prod_p_f,
"prod_v_forecast": prod_v_f,
},
)
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
sim_obs, *_ = obs.simulate(env.action_space())
assert np.all(
prod_p_f[1 + ts, :-1] == sim_obs.gen_p[:-1]
), f"error at iteration {ts}"
assert (
sim_obs.minute_of_hour == (obs.minute_of_hour + 5) % 60
), f"error at iteration {ts}"
env.close()
def test_change_forecast(self):
load_p_f = 1.0 * self.env_ref.chronics_handler.real_data.data.load_p_forecast
load_q_f = 1.0 * self.env_ref.chronics_handler.real_data.data.load_q_forecast
prod_p_f = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_p_forecast
prod_v_f = 1.0 * self.env_ref.chronics_handler.real_data.data.prod_v_forecast
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
self.env_name,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": self.load_p,
"load_q": self.load_q,
"prod_p": self.prod_p,
"prod_v": self.prod_v,
"load_p_forecast": load_p_f,
"load_q_forecast": load_q_f,
"prod_p_forecast": prod_p_f,
"prod_v_forecast": prod_v_f,
},
)
env.chronics_handler.real_data.change_forecasts(
self.load_p, self.load_q, self.prod_p, self.prod_v
) # should not affect anything
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
sim_obs, *_ = obs.simulate(env.action_space())
assert np.all(
prod_p_f[1 + ts, :-1] == sim_obs.gen_p[:-1]
), f"error at iteration {ts}"
assert (
sim_obs.minute_of_hour == (obs.minute_of_hour + 5) % 60
), f"error at iteration {ts}"
env.reset() # now forecast should be modified
for ts in range(10):
obs, *_ = env.step(env.action_space())
assert np.all(
self.prod_p[1 + ts, :-1] == obs.gen_p[:-1]
), f"error at iteration {ts}"
sim_obs, *_ = obs.simulate(env.action_space())
assert np.all(obs.gen_p == sim_obs.gen_p), f"error at iteration {ts}"
assert (
sim_obs.minute_of_hour == (obs.minute_of_hour + 5) % 60
), f"error at iteration {ts}"
env.close()
class TestNPYChronicsWithHazards(unittest.TestCase):
"""
This class tests the possibility in grid2op to limit the number of call to "obs.simulate"
"""
def test_maintenance_ok(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
env_path = os.path.join(PATH_DATA_TEST, "env_14_test_maintenance")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_ref = grid2op.make(env_path, test=True, param=param)
env_ref.chronics_handler.real_data.data.maintenance_starting_hour = 1
env_ref.chronics_handler.real_data.data.maintenance_ending_hour = 2
env_ref.seed(0) # 1 -> 108
env_ref.reset()
load_p = 1.0 * env_ref.chronics_handler.real_data.data.load_p
load_q = 1.0 * env_ref.chronics_handler.real_data.data.load_q
prod_p = 1.0 * env_ref.chronics_handler.real_data.data.prod_p
prod_v = 1.0 * env_ref.chronics_handler.real_data.data.prod_v
load_p_f = 1.0 * env_ref.chronics_handler.real_data.data.load_p_forecast
load_q_f = 1.0 * env_ref.chronics_handler.real_data.data.load_q_forecast
prod_p_f = 1.0 * env_ref.chronics_handler.real_data.data.prod_p_forecast
prod_v_f = 1.0 * env_ref.chronics_handler.real_data.data.prod_v_forecast
maintenance = copy.deepcopy(env_ref.chronics_handler.real_data.data.maintenance)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
env_path,
chronics_class=FromNPY,
test=True,
data_feeding_kwargs={
"i_start": 0,
"i_end": 10, # excluded
"load_p": load_p,
"load_q": load_q,
"prod_p": prod_p,
"prod_v": prod_v,
"load_p_forecast": load_p_f,
"load_q_forecast": load_q_f,
"prod_p_forecast": prod_p_f,
"prod_v_forecast": prod_v_f,
"maintenance": maintenance,
},
param=param,
)
obs = env.reset()
obs_ref = env_ref.reset()
for ts in range(8):
obs, *_ = env.step(env.action_space())
obs_ref, *_ = env_ref.step(env.action_space())
assert np.all(
obs.time_before_cooldown_line == obs_ref.time_before_cooldown_line
), f"error at step {ts}"
sim_obs, *_ = obs.simulate(env.action_space())
sim_obs_ref, *_ = obs_ref.simulate(env.action_space())
assert np.all(
sim_obs.time_before_cooldown_line
== sim_obs_ref.time_before_cooldown_line
), f"error at step {ts}"
# TODO test obs.max_step
# test hazards
if __name__ == "__main__":
unittest.main()
| 20,039 | 39.484848 | 126 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_copy_env_close.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import gc
import sys
import warnings
import unittest
# see https://code.activestate.com/recipes/577504/
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
import grid2op
from grid2op.Exceptions import EnvError
from grid2op.Backend import Backend
from pandapower.auxiliary import pandapowerNet
class TestDanglingRef(unittest.TestCase):
def _clean_envs(self):
for obj_ in gc.get_objects():
if (
isinstance(obj_, grid2op.Environment.BaseEnv)
or isinstance(obj_, grid2op.Environment.BaseMultiProcessEnvironment)
or isinstance(obj_, grid2op.Environment.MultiMixEnvironment)
or isinstance(obj_, grid2op.Observation.BaseObservation)
):
del obj_
def setUp(self) -> None:
# make sure that there is no "dangling" reference to any environment
current_len = len(gc.get_objects()) + 1
while len(gc.get_objects()) != current_len:
self._clean_envs()
current_len = len(gc.get_objects())
gc.collect()
gc.collect()
def test_dangling_reference(self):
nb_env_init = len(
[o for o in gc.get_objects() if isinstance(o, grid2op.Environment.BaseEnv)]
)
nb_backend_init = len([o for o in gc.get_objects() if isinstance(o, Backend)])
nb_ppnet_init = len(
[o for o in gc.get_objects() if isinstance(o, pandapowerNet)]
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_case14_sandbox", test=True)
nb_env_before = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_before = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
nb_ppnet_before = (
len([o for o in gc.get_objects() if isinstance(o, pandapowerNet)])
- nb_ppnet_init
)
assert (
nb_env_before == 2
), f"there should be 2 environments, but we found {nb_env_before}"
assert (
nb_backend_before == 2
), f"there should be 2 backends, but we found {nb_backend_before}"
assert (
nb_ppnet_before == 4
), f"there should be 4 pp networks, but we found {nb_ppnet_before}"
# there are 4 pp nets because PandaPowerBackend keeps a copy of the initial grid for faster reset
# and it's copied for both the env backend and the obs_env backend
# make a copy
env_cpy = env.copy()
nb_env_after = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_after = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
nb_ppnet_after = (
len([o for o in gc.get_objects() if isinstance(o, pandapowerNet)])
- nb_ppnet_init
)
assert (
nb_env_after == 4
), f"there should be 4 environments after copy, but we found {nb_env_after}"
assert (
nb_backend_after == 4
), f"there should be 4 backend after copy, but we found {nb_backend_after}"
assert (
nb_ppnet_after == 8
), f"there should be 8 pp networks after copy, but we found {nb_ppnet_after}"
# reset the copied environment
obs_cpy = env_cpy.reset()
nb_env_after_reset = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_after_reset = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
assert (
nb_env_after_reset == 4
), f"there should be 4 environments after reset, but we found {nb_env_after_reset}"
assert (
nb_backend_after_reset == 4
), f"there should be 4 backends after reset, but we found {nb_backend_after_reset}"
# call step (on the copied env)
obs_cpy, reward, done, info = env_cpy.step(env_cpy.action_space())
nb_env_after_step = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_after_step = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
assert (
nb_env_after_step == 4
), f"there should be 4 environments after step, but we found {nb_env_after_step}"
assert (
nb_backend_after_step == 4
), f"there should be 4 backends after step, but we found {nb_backend_after_step}"
# call steps on init env
obs, reward, done, info = env.step(env_cpy.action_space())
nb_env_after_step = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_after_step = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
assert (
nb_env_after_step == 4
), f"there should be 4 environments after step, but we found {nb_env_after_step}"
assert (
nb_backend_after_step == 4
), f"there should be 4 backends after step, but we found {nb_backend_after_step}"
# now i close the initial environment, and check that everything is working as expected
env.close()
del env
gc.collect()
nb_env_after_close = (
len(
[
o
for o in gc.get_objects()
if isinstance(o, grid2op.Environment.BaseEnv)
]
)
- nb_env_init
)
nb_backend_after_close = (
len([o for o in gc.get_objects() if isinstance(o, Backend)])
- nb_backend_init
)
nb_ppnet_after_close = (
len([o for o in gc.get_objects() if isinstance(o, pandapowerNet)])
- nb_ppnet_init
)
assert (
nb_env_after_close == 3
), f"there should be 3 environments after close, but we found {nb_env_after_close}"
# the "obs_env" of the observation cannot be collected, as it's used on the observation...
assert (
nb_backend_after_close == 2
), f"there should be 2 backends after close, but we found {nb_backend_after_close}"
assert (
nb_ppnet_after_close == 4
), f"there should be 4 pp networks after close, but we found {nb_ppnet_after_close}"
# but the "grid" of the "obs_env" is definitely cleaned up
# now check i can properly do step, reset and simulate
obs_cpy, reward, done, info = env_cpy.step(env_cpy.action_space())
_ = obs_cpy.simulate(env_cpy.action_space())
obs_cpy = env_cpy.reset()
# finally I checked that I cannot use simulate on the closed environment
with self.assertRaises(EnvError):
_ = obs.simulate(env_cpy.action_space())
if __name__ == "__main__":
unittest.main()
| 8,410 | 34.791489 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_decompose_as_unary_actions.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import pdb
import time
import unittest
import warnings
import grid2op
from grid2op.Parameters import Parameters
from grid2op.dtypes import dt_float
from grid2op.Action import PlayableAction, CompleteAction
import warnings
# TODO check when there is also redispatching
class TestDecompUnary(unittest.TestCase):
"""test the env part of the storage functionality"""
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
self.env = grid2op.make(
"educ_case14_storage",
test=True,
action_class=PlayableAction,
)
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_change_bus(self):
act = self.env.action_space({"change_bus": {"loads_id": [0, 1],
"generators_id": [0]}})
res = act.decompose_as_unary_actions()
assert len(res) == 1
assert "change_bus" in res
assert len(res["change_bus"]) == 2
assert res["change_bus"][0]._change_bus_vect[act.load_pos_topo_vect[0]]
assert res["change_bus"][0]._change_bus_vect[act.gen_pos_topo_vect[0]]
assert not res["change_bus"][0]._change_bus_vect[act.load_pos_topo_vect[1]]
assert not res["change_bus"][1]._change_bus_vect[act.load_pos_topo_vect[0]]
assert not res["change_bus"][1]._change_bus_vect[act.gen_pos_topo_vect[0]]
assert res["change_bus"][1]._change_bus_vect[act.load_pos_topo_vect[1]]
res = act.decompose_as_unary_actions(group_topo=True)
assert len(res) == 1
assert "change_bus" in res
assert len(res["change_bus"]) == 1
assert res["change_bus"][0]._change_bus_vect[act.load_pos_topo_vect[0]]
assert res["change_bus"][0]._change_bus_vect[act.gen_pos_topo_vect[0]]
assert res["change_bus"][0]._change_bus_vect[act.load_pos_topo_vect[1]]
def test_set_bus(self):
act = self.env.action_space({"set_bus": {"loads_id": [(0, 2), (1, 2)],
"generators_id": [(0, 2)]}})
res = act.decompose_as_unary_actions()
assert len(res) == 1
assert "set_bus" in res
assert len(res["set_bus"]) == 2
assert res["set_bus"][0]._set_topo_vect[act.load_pos_topo_vect[0]] == 2
assert res["set_bus"][0]._set_topo_vect[act.gen_pos_topo_vect[0]] == 2
assert res["set_bus"][0]._set_topo_vect[act.load_pos_topo_vect[1]] == 0
assert res["set_bus"][1]._set_topo_vect[act.load_pos_topo_vect[0]] == 0
assert res["set_bus"][1]._set_topo_vect[act.gen_pos_topo_vect[0]] == 0
assert res["set_bus"][1]._set_topo_vect[act.load_pos_topo_vect[1]] == 2
res = act.decompose_as_unary_actions(group_topo=True)
assert len(res) == 1
assert "set_bus" in res
assert len(res["set_bus"]) == 1
assert res["set_bus"][0]._set_topo_vect[act.load_pos_topo_vect[0]] == 2
assert res["set_bus"][0]._set_topo_vect[act.gen_pos_topo_vect[0]] == 2
assert res["set_bus"][0]._set_topo_vect[act.load_pos_topo_vect[1]] == 2
def test_set_ls(self):
act = self.env.action_space({"set_line_status": [(0, -1), (1, -1)]})
res = act.decompose_as_unary_actions()
assert len(res) == 1
assert "set_line_status" in res
assert len(res["set_line_status"]) == 2
assert res["set_line_status"][0]._set_line_status[0] == -1
assert not res["set_line_status"][0]._set_line_status[1] == -1
assert not res["set_line_status"][1]._set_line_status[0] == -1
assert res["set_line_status"][1]._set_line_status[1] == -1
res = act.decompose_as_unary_actions(group_line_status=True)
assert len(res) == 1
assert "set_line_status" in res
assert len(res["set_line_status"]) == 1
assert res["set_line_status"][0]._set_line_status[0] == -1
assert res["set_line_status"][0]._set_line_status[1] == -1
def test_change_ls(self):
act = self.env.action_space({"change_line_status": [0, 1]})
res = act.decompose_as_unary_actions()
assert len(res) == 1
assert "change_line_status" in res
assert len(res["change_line_status"]) == 2
assert res["change_line_status"][0]._switch_line_status[0]
assert not res["change_line_status"][0]._switch_line_status[1]
assert not res["change_line_status"][1]._switch_line_status[0]
assert res["change_line_status"][1]._switch_line_status[1]
res = act.decompose_as_unary_actions(group_line_status=True)
assert len(res) == 1
assert "change_line_status" in res
assert len(res["change_line_status"]) == 1
assert res["change_line_status"][0]._switch_line_status[0]
assert res["change_line_status"][0]._switch_line_status[1]
def test_redispatch(self):
act = self.env.action_space({"redispatch": [(0, +1.), (1, -1.)]})
res = act.decompose_as_unary_actions(group_redispatch=False)
assert len(res) == 1
assert "redispatch" in res
assert len(res["redispatch"]) == 2
assert res["redispatch"][0]._redispatch[0] == 1.
assert res["redispatch"][0]._redispatch[1] == 0.
assert res["redispatch"][1]._redispatch[0] == 0.
assert res["redispatch"][1]._redispatch[1] == -1.
res = act.decompose_as_unary_actions(group_redispatch=True)
assert len(res) == 1
assert "redispatch" in res
assert len(res["redispatch"]) == 1
assert res["redispatch"][0]._redispatch[0] == 1.
assert res["redispatch"][0]._redispatch[1] == -1.
def test_storage(self):
act = self.env.action_space({"set_storage": [(0, +1.), (1, -1.)]})
res = act.decompose_as_unary_actions(group_storage=False)
assert len(res) == 1
assert "set_storage" in res
assert len(res["set_storage"]) == 2
assert res["set_storage"][0]._storage_power[0] == 1.
assert res["set_storage"][0]._storage_power[1] == 0.
assert res["set_storage"][1]._storage_power[0] == 0.
assert res["set_storage"][1]._storage_power[1] == -1.
res = act.decompose_as_unary_actions(group_storage=True)
assert len(res) == 1
assert "set_storage" in res
assert len(res["set_storage"]) == 1
assert res["set_storage"][0]._storage_power[0] == 1.
assert res["set_storage"][0]._storage_power[1] == -1.
def test_curtail(self):
act = self.env.action_space({"curtail": [(4, 0.8), (5, 0.7)]})
res = act.decompose_as_unary_actions(group_curtail=False)
assert len(res) == 1
assert "curtail" in res
assert len(res["curtail"]) == 2
assert res["curtail"][0]._curtail[4] == dt_float(0.8)
assert res["curtail"][0]._curtail[5] == -1.0
assert res["curtail"][1]._curtail[4] == -1.0
assert res["curtail"][1]._curtail[5] == dt_float(0.7)
res = act.decompose_as_unary_actions(group_curtail=True)
assert len(res) == 1
assert "curtail" in res
assert len(res["curtail"]) == 1
assert res["curtail"][0]._curtail[4] == dt_float(0.8)
assert res["curtail"][0]._curtail[5] == dt_float(0.7)
def test_all(self):
act = self.env.action_space({"curtail": [(4, 0.8), (5, 0.7)],
"set_storage": [(0, +1.), (1, -1.)],
"redispatch": [(0, +1.), (1, -1.)],
"change_line_status": [2, 3],
"set_line_status": [(0, -1), (1, -1)],
"set_bus": {"loads_id": [(0, 2), (1, 2)],
"generators_id": [(0, 2)]},
"change_bus": {"loads_id": [2, 3],
"generators_id": [1]}
})
res = act.decompose_as_unary_actions()
assert len(res) == 7
assert "curtail" in res
assert "curtail" in res
assert "redispatch" in res
assert "change_line_status" in res
assert "set_line_status" in res
assert "set_bus" in res
assert "change_bus" in res
tmp = self.env.action_space()
for k, v in res.items():
for a in v:
tmp += a
assert tmp == act
if __name__ == "__main__":
unittest.main()
| 9,282 | 44.063107 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_defaultgym_compat.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
from _aux_test_gym_compat import (AuxilliaryForTest,
_AuxTestGymCompatModule,
_AuxTestBoxGymObsSpace,
_AuxTestBoxGymActSpace,
_AuxTestMultiDiscreteGymActSpace,
_AuxTestDiscreteGymActSpace,
_AuxTestAllGymActSpaceWithAlarm,
_AuxTestGOObsInRange)
import unittest
class TestGymCompatModule(_AuxTestGymCompatModule, AuxilliaryForTest, unittest.TestCase):
pass
class TestBoxGymObsSpace(_AuxTestBoxGymObsSpace, AuxilliaryForTest, unittest.TestCase):
pass
class TestBoxGymActSpace(_AuxTestBoxGymActSpace, AuxilliaryForTest, unittest.TestCase):
pass
class TestMultiDiscreteGymActSpace(_AuxTestMultiDiscreteGymActSpace, AuxilliaryForTest, unittest.TestCase):
pass
class TestDiscreteGymActSpace(_AuxTestDiscreteGymActSpace, AuxilliaryForTest, unittest.TestCase):
pass
class TestAllGymActSpaceWithAlarm(_AuxTestAllGymActSpaceWithAlarm, AuxilliaryForTest, unittest.TestCase):
pass
class TestGOObsInRange(_AuxTestGOObsInRange, AuxilliaryForTest, unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
| 1,738 | 38.522727 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_diff_backend.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import grid2op
from grid2op.Agent import BaseAgent
from grid2op.Backend import PandaPowerBackend
from grid2op.Runner import Runner
import unittest
import warnings
import numpy as np
import pdb
class ModifPPBackend(PandaPowerBackend):
pass
class RememberRX(BaseAgent):
def act(self, observation, reward, done=False):
self._x = 1.0 * observation._obs_env.backend._grid.line["x_ohm_per_km"]
self._r = 1.0 * observation._obs_env.backend._grid.line["r_ohm_per_km"]
self._detailed_infos_for_cascading_failures = observation._obs_env.backend.detailed_infos_for_cascading_failures
self._lightsim2grid = observation._obs_env.backend._lightsim2grid
self._max_iter = observation._obs_env.backend._max_iter
self._bk = observation._obs_env.backend
return self.action_space()
def __copy__(self):
# prevent copy
raise copy.Error
class Case14DiffGridTester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.env = grid2op.make("l2rpn_case14_sandbox_diff_grid", test=True)
self.env.seed(0)
self.env.set_id(0)
def test_backend_different(self):
assert self.env.backend._grid is not self.env.observation_space._backend_obs
x_orig = self.env.backend._grid.line["x_ohm_per_km"]
x_modif = self.env.observation_space._backend_obs._grid.line["x_ohm_per_km"]
assert np.all(x_orig != x_modif)
r_orig = self.env.backend._grid.line["r_ohm_per_km"]
r_modif = self.env.observation_space._backend_obs._grid.line["r_ohm_per_km"]
assert np.all(r_orig != r_modif)
def test_simulate(self):
obs_init = self.env.reset()
loadp_next = [22.1, 89. , 45.9, 6.9, 12.3, 28.4, 8.8, 3.4, 5.5, 12.9, 15.2]
loadq_next = [15.5, 62.1, 31.2, 4.9, 8.4, 19.8, 6.1, 2.4, 3.8, 8.9, 10.6]
genp_next = [73.3 , 72.6 , 36.6 , 0. , 0. , 71.5158]
act = self.env.action_space()
# set the observation to the right values (for the forecast)
obs_init._forecasted_inj[1][1]["injection"]["load_p"] = np.array(loadp_next).astype(np.float32)
obs_init._forecasted_inj[1][1]["injection"]["load_q"] = np.array(loadq_next).astype(np.float32)
obs_init._forecasted_inj[1][1]["injection"]["prod_p"] = np.array(genp_next).astype(np.float32)
if 1 in obs_init._forecasted_grid_act:
del obs_init._forecasted_grid_act[1]
sim_obs, sim_r, simd, sim_i = obs_init.simulate(act)
obs, reward, done, info = self.env.step(act)
# inputs are the same
assert np.all(sim_obs.load_p == obs.load_p)
assert np.all(sim_obs.load_q == obs.load_q)
assert np.all(sim_obs.gen_p[:-1] == obs.gen_p[:-1]) # all equals except the slack
# and now check the outputs of the backend are different
assert sim_obs.gen_p[-1] != obs.gen_p[-1] # slack different
assert np.all(sim_obs.p_or != obs.p_or)
assert np.all(sim_obs.q_or != obs.q_or)
assert np.all(sim_obs.a_or != obs.a_or)
def test_simulator(self):
obs = self.env.reset()
sim = obs.get_simulator()
assert self.env.backend._grid is not sim.backend
x_orig = self.env.backend._grid.line["x_ohm_per_km"]
x_modif = sim.backend._grid.line["x_ohm_per_km"]
assert np.all(x_orig != x_modif)
r_orig = self.env.backend._grid.line["r_ohm_per_km"]
r_modif = sim.backend._grid.line["r_ohm_per_km"]
assert np.all(r_orig != r_modif)
def test_forecasted_env(self):
obs = self.env.reset()
act = self.env.action_space()
for_env = obs.get_forecast_env()
assert self.env.backend._grid is not for_env.backend
x_orig = self.env.backend._grid.line["x_ohm_per_km"]
x_modif = for_env.backend._grid.line["x_ohm_per_km"]
assert np.all(x_orig != x_modif)
r_orig = self.env.backend._grid.line["r_ohm_per_km"]
r_modif = for_env.backend._grid.line["r_ohm_per_km"]
assert np.all(r_orig != r_modif)
sim_obs, sim_r, simd, sim_i = obs.simulate(act)
for_obs, for_r, for_d, for_i = for_env.step(act)
assert np.all(sim_obs.a_or == for_obs.a_or)
def test_thermal_limit(self):
obs = self.env.reset()
sim = obs.get_simulator()
for_env = obs.get_forecast_env()
assert np.all(sim.backend.get_thermal_limit() == self.env.get_thermal_limit())
assert np.all(for_env.get_thermal_limit() == self.env.get_thermal_limit())
assert np.all(obs._obs_env.get_thermal_limit() == self.env.get_thermal_limit())
new_th_lim = 2.0 * self.env.get_thermal_limit()
self.env.set_thermal_limit(new_th_lim)
obs = self.env.reset()
sim = obs.get_simulator()
for_env = obs.get_forecast_env()
assert np.all(sim.backend.get_thermal_limit() == new_th_lim)
assert np.all(for_env.get_thermal_limit() == new_th_lim)
assert np.all(obs._obs_env.get_thermal_limit() == new_th_lim)
def test_runner(self):
agent = RememberRX(self.env.action_space)
runner = Runner(**self.env.get_params_for_runner(), agentInstance=agent, agentClass=None)
_ = runner.run(nb_episode=1, max_iter=1)
obs = self.env.reset()
assert hasattr(agent, "_r")
assert np.all(agent._r == obs._obs_env.backend._grid.line["r_ohm_per_km"])
assert np.all(agent._r != self.env.backend._grid.line["r_ohm_per_km"])
assert hasattr(agent, "_x")
assert np.all(agent._x == obs._obs_env.backend._grid.line["x_ohm_per_km"])
assert np.all(agent._x != self.env.backend._grid.line["x_ohm_per_km"])
class Case14DiffGridCopyTester(Case14DiffGridTester):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.aux_env = grid2op.make("l2rpn_case14_sandbox_diff_grid", test=True)
self.env = self.aux_env.copy()
self.env.seed(0)
self.env.set_id(0)
class DiffGridMakeTester(unittest.TestCase):
def _aux_check_bk_kwargs(self, bk):
assert bk._lightsim2grid
assert bk._max_iter == 15
def _aux_check_different_stuff(self, env, fun_bk):
obs = env.reset()
fun_bk(obs._obs_env.backend)
# copy
env_cpy = env.copy()
obs_cpy = env_cpy.reset()
fun_bk(obs_cpy._obs_env.backend)
# runner
agent = RememberRX(env.action_space)
runner = Runner(**env.get_params_for_runner(), agentInstance=agent, agentClass=None)
_ = runner.run(nb_episode=1, max_iter=1)
fun_bk(agent)
# forecasted_env
for_env = obs.get_forecast_env()
fun_bk(for_env.backend)
# simulator
sim = obs.get_simulator()
fun_bk(sim.backend)
def test_bk_kwargs(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
env = grid2op.make("l2rpn_case14_sandbox_diff_grid", test=True,
observation_backend_kwargs={"max_iter": 15,
"lightsim2grid": True})
self._aux_check_different_stuff(env, self._aux_check_bk_kwargs)
def _aux_bk_class(self, bk):
if isinstance(bk, PandaPowerBackend):
# subtlety: it can be called with an agent for the test of runner...
assert isinstance(bk, ModifPPBackend)
else:
# in this case "bk" is in fact an agent...
assert isinstance(bk._bk, ModifPPBackend)
def test_bk_class(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
env = grid2op.make("l2rpn_case14_sandbox_diff_grid", test=True,
observation_backend_class=ModifPPBackend)
self._aux_check_different_stuff(env, self._aux_bk_class)
if __name__ == "__main__":
unittest.main()
| 8,991 | 42.230769 | 120 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_educpp_backend.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import copy
import pdb
import time
import warnings
import unittest
import grid2op
from grid2op.Backend.EducPandaPowerBackend import EducPandaPowerBackend
import pdb
class EducPPTester(unittest.TestCase):
"""mainly to test that a backend that do not support shunts_data can
be loaded properly.
"""
def test_make(self):
for env_name in grid2op.list_available_test_env():
if (env_name == "l2rpn_icaps_2021" or
env_name == "l2rpn_neurips_2020_track1" or
env_name == "l2rpn_wcci_2020" or
env_name == "l2rpn_wcci_2022_dev" or
env_name == "l2rpn_wcci_2022"
):
# does not work because of generators name
# in the redispatching data
# or name in the powerlines (when maintenance)
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(env_name,
test=True,
backend=EducPandaPowerBackend(),
_add_to_name="educppbk")
assert type(env).n_shunt is None, f"error for {env_name}"
assert not type(env).shunts_data_available, f"error for {env_name}"
env.close()
if __name__ == "__main__":
unittest.main()
| 1,903 | 37.857143 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_elements_graph.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
from grid2op.Action import PlayableAction
import networkx
import unittest
import warnings
import pdb
class TestElementsGraph14SandBox(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
self.env.seed(0)
self.env.set_id(0)
self.tol = 1e-5
def _aux_get_topo_action(self):
sub_id = 4
topo = (1, 2, 1, 2, 1)
return sub_id, topo
def _aux_test_kcl(self, graph):
for bus_id, node_id in enumerate(graph.graph["bus_nodes_id"]):
sum_p = 0.
sum_q = 0.
for ancestor in graph.predecessors(node_id):
this_edge = graph.edges[(ancestor, node_id)]
if "p" in this_edge:
sum_p += this_edge["p"]
if "q" in this_edge:
sum_q += this_edge["q"]
assert abs(sum_p) <= self.tol, f"error for node {node_id} representing bus {bus_id}: {abs(sum_p)} != 0."
assert abs(sum_q) <= self.tol, f"error for node {node_id} representing bus {bus_id}: {abs(sum_q)} != 0."
def _aux_test_bus_consistent(self, graph):
for bus_id, node_id in enumerate(graph.graph["bus_nodes_id"]):
if len(list(graph.predecessors(node_id))):
# if I have predecessor (so some elements are connected to me), I am connected
assert graph.nodes[node_id]["connected"], f"error for node {node_id} representing bus {bus_id}"
else:
assert not graph.nodes[node_id]["connected"], f"error for node {node_id} representing bus {bus_id}"
def _aux_test_basic_props(self, obs, graph):
# test loads
for l_id in range(obs.n_load):
node_el_id = graph.graph["load_nodes_id"][l_id]
assert graph.nodes[node_el_id]["id"] == l_id
if graph.nodes[node_el_id]["connected"]:
global_bus_id = type(obs).local_bus_to_global_int(obs.load_bus[l_id], obs.load_to_subid[l_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == l_id
# test gen
for g_id in range(obs.n_gen):
node_el_id = graph.graph["gen_nodes_id"][g_id]
assert graph.nodes[node_el_id]["id"] == g_id
if graph.nodes[node_el_id]["connected"]:
global_bus_id = type(obs).local_bus_to_global_int(obs.gen_bus[g_id], obs.gen_to_subid[g_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == g_id
# test line
for l_id in range(obs.n_line):
node_el_id = graph.graph["line_nodes_id"][l_id]
assert graph.nodes[node_el_id]["id"] == l_id
if graph.nodes[node_el_id]["connected"]:
# or side
global_bus_id = type(obs).local_bus_to_global_int(obs.line_or_bus[l_id], obs.line_or_to_subid[l_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == l_id
assert graph.edges[node_el_id, node_bus_id]["side"] == "or"
# ex side
global_bus_id = type(obs).local_bus_to_global_int(obs.line_ex_bus[l_id], obs.line_ex_to_subid[l_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == l_id
assert graph.edges[node_el_id, node_bus_id]["side"] == "ex"
# test storage
for s_id in range(obs.n_storage):
node_el_id = graph.graph["storage_nodes_id"][s_id]
assert graph.nodes[node_el_id]["id"] == s_id
if graph.nodes[node_el_id]["connected"]:
global_bus_id = type(obs).local_bus_to_global_int(obs.storage_bus[s_id], obs.storage_to_subid[s_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == s_id
# test shunts
for s_id in range(obs.n_shunt):
node_el_id = graph.graph["shunt_nodes_id"][s_id]
assert graph.nodes[node_el_id]["id"] == s_id
if graph.nodes[node_el_id]["connected"]:
global_bus_id = type(obs).local_bus_to_global_int(obs._shunt_bus[s_id], obs.shunt_to_subid[s_id])
node_bus_id = graph.graph["bus_nodes_id"][global_bus_id]
assert graph.edges[node_el_id, node_bus_id]["id"] == s_id
def test_can_make(self):
obs = self.env.reset()
complete_graph = obs.get_elements_graph()
cls = type(obs)
assert len(complete_graph.nodes) == cls.n_sub + 2*cls.n_sub + cls.n_load + cls.n_gen + cls.n_line + cls.n_storage + cls.n_shunt
self._aux_test_kcl(complete_graph)
self._aux_test_bus_consistent(complete_graph)
self._aux_test_basic_props(obs, complete_graph)
def test_disconnected_lines(self):
obs = self.env.reset()
l_id = 4
obs, reward, done, info = self.env.step(self.env.action_space({"set_line_status": [(l_id, -1)]}))
assert not done
with warnings.catch_warnings():
warnings.filterwarnings("error")
# an error in the construction of the edges
graph = obs.get_elements_graph()
lines_id = graph.graph['line_nodes_id']
assert not graph.nodes[lines_id[l_id]]["connected"]
neighbors = list(networkx.neighbors(graph, lines_id[4]))
assert not neighbors
self._aux_test_kcl(graph)
self._aux_test_bus_consistent(graph)
self._aux_test_basic_props(obs, graph)
def test_topo(self):
obs = self.env.reset()
sub_id, topo = self._aux_get_topo_action()
action = self.env.action_space({"set_bus": {"substations_id": [(sub_id, topo)]}})
obs, reward, done, info = self.env.step(action)
assert not done
with warnings.catch_warnings():
warnings.filterwarnings("error")
# an error in the construction of the edges
graph = obs.get_elements_graph()
# correct bus are connected
bus_ids = graph.graph["bus_nodes_id"]
assert graph.nodes[bus_ids[sub_id]]["connected"]
assert graph.nodes[bus_ids[sub_id + obs.n_sub]]["connected"]
# check some other things
self._aux_test_kcl(graph)
self._aux_test_bus_consistent(graph)
self._aux_test_basic_props(obs, graph)
def test_game_over(self):
obs = self.env.reset()
action = self.env.action_space({"set_bus": {"loads_id": [(0, -1)]}})
obs, reward, done, info = self.env.step(action)
assert done
with warnings.catch_warnings():
warnings.filterwarnings("error")
# an error in the construction of the edges
graph = obs.get_elements_graph()
# no edges
assert len(graph.edges) == 2 * self.env.n_sub # each node to its substation
# every element disconnected
for el in range(obs.n_sub, len(graph.nodes)):
assert not graph.nodes[el]["connected"], f"node {el} should be disconnected"
class TestElementsGraph14Storage(TestElementsGraph14SandBox):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.env = grid2op.make("educ_case14_storage", test=True, action_class=PlayableAction)
self.env.seed(0)
self.env.set_id(0)
self.tol = 1e-5
def _aux_get_topo_action(self):
sub_id = 4
topo = (1, 2, 1, 2, 1)
return sub_id, topo
class TestElementsGraph118(TestElementsGraph14SandBox):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.env = grid2op.make("l2rpn_wcci_2022", test=True)
self.env.seed(0)
self.env.set_id(0)
self.tol = 3e-5
def _aux_get_topo_action(self):
sub_id = 4
topo = (1, 2, 1, 2, 1)
return sub_id, topo
if __name__ == "__main__":
unittest.main()
| 9,118 | 44.368159 | 135 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_feature_issue_447.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
from grid2op.Runner import Runner
from grid2op.Chronics import MultifolderWithCache # highly recommended for training
import warnings
import unittest
from grid2op.Exceptions import ChronicsError
from grid2op.Runner import Runner
import pdb
class TestPreventWrongBehaviour(unittest.TestCase):
def setUp(self) -> None:
env_name = "l2rpn_case14_sandbox"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(env_name,
chronics_class=MultifolderWithCache,
test=True)
def tearDown(self) -> None:
self.env.close()
def test_can_make(self):
pass
def test_cannot_step(self):
with self.assertRaises(ChronicsError):
self.env.step(self.env.action_space())
def test_cannot_reset(self):
with self.assertRaises(ChronicsError):
obs = self.env.reset()
def test_can_reset(self):
self.env.chronics_handler.reset()
obs = self.env.reset()
self.env.step(self.env.action_space())
def test_can_reset(self):
self.env.chronics_handler.reset()
obs = self.env.reset()
def test_when_change_filter(self):
self.env.chronics_handler.set_filter(lambda x: True)
with self.assertRaises(ChronicsError):
obs = self.env.reset()
self.env.chronics_handler.reset()
obs = self.env.reset()
self.env.step(self.env.action_space())
def test_runner(self):
with self.assertRaises(ChronicsError):
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1,
nb_process=1,
max_iter=5
)
self.env.chronics_handler.real_data.reset()
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1,
nb_process=1,
max_iter=5
)
def test_copy(self):
# when the copied env is not init
env_cpy = self.env.copy()
with self.assertRaises(ChronicsError):
env_cpy.step(self.env.action_space())
with self.assertRaises(ChronicsError):
env_cpy.reset()
env_cpy.chronics_handler.reset()
obs = env_cpy.reset()
env_cpy.step(env_cpy.action_space())
env_cpy.close()
# if the copied env is properly init
self.env.chronics_handler.reset()
env_cpy2 = self.env.copy()
env_cpy2.chronics_handler.reset()
obs = env_cpy2.reset()
env_cpy2.step(env_cpy2.action_space())
def test_runner_max_iter(self):
# env_name = "l2rpn_case14_sandbox"
# self.env = grid2op.make(env_name,
# # chronics_class=MultifolderWithCache,
# test=True)
self.env.chronics_handler.real_data.reset()
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=1,
nb_process=1,
max_iter=5
)
assert res[0][3] == 5, f"Is {res[0][3]} should be 5"
assert res[0][4] == 5, f"Is {res[0][4]} should be 5"
res = runner.run(nb_episode=1,
nb_process=1
)
assert res[0][3] == 575, f"Is {res[0][3]} should be 575"
assert res[0][4] == 575, f"Is {res[0][4]} should be 575"
if __name__ == "__main__":
unittest.main()
| 4,209 | 35.293103 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_forecast_from_arrays.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
import numpy as np
import pdb
class TestForecastFromArrays(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_basic_behaviour(self):
obs = self.env.reset()
# test the max step
for nb_ts in [1, 3, 10, 30]:
load_p_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
load_q_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
gen_p_forecasted = np.tile(obs.gen_p, nb_ts).reshape(nb_ts, -1)
gen_v_forecasted = np.tile(obs.gen_v, nb_ts).reshape(nb_ts, -1)
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert sim_obs.max_step == nb_ts + 1
# test with some actions
sim_obs1, reward, done, info = forcast_env.step(self.env.action_space())
assert sim_obs1.max_step == nb_ts + 1
sim_obs2, reward, done, info = forcast_env.step(self.env.action_space())
assert sim_obs2.max_step == nb_ts + 1
sim_obs3, reward, done, info = forcast_env.step(self.env.action_space())
assert sim_obs3.max_step == nb_ts + 1
def test_missing_gen_v(self):
obs = self.env.reset()
nb_ts = 5
# test the max step
load_p_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
load_q_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
gen_p_forecasted = np.tile(obs.gen_p, nb_ts).reshape(nb_ts, -1)
gen_v_forecasted = None
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert (sim_obs.gen_v == obs.gen_v).all()
sim_obs1, reward, done, info = forcast_env.step(self.env.action_space())
def test_missing_gen_p(self):
obs = self.env.reset()
nb_ts = 5
# test the max step
load_p_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
load_q_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
gen_p_forecasted = None
gen_v_forecasted = np.tile(obs.gen_v, nb_ts).reshape(nb_ts, -1)
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert (sim_obs.gen_p == obs.gen_p).all()
sim_obs1, reward, done, info = forcast_env.step(self.env.action_space())
def test_missing_load_p(self):
obs = self.env.reset()
nb_ts = 5
# test the max step
load_p_forecasted = None
load_q_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
gen_p_forecasted = np.tile(obs.gen_p, nb_ts).reshape(nb_ts, -1)
gen_v_forecasted = np.tile(obs.gen_v, nb_ts).reshape(nb_ts, -1)
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert (sim_obs.load_p == obs.load_p).all()
sim_obs1, reward, done, info = forcast_env.step(self.env.action_space())
def test_missing_load_q(self):
obs = self.env.reset()
nb_ts = 5
# test the max step
load_p_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
load_q_forecasted = None
gen_p_forecasted = np.tile(obs.gen_p, nb_ts).reshape(nb_ts, -1)
gen_v_forecasted = np.tile(obs.gen_v, nb_ts).reshape(nb_ts, -1)
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert (sim_obs.load_q == obs.load_q).all()
sim_obs1, reward, done, info = forcast_env.step(self.env.action_space())
def test_all_missing(self):
obs = self.env.reset()
# test the max step
load_p_forecasted = None
load_q_forecasted = None
gen_p_forecasted = None
gen_v_forecasted = None
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted)
sim_obs = forcast_env.reset()
assert sim_obs.max_step == 1
def test_all_without_maintenance(self):
obs = self.env.reset()
nb_ts = 5
# test the max step
load_p_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
load_q_forecasted = np.tile(obs.load_p, nb_ts).reshape(nb_ts, -1)
gen_p_forecasted = np.tile(obs.gen_p, nb_ts).reshape(nb_ts, -1)
gen_v_forecasted = np.tile(obs.gen_v, nb_ts).reshape(nb_ts, -1)
forcast_env = obs.get_env_from_external_forecasts(load_p_forecasted,
load_q_forecasted,
gen_p_forecasted,
gen_v_forecasted,
with_maintenance=False)
sim_obs = forcast_env.reset()
assert sim_obs.max_step == nb_ts + 1
if __name__ == "__main__":
unittest.main()
| 7,292 | 44.298137 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_fromChronix2grid.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import os
import grid2op
import numpy as np
from grid2op.Chronics import FromChronix2grid
import unittest
import pkg_resources
from lightsim2grid import LightSimBackend
DEV_DATA_FOLDER = pkg_resources.resource_filename("grid2op", "data")
class TestFromChronix2Grid(unittest.TestCase):
def _aux_reset_env(self):
self.env.seed(self.seed_)
self.env.set_id(self.scen_nm)
return self.env.reset()
def setUp(self) -> None:
self.seed_ = 0
self.env_nm = "l2rpn_wcci_2022_dev"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(self.env_nm,
test=True,
backend=LightSimBackend(),
chronics_class=FromChronix2grid,
data_feeding_kwargs={"env_path": os.path.join(DEV_DATA_FOLDER, self.env_nm), # os.path.join(grid2op.get_current_local_dir(), self.env_nm),
"with_maintenance": True,
"max_iter": 10,
"with_loss": False
}
)
def test_ok(self):
"""test it can be created"""
assert self.env.chronics_handler.real_data._gen_p.shape == (12, 62)
assert np.all(np.isfinite(self.env.chronics_handler.real_data._gen_p))
def test_seed_setid(self):
"""test env.seed(...) and env.set_id(...)"""
id_ref = '2525122259@2050-02-28'
id_ref = '377638611@2050-02-28'
# test tell_id
sum_prod_ref = 42340.949878
sum_prod_ref = 41784.477161
self.env.seed(self.seed_)
self.env.reset()
id_ = self.env.chronics_handler.get_id()
assert id_ == id_ref, f"wrong id {id_} instead of {id_ref}"
assert abs(self.env.chronics_handler.real_data._gen_p.sum() - sum_prod_ref) <= 1e-4, f"{self.env.chronics_handler.real_data._gen_p.sum():.2f}"
self.env.reset()
# assert abs(self.env.chronics_handler.real_data._gen_p.sum() - 38160.833356999996) <= 1e-4
assert abs(self.env.chronics_handler.real_data._gen_p.sum() - 37662.206248999995) <= 1e-4, f"{self.env.chronics_handler.real_data._gen_p.sum():.2f}"
self.env.set_id(id_ref)
self.env.reset()
assert abs(self.env.chronics_handler.real_data._gen_p.sum() - sum_prod_ref) <= 1e-4, f"{self.env.chronics_handler.real_data._gen_p.sum():.2f}"
# test seed
self.env.seed(self.seed_)
self.env.reset()
assert abs(self.env.chronics_handler.real_data._gen_p.sum() - sum_prod_ref) <= 1e-4, f"{self.env.chronics_handler.real_data._gen_p.sum():.2f}"
def test_episode(self):
"""test that the episode can go until the end"""
self.env.seed(1)
obs = self.env.reset()
assert obs.current_step == 0
assert obs.max_step == 10
for i in range(obs.max_step - 1):
obs, reward, done, info = self.env.step(self.env.action_space())
assert not done, f"episode should not be over at iteration {i}"
obs, reward, done, info = self.env.step(self.env.action_space())
assert obs.current_step == 10
assert obs.max_step == 10
assert done, "episode should have terminated"
obs = self.env.reset()
assert obs.max_step == 10
assert obs.current_step == 0
def test_maintenance(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(self.env_nm,
test=True,
# backend=LightSimBackend(),
chronics_class=FromChronix2grid,
data_feeding_kwargs={"env_path": os.path.join(DEV_DATA_FOLDER, self.env_nm),
"with_maintenance": True,
"max_iter": 2 * 288,
"with_loss": False
}
)
self.env.seed(0)
id_ref = '0@2050-08-08'
self.env.set_id(id_ref)
obs = self.env.reset()
assert np.all(obs.time_next_maintenance[[43, 126]] == [107, 395])
assert np.all(obs.time_next_maintenance[:43] == -1)
assert np.all(obs.time_next_maintenance[127:] == -1)
assert np.all(obs.time_next_maintenance[44:126] == -1)
assert self.env.chronics_handler.real_data.maintenance is not None
assert self.env.chronics_handler.real_data.maintenance.sum() == 192
assert self.env.chronics_handler.real_data.maintenance_time is not None
assert self.env.chronics_handler.real_data.maintenance_duration is not None
if __name__ == "__main__":
unittest.main() | 5,653 | 46.915254 | 175 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_generate_classes.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
from pathlib import Path
from grid2op.Environment import Environment, MultiMixEnvironment
from grid2op.tests.helper_path_test import *
import grid2op
import shutil
import pdb
class TestGenerateFile(unittest.TestCase):
def _aux_assert_exists_then_delete(self, env):
if isinstance(env, MultiMixEnvironment):
for mix in env:
self._aux_assert_exists_then_delete(mix)
elif isinstance(env, Environment):
path = Path(env.get_path_env()) / "_grid2op_classes"
assert path.exists()
shutil.rmtree(path, ignore_errors=True)
else:
raise RuntimeError("Unknown env type")
def list_env(self):
env_with_alert = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
return grid2op.list_available_test_env() + [env_with_alert]
def test_can_generate(self):
for env_nm in self.list_env():
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(env_nm, test=True)
env.generate_classes()
self._aux_assert_exists_then_delete(env)
env.close()
def test_can_load(self):
for env_nm in self.list_env():
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(env_nm, test=True, _add_to_name="_TestGenerateFile")
env.generate_classes()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
try:
env2 = grid2op.make(env_nm,
test=True,
experimental_read_from_local_dir=True)
env2.close()
except RuntimeError as exc_:
raise RuntimeError(f"Error for {env_nm}") from exc_
self._aux_assert_exists_then_delete(env)
env.close()
if __name__ == "__main__":
unittest.main()
| 2,593 | 37.147059 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_global_to_local_dc.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import grid2op
import pandapower as pp
import numpy as np
import pdb
class TestBugShuntDC(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
def tearDown(self) -> None:
self.env.close()
def test_shunt_dc(self):
self.env.backend.runpf(is_dc=True)
p_subs, q_subs, p_bus, q_bus, diff_v_bus = self.env.backend.check_kirchoff()
assert np.abs(p_subs).max() <=1e-5
assert np.abs(p_bus).max() <=1e-5
# below it does not pass due to https://github.com/e2nIEE/pandapower/issues/1996
# assert np.abs(diff_v_bus).max() <=1e-5
def test_shunt_dc_alone(self):
self.env.backend._grid.shunt["bus"][0] += 14
self.env.backend._grid.bus["in_service"][self.env.backend._grid.shunt["bus"][0]] = True
self.env.backend.runpf(is_dc=True)
p_subs, q_subs, p_bus, q_bus, diff_v_bus = self.env.backend.check_kirchoff()
assert np.abs(p_subs).max() <=1e-5
assert np.abs(p_bus).max() <=1e-5
# below it does not pass due to https://github.com/e2nIEE/pandapower/issues/1996
# assert np.abs(diff_v_bus).max() <=1e-5
if __name__ == "__main__":
unittest.main()
| 1,857 | 38.531915 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_gym_env_renderer.py | # Copyright (c) 2019-2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
import grid2op
from grid2op.gym_compat import GymEnv
import numpy as np
class TestGymEnvRenderer(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
self.env.seed(0)
self.env.set_id(0)
def test_render_signature(self):
genv = GymEnv(self.env)
_ = genv.reset()
array = genv.render()
assert array.shape == (720, 1280, 3)
with self.assertRaises(TypeError):
array = genv.render(render_mode="rgb_array")
if __name__ == "__main__":
unittest.main() | 1,319 | 34.675676 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_gymnasium_compat.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
from _aux_test_gym_compat import (GYMNASIUM_AVAILABLE,
_AuxTestGymCompatModule,
_AuxTestBoxGymObsSpace,
_AuxTestBoxGymActSpace,
_AuxTestMultiDiscreteGymActSpace,
_AuxTestDiscreteGymActSpace,
_AuxTestAllGymActSpaceWithAlarm,
_AuxTestGOObsInRange)
import unittest
class AuxilliaryForTestGymnasium:
def _aux_GymEnv_cls(self):
from grid2op.gym_compat import GymnasiumEnv
return GymnasiumEnv
def _aux_ContinuousToDiscreteConverter_cls(self):
from grid2op.gym_compat import ContinuousToDiscreteConverterGymnasium
return ContinuousToDiscreteConverterGymnasium
def _aux_ScalerAttrConverter_cls(self):
from grid2op.gym_compat import ScalerAttrConverterGymnasium
return ScalerAttrConverterGymnasium
def _aux_MultiToTupleConverter_cls(self):
from grid2op.gym_compat import MultiToTupleConverterGymnasium
return MultiToTupleConverterGymnasium
def _aux_BoxGymObsSpace_cls(self):
from grid2op.gym_compat import BoxGymnasiumObsSpace
return BoxGymnasiumObsSpace
def _aux_BoxGymActSpace_cls(self):
from grid2op.gym_compat import BoxGymnasiumActSpace
return BoxGymnasiumActSpace
def _aux_MultiDiscreteActSpace_cls(self):
from grid2op.gym_compat import MultiDiscreteActSpaceGymnasium
return MultiDiscreteActSpaceGymnasium
def _aux_DiscreteActSpace_cls(self):
from grid2op.gym_compat import DiscreteActSpaceGymnasium
return DiscreteActSpaceGymnasium
def _aux_Box_cls(self):
if GYMNASIUM_AVAILABLE:
from gymnasium.spaces import Box
return Box
def _aux_MultiDiscrete_cls(self):
if GYMNASIUM_AVAILABLE:
from gymnasium.spaces import MultiDiscrete
return MultiDiscrete
def _aux_Discrete_cls(self):
if GYMNASIUM_AVAILABLE:
from gymnasium.spaces import Discrete
return Discrete
def _aux_Tuple_cls(self):
if GYMNASIUM_AVAILABLE:
from gymnasium.spaces import Tuple
return Tuple
def _aux_Dict_cls(self):
if GYMNASIUM_AVAILABLE:
from gymnasium.spaces import Dict
return Dict
def _skip_if_no_gym(self):
if not GYMNASIUM_AVAILABLE:
self.skipTest("Gym is not available")
class TestGymnasiumCompatModule(_AuxTestGymCompatModule, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestBoxGymnasiumObsSpace(_AuxTestBoxGymObsSpace, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestBoxGymnasiumActSpace(_AuxTestBoxGymActSpace, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestMultiDiscreteGymnasiumActSpace(_AuxTestMultiDiscreteGymActSpace, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestDiscreteGymnasiumActSpace(_AuxTestDiscreteGymActSpace, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestAllGymnasiumActSpaceWithAlarm(_AuxTestAllGymActSpaceWithAlarm, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
class TestGOObsInRangeGymnasium(_AuxTestGOObsInRange, AuxilliaryForTestGymnasium, unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
| 3,982 | 36.224299 | 122 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_highres_sim_counter.py | # Copyright (c) 2023, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import grid2op
from grid2op.Chronics import FromHandlers
from grid2op.Chronics.handlers import PerfectForecastHandler, CSVHandler, DoNothingHandler
from grid2op.Observation import BaseObservation
from grid2op.Runner import Runner
from grid2op.Agent import BaseAgent
import pdb
import warnings
class OneSimulateAgent(BaseAgent):
def act(self, observation: BaseObservation, reward: float, done: bool = False):
observation.simulate(self.action_space())
if observation.prod_p.sum() <= 250:
# just to make different number of "simulate" per episode
# this never triggers for ep id 0 but do it 3 times for ep_id 1 (provided that max_ts is 5)
observation.simulate(self.action_space())
return super().act(observation, reward, done)
class HighreSimTester(unittest.TestCase):
def _make_env(self):
forecasts_horizons = [5, 10, 15, 20, 25, 30]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# this needs to be tested with pandapower backend
env = grid2op.make("l2rpn_case14_sandbox",
test=True,
data_feeding_kwargs={"gridvalueClass": FromHandlers,
"gen_p_handler": CSVHandler("prod_p"),
"load_p_handler": CSVHandler("load_p"),
"gen_v_handler": DoNothingHandler("prod_v"),
"load_q_handler": CSVHandler("load_q"),
"h_forecast": forecasts_horizons,
"gen_p_for_handler": PerfectForecastHandler("prod_p_forecasted"),
"load_p_for_handler": PerfectForecastHandler("load_p_forecasted"),
"load_q_for_handler": PerfectForecastHandler("load_q_forecasted"),
})
env.seed(0)
env.set_id(0)
return env
def setUp(self) -> None:
self.env = self._make_env()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_simple_setting(self):
"""test when no copy, runner, chain to simulate etc., just simulate and reset"""
obs0 = self.env.reset()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
obs0.simulate(self.env.action_space())
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
obs0.simulate(self.env.action_space())
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
obs0.simulate(self.env.action_space(), 5)
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
obs1 = self.env.reset()
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
obs1.simulate(self.env.action_space())
assert self.env.nb_highres_called == 4, f"{self.env.nb_highres_called} vs 4"
obs0.simulate(self.env.action_space(), 3)
assert self.env.nb_highres_called == 5, f"{self.env.nb_highres_called} vs 5"
obs2, *_ = self.env.step(self.env.action_space())
assert self.env.nb_highres_called == 5, f"{self.env.nb_highres_called} vs 5"
obs2.simulate(self.env.action_space(), 3)
assert self.env.nb_highres_called == 6, f"{self.env.nb_highres_called} vs 6"
def test_forecast_env(self):
"""test the correct behaviour even when there is a forecast env"""
obs0 = self.env.reset()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
for_env = obs0.get_forecast_env()
for_env.step(self.env.action_space())
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
for_env.step(self.env.action_space())
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
for_env.step(self.env.action_space())
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
for_env1 = obs0.get_forecast_env()
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
obs1, *_ = self.env.step(self.env.action_space())
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
for_env1.step(self.env.action_space())
assert self.env.nb_highres_called == 4, f"{self.env.nb_highres_called} vs 4"
for_env.step(self.env.action_space())
assert self.env.nb_highres_called == 5, f"{self.env.nb_highres_called} vs 5"
obs1.simulate(self.env.action_space(), 3)
assert self.env.nb_highres_called == 6, f"{self.env.nb_highres_called} vs 6"
for_env2 = for_env1.copy()
assert self.env.nb_highres_called == 6, f"{self.env.nb_highres_called} vs 6"
for_env2.step(self.env.action_space())
assert self.env.nb_highres_called == 7, f"{self.env.nb_highres_called} vs 7"
def test_env_copied(self):
"""test the nb_highres is kept when env is copied"""
obs0 = self.env.reset()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
env_cpy = self.env.copy()
obs1 = env_cpy.reset()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
assert env_cpy.nb_highres_called == 0, f"{env_cpy.nb_highres_called} vs 0"
obs1.simulate(self.env.action_space(), 3)
assert env_cpy.nb_highres_called == 1, f"{env_cpy.nb_highres_called} vs 1"
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
obs0.simulate(self.env.action_space())
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
assert env_cpy.nb_highres_called == 2, f"{env_cpy.nb_highres_called} vs 2"
for_env = obs0.get_forecast_env()
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
assert env_cpy.nb_highres_called == 2, f"{env_cpy.nb_highres_called} vs 2"
for_env.step(self.env.action_space())
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
assert env_cpy.nb_highres_called == 3, f"{env_cpy.nb_highres_called} vs 3"
for_env1 = obs1.get_forecast_env()
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
assert env_cpy.nb_highres_called == 3, f"{env_cpy.nb_highres_called} vs 3"
for_env1.step(self.env.action_space())
assert self.env.nb_highres_called == 4, f"{self.env.nb_highres_called} vs 4"
assert env_cpy.nb_highres_called == 4, f"{env_cpy.nb_highres_called} vs 4"
def test_chain_simulate(self):
"""test it counts properly when the calls to obs.simulate are chained"""
obs0 = self.env.reset()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
obs1, *_ = obs0.simulate(self.env.action_space())
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
obs2, *_ = obs1.simulate(self.env.action_space())
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
obs3, *_ = obs2.simulate(self.env.action_space())
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
def test_simulator(self):
"""test it works when I use simulator"""
obs0 = self.env.reset()
sim0 = obs0.get_simulator()
assert self.env.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
simulator_stressed0 = sim0.predict(act=self.env.action_space(), do_copy=False)
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
simulator_stressed1 = simulator_stressed0.predict(act=self.env.action_space())
assert self.env.nb_highres_called == 2, f"{self.env.nb_highres_called} vs 2"
simulator_stressed2 = simulator_stressed1.predict(act=self.env.action_space())
assert self.env.nb_highres_called == 3, f"{self.env.nb_highres_called} vs 3"
def test_noshare_between_makes(self):
"""test that if call twice the 'make' function then the highres_sim_counter is not shared"""
env1 = self._make_env()
obs0 = self.env.reset()
obs0.simulate(self.env.action_space())
assert self.env.nb_highres_called == 1, f"{self.env.nb_highres_called} vs 1"
assert env1.nb_highres_called == 0, f"{self.env.nb_highres_called} vs 0"
def test_runner_seq(self):
"""test it behaves normally with the runner"""
runner = Runner(**self.env.get_params_for_runner())
# normal processing, with do nothing
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = runner.run(nb_episode=1, max_iter=5, add_nb_highres_sim=True)
assert len(res) == 1
assert len(res[0]) == 6
assert res[0][5] == 0
# normal processing with an agent that uses simulate
runner = Runner(**self.env.get_params_for_runner(), agentClass=OneSimulateAgent)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = runner.run(nb_episode=1, max_iter=5, add_nb_highres_sim=True)
assert len(res) == 1
assert len(res[0]) == 6
assert res[0][5] == 5
# normal processing with an agent that uses forecasted_env
class OneForEnvAgent(BaseAgent):
def act(self, observation: BaseObservation, reward: float, done: bool = False):
for_env = observation.get_forecast_env()
for_env.step(self.action_space())
return super().act(observation, reward, done)
runner = Runner(**self.env.get_params_for_runner(), agentClass=OneForEnvAgent)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = runner.run(nb_episode=1, max_iter=5, add_nb_highres_sim=True)
assert len(res) == 1
assert len(res[0]) == 6
assert res[0][5] == 5
# 2 episodes sequential
runner = Runner(**self.env.get_params_for_runner(), agentClass=OneSimulateAgent)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = runner.run(nb_episode=2, max_iter=5, add_nb_highres_sim=True)
assert len(res) == 2
assert len(res[0]) == 6
assert res[0][5] == 5
assert len(res[1]) == 6
assert res[1][5] == 8
def test_runner_par(self):
# 2 episodes parrallel
runner = Runner(**self.env.get_params_for_runner(), agentClass=OneSimulateAgent)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
res = runner.run(nb_episode=2, max_iter=5, add_nb_highres_sim=True, nb_process=2)
assert len(res) == 2
assert len(res[0]) == 6
assert res[0][5] == 5
assert len(res[1]) == 6
assert res[1][5] == 8
if __name__ == '__main__':
unittest.main()
| 11,891 | 48.55 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_126.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
from grid2op.Agent import DeltaRedispatchRandomAgent
from grid2op.Runner import Runner
from grid2op import make
from grid2op.Episode import EpisodeData
import tempfile
import pdb
class Issue126Tester(unittest.TestCase):
def test_issue_126(self):
# run redispatch agent on one scenario for 100 timesteps
dataset = "rte_case14_realistic"
nb_episode = 1
nb_timesteps = 100
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = make(dataset, test=True)
agent = DeltaRedispatchRandomAgent(env.action_space)
runner = Runner(
**env.get_params_for_runner(), agentClass=None, agentInstance=agent
)
with tempfile.TemporaryDirectory() as tmpdirname:
res = runner.run(
nb_episode=nb_episode,
path_save=tmpdirname,
nb_process=1,
max_iter=nb_timesteps,
env_seeds=[0],
agent_seeds=[0],
pbar=False,
)
episode_data = EpisodeData.from_disk(tmpdirname, res[0][1])
assert (
len(episode_data.actions.objects) - nb_timesteps == 0
), "wrong number of actions {}".format(len(episode_data.actions.objects))
assert (
len(episode_data.actions) - nb_timesteps == 0
), "wrong number of actions {}".format(len(episode_data.actions))
assert (
len(episode_data.observations.objects) - (nb_timesteps + 1) == 0
), "wrong number of observations: {}".format(
len(episode_data.observations.objects)
)
assert (
len(episode_data.observations) - (nb_timesteps + 1) == 0
), "wrong number of observations {}".format(len(episode_data.observations))
if __name__ == "__main__":
unittest.main()
| 2,364 | 36.539683 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_131.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
#!/usr/bin/env python3
import grid2op
import unittest
import numpy as np
import warnings
class Issue131Tester(unittest.TestCase):
def test_issue_131(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("rte_case14_realistic", test=True)
# Get forecast after a simulate works
obs = env.reset()
obs.simulate(env.action_space({}))
prod_p_fa, prod_v_fa, load_p_fa, load_q_fa = obs.get_forecasted_inj()
shapes_a = (prod_p_fa.shape, prod_v_fa.shape, load_p_fa.shape, load_q_fa.shape)
# Get forecast before any simulate doesnt work
env.set_id(1)
obs = env.reset()
prod_p_fb, prod_v_fb, load_p_fb, load_q_fb = obs.get_forecasted_inj()
shapes_b = (prod_p_fb.shape, prod_v_fb.shape, load_p_fb.shape, load_q_fb.shape)
assert shapes_a == shapes_b
assert np.all(prod_p_fa == prod_p_fb)
assert np.all(prod_v_fa == prod_v_fb)
assert np.all(load_p_fa == load_p_fb)
assert np.all(load_q_fa == load_q_fb)
if __name__ == "__main__":
unittest.main()
| 1,600 | 35.386364 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_140.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import numpy as np
#!/usr/bin/env python3
import grid2op
import unittest
import numpy as np
import warnings
from grid2op.Parameters import Parameters
import pdb
class Issue140Tester(unittest.TestCase):
def test_issue_140(self):
# TODO change that
envs = grid2op.list_available_local_env()
env_name = "l2rpn_neurips_2020_track1_small"
if env_name not in envs:
# the environment is not downloaded, I skip this test
self.skipTest("{} is not downloaded".format(env_name))
param = Parameters()
# test was originally designed with these values
param.init_from_dict(
{
"NO_OVERFLOW_DISCONNECTION": False,
"NB_TIMESTEP_OVERFLOW_ALLOWED": 3,
"NB_TIMESTEP_COOLDOWN_SUB": 3,
"NB_TIMESTEP_COOLDOWN_LINE": 3,
"HARD_OVERFLOW_THRESHOLD": 200.0,
"NB_TIMESTEP_RECONNECTION": 12,
"IGNORE_MIN_UP_DOWN_TIME": True,
"ALLOW_DISPATCH_GEN_SWITCH_OFF": True,
"ENV_DC": False,
"FORECAST_DC": False,
"MAX_SUB_CHANGED": 1,
"MAX_LINE_STATUS_CHANGED": 1,
}
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
env_name,
param=param,
)
ts_per_chronics = 2016
seed = 725
np.random.seed(seed)
env.seed(seed)
env.set_id(np.random.randint(100000))
_ = env.reset()
max_day = (env.chronics_handler.max_timestep() - 2016) // 288
start_timestep = np.random.randint(max_day) * 288 - 1 # start at 00:00
if start_timestep > 0:
env.fast_forward_chronics(start_timestep)
obs = env.get_obs()
done = False
steps = 0
do_nothing = env.action_space({})
for i in range(119):
obs, reward, done, info = env.step(do_nothing)
assert not done
act0 = env.action_space(
{
"set_bus": {
"lines_ex_id": [(41, 2), (42, 1), (57, 1)],
"lines_or_id": [(44, 2)],
"generators_id": [(16, 2)],
}
}
)
act1 = env.action_space(
{
"set_bus": {
"lines_ex_id": [
(17, 2),
(18, 1),
(19, 1),
(20, 2),
(21, 2),
],
"lines_or_id": [
(22, 2),
(23, 2),
(27, 1),
(28, 1),
(48, 2),
(49, 2),
(54, 1),
],
"generators_id": [(5, 2), (6, 1), (7, 1), (8, 1)],
"loads_id": [(17, 2)],
}
}
)
act2 = env.action_space(
{
"set_bus": {
"lines_ex_id": [(36, 2), (37, 2), (38, 2), (39, 2)],
"lines_or_id": [(40, 1), (41, 1)],
"generators_id": [(14, 1)],
"loads_id": [(27, 1)],
}
}
)
obs, reward, done, info = env.step(act0)
obs, reward, done, info = env.step(act1)
assert not done
simulate_obs0, simulate_reward0, simulate_done0, simulate_info0 = obs.simulate(
do_nothing
)
simulate_obs1, simulate_reward1, simulate_done1, simulate_info1 = obs.simulate(
act2
)
obs, reward, done, info = env.step(act2)
assert simulate_done0 is False
assert simulate_done1 is True
assert done is True
assert info["is_illegal"] == False
assert simulate_info1["is_illegal"] == False
if __name__ == "__main__":
unittest.main()
| 4,568 | 30.510345 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_146.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import numpy as np
#!/usr/bin/env python3
import grid2op
import unittest
from grid2op.Reward import BaseReward
import warnings
from grid2op.dtypes import dt_float
import pdb
class TestReward(BaseReward):
def __init__(self):
super().__init__()
self.reward_min = dt_float(100.0) # Note difference from below
self.reward_max = dt_float(0.0)
def __call__(self, action, env, has_error, is_done, is_illegal, is_ambiguous):
if has_error:
return dt_float(-10.0)
else:
return dt_float(1.0)
class Issue146Tester(unittest.TestCase):
def test_issue_146(self):
"""
the reward helper skipped the call to the reward when "has_error" was True
This was not really an issue... but rather a enhancement, but still
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"rte_case14_realistic", test=True, reward_class=TestReward
)
action = env.action_space(
{"set_bus": {"substations_id": [(1, [2, 2, 1, 1, 2, -1])]}}
)
obs, reward, done, info = env.step(action)
assert done
assert reward == dt_float(
-10.0
), 'reward should be -10.0 and not "reward_min" (ie 100.)'
if __name__ == "__main__":
unittest.main()
| 1,860 | 29.508197 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_147.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import numpy as np
#!/usr/bin/env python3
import grid2op
import unittest
from grid2op.Parameters import Parameters
import warnings
import pdb
class Issue147Tester(unittest.TestCase):
def test_issue_147(self):
"""
The rule "Prevent Reconnection" was not properly applied, this was because the
observation of the _ObsEnv was not properly updated.
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_SUB = 3
param.NB_TIMESTEP_COOLDOWN_LINE = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("rte_case14_realistic", test=True, param=param)
action = env.action_space(
{"set_bus": {"substations_id": [(1, [2, 2, 1, 1, 2, 2])]}}
)
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(0, -1)]})
)
env.step(env.action_space())
sim_o, sim_r, sim_d, info = obs.simulate(env.action_space())
env.step(env.action_space())
sim_o, sim_r, sim_d, info = obs.simulate(env.action_space())
env.step(env.action_space())
sim_o, sim_r, sim_d, info = obs.simulate(env.action_space())
obs, reward, done, info = env.step(
env.action_space({"set_line_status": [(0, 1)]})
)
assert obs.time_before_cooldown_line[0] == 3
sim_o, sim_r, sim_d, sim_info = obs.simulate(action)
assert not sim_d
assert not sim_info[
"is_illegal"
] # this was declared as "illegal" due to an issue with updating
# the line status in the observation of the _ObsEnv
obs, reward, done, info = obs.simulate(action)
assert not info["is_illegal"]
if __name__ == "__main__":
unittest.main()
| 2,330 | 34.861538 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_148.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import numpy as np
import os
from grid2op.tests.helper_path_test import PATH_CHRONICS
import grid2op
import unittest
from grid2op.Parameters import Parameters
import warnings
import pdb
class Issue148Tester(unittest.TestCase):
def test_issue_148(self):
"""
The rule "Prevent Reconnection" was not properly applied, this was because the
observation of the _ObsEnv was not properly updated.
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_SUB = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
os.path.join(PATH_CHRONICS, "env_14_test_maintenance"),
test=True,
param=param,
)
ID_MAINT = 11 # in maintenance at the second time step
obs = env.reset()
# check i can "simulate" properly if a maintenance happens next
sim_o, sim_r, sim_d, sim_i = obs.simulate(env.action_space())
assert not sim_d
assert (
sim_o.time_next_maintenance[ID_MAINT] == 0
) # the stuff have been properly updated
assert not sim_o.line_status[ID_MAINT]
oo_, rr_, dd_, ii_ = env.step(env.action_space())
assert not dd_
assert oo_.time_next_maintenance[ID_MAINT] == 0
assert not oo_.line_status[ID_MAINT]
# check once the maintenance is performed, it stays this way
sim_o, sim_r, sim_d, sim_i = oo_.simulate(env.action_space())
assert not sim_d
assert (
sim_o.time_next_maintenance[ID_MAINT] == 0
) # the stuff have been properly updated
assert not sim_o.line_status[ID_MAINT]
oo_, rr_, dd_, ii_ = env.step(env.action_space())
assert not dd_
assert oo_.time_next_maintenance[ID_MAINT] == 0
assert not oo_.line_status[ID_MAINT]
# now test the cooldown
action = env.action_space(
{"set_bus": {"substations_id": [(1, [1, 1, 1, 1, 1, 1])]}}
)
oo_, rr_, dd_, ii_ = env.step(action)
assert oo_.time_before_cooldown_sub[1] == 3
oo_, rr_, dd_, ii_ = env.step(env.action_space())
oo_, rr_, dd_, ii_ = env.step(action)
assert oo_.time_before_cooldown_sub[1] == 1
assert ii_["is_illegal"]
# still illegal (cooldown of 1 now so 0 later)
ooo_, rr_, dd_, ii_ = oo_.simulate(action)
assert not dd_
assert ooo_.time_before_cooldown_sub[ID_MAINT] == 0
assert ii_["is_illegal"]
# we check that's illegal (cooldown is 1 now so 0 later)
ooo_, rr_, dd_, ii_ = env.step(action)
assert not dd_
assert ooo_.time_before_cooldown_sub[ID_MAINT] == 0
assert ii_["is_illegal"]
# we check that's legal next step
oooo_, rr_, dd_, ii_ = env.step(action)
assert not dd_
assert oooo_.time_before_cooldown_sub[ID_MAINT] == 0
assert not ii_["is_illegal"]
# but now it's legal to simulate ("next step" - see just above- it's legal)
oooo_, rr_, dd_, ii_ = ooo_.simulate(action)
assert not dd_
assert oooo_.time_before_cooldown_sub[ID_MAINT] == 0
assert not ii_["is_illegal"]
if __name__ == "__main__":
unittest.main()
| 3,841 | 36.666667 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_151.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import numpy as np
import os
from grid2op.tests.helper_path_test import PATH_CHRONICS
import grid2op
import unittest
from grid2op.Parameters import Parameters
import warnings
import pdb
class Issue151Tester(unittest.TestCase):
def test_issue_151(self):
"""
The rule "Prevent Reconnection" was not properly applied, this was because the
observation of the _ObsEnv was not properly updated.
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_SUB = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("rte_case14_realistic", test=True)
do_nothing = env.action_space({})
obs, reward, done, info = env.step(do_nothing)
obs.line_status = (
obs.line_status / 1
) # do some weird things to the vector "line_status"
# the next line of cod
_, _, _, _ = env.step(do_nothing)
if __name__ == "__main__":
unittest.main()
| 1,524 | 32.152174 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_153.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import numpy as np
import grid2op
import unittest
from grid2op.Parameters import Parameters
import warnings
class Issue153Tester(unittest.TestCase):
def test_issue_153(self):
"""
The rule "Prevent Reconnection" was not properly applied, this was because the
observation of the _ObsEnv was not properly updated.
"""
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
param.NB_TIMESTEP_COOLDOWN_SUB = 3
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(
"rte_case14_realistic", test=True, _add_to_name="test_issue_153"
)
env.gen_max_ramp_up[:] = env.gen_pmax
env.gen_max_ramp_down[:] = env.gen_pmax
env.action_space.gen_max_ramp_up[:] = env.gen_pmax
env.action_space.gen_max_ramp_down[:] = env.gen_pmax
env.action_space.actionClass.gen_max_ramp_up[:] = env.gen_pmax
env.action_space.actionClass.gen_max_ramp_down[:] = env.gen_pmax
obs = env.reset()
# prod 1 do [74.8, 77. , 75.1, 76.4, 76.3, 75. , 74.5, 74.2, 73. , 72.6]
for i in range(3):
obs, reward, done, info = env.step(env.action_space())
# now generator 1 decreases: 76.3, 75. , 74.5, 74.2, 73. , 72.6
action = env.action_space({"redispatch": [(0, -76)]})
obs, reward, done, info = env.step(action)
# should be at 0.3
assert np.abs(obs.prod_p[0] - 0.3) <= 1e-2, "wrong data"
# I do an illegal action
obs, reward, done, info = env.step(action)
# and the redispatching was negative (this was the issue)
assert obs.prod_p[0] >= -env._tol_poly, "generator should be positive"
if __name__ == "__main__":
unittest.main()
| 2,266 | 38.77193 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_164.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import grid2op
from grid2op.Reward import BaseReward
from grid2op.dtypes import dt_float
from grid2op.Exceptions import DivergingPowerFlow
class Test164_Reward(BaseReward):
def __init__(self):
super().__init__()
self.reward_min = dt_float(-1.0)
self.reward_max = dt_float(1.0)
def __call__(self, action, env, has_error, is_done, is_illegal, is_ambiguous):
if has_error:
return self.reward_min
elif is_done:
return self.reward_max
return dt_float(0.0)
class Issue164Tester(unittest.TestCase):
def test_issue_164(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make('rte_case14_realistic', reward_class=Test164_Reward, test=True)
max_timestep = env.chronics_handler.max_timestep()
obs = env.reset()
env.fast_forward_chronics(max_timestep - 3)
obs = env.get_obs()
while True:
obs, reward, done, info = env.step(env.action_space())
assert not info["exception"], "there should not be any exception"
if done:
assert reward == 1.0, "wrong reward computed when episode is over"
break
if __name__ == "__main__":
unittest.main()
| 1,794 | 31.053571 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_185.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import os
from grid2op.tests.helper_path_test import *
import grid2op
from grid2op.gym_compat import (
GymEnv,
BoxGymActSpace,
BoxGymObsSpace,
MultiDiscreteActSpace,
DiscreteActSpace,
)
import pdb
ENV_WITH_ALARM_NAME = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
class Issue185Tester(unittest.TestCase):
"""
this test ensure that every "test" environment can be converted to gym
this test suit goes beyond the simple error raised in the github issue.
"""
def get_list_env(self):
res = grid2op.list_available_test_env()
res.append(ENV_WITH_ALARM_NAME)
return res
def test_issue_185(self):
for env_name in self.get_list_env():
if env_name == "blank":
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True) as env:
try:
gym_env = GymEnv(env)
# gym_env.seed(0)
# gym_env.observation_space.seed(0)
# gym_env.action_space.seed(0)
gym_env.action_space.seed(0)
obs_gym, *_ = gym_env.reset(seed=0) # reset and seed
assert (
obs_gym["a_ex"].shape[0] == env.n_line
), f"error for {env_name}"
# if obs_gym not in gym_env.observation_space:
for k in gym_env.observation_space.spaces.keys():
assert (
obs_gym[k] in gym_env.observation_space[k]
), f"error for {env_name}, for key={k}"
finally:
gym_env.close()
def test_issue_185_act_box_space(self):
for env_name in self.get_list_env():
if env_name == "blank":
continue
if env_name == "rte_case5_example":
# no action to perform for this env ! (no redispatch, curtail, storage)
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True) as env:
try:
gym_env = GymEnv(env)
try:
gym_env.action_space = BoxGymActSpace(gym_env.init_env.action_space)
except Exception as exc_:
raise AssertionError(f"Error for {env_name}: {exc_}") from exc_
# gym_env.seed(0)
# gym_env.observation_space.seed(0)
# gym_env.action_space.seed(0)
gym_env.action_space.seed(0)
obs_gym, *_ = gym_env.reset(seed=0) # reset and seed
assert isinstance(obs_gym, dict), "probably a wrong gym version"
# "was_alert_used_after_attack"
# "was_alarm_used_after_game_over"
for key in gym_env.observation_space.keys():
assert key in obs_gym, f"error for {env_name} for {key}"
assert obs_gym[key] in gym_env.observation_space[key], f"error for {env_name} for {key}"
act = gym_env.action_space.sample()
assert act in gym_env.action_space, f"error for {env_name}"
obs, reward, done, truncated, info = gym_env.step(act)
assert isinstance(obs_gym, dict)
for key in gym_env.observation_space.keys():
assert key in obs_gym, f"error for {env_name} for {key}"
assert obs_gym[key] in gym_env.observation_space[key], f"error for {env_name} for {key}"
finally:
gym_env.close()
def test_issue_185_obs_box_space(self):
for env_name in self.get_list_env():
if env_name == "blank":
continue
# if env_name != "l2rpn_neurips_2020_track1":
# continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True) as env:
try:
gym_env = GymEnv(env)
gym_env.observation_space.close()
gym_env.observation_space = BoxGymObsSpace(
gym_env.init_env.observation_space
)
# gym_env.seed(0)
# gym_env.observation_space.seed(0)
# gym_env.action_space.seed(0)
gym_env.action_space.seed(0)
obs_gym, *_ = gym_env.reset(seed=0) # reset and seed
if obs_gym not in gym_env.observation_space:
raise AssertionError(f"error for {env_name}: \n{gym_env.observation_space.low}\n{obs_gym}\n{gym_env.observation_space.high}")
act = gym_env.action_space.sample()
assert act in gym_env.action_space, f"error for {env_name}"
obs, reward, done, truncated, info = gym_env.step(act)
if obs not in gym_env.observation_space:
raise AssertionError(f"error for {env_name}: \n{gym_env.observation_space.low}\n{obs}\n{gym_env.observation_space.high}")
finally:
gym_env.close()
def test_issue_185_act_multidiscrete_space(self):
for env_name in self.get_list_env():
if env_name == "blank":
continue
elif env_name == "l2rpn_neurips_2020_track1":
# takes too much time
continue
elif env_name == "l2rpn_neurips_2020_track2":
# takes too much time
continue
elif env_name == "rte_case118_example":
# takes too much time
continue
elif env_name == ENV_WITH_ALARM_NAME:
# takes too much time
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True) as env:
try:
gym_env = GymEnv(env)
gym_env.action_space = MultiDiscreteActSpace(
gym_env.init_env.action_space
)
# gym_env.seed(0)
# gym_env.observation_space.seed(0)
gym_env.action_space.seed(0)
obs_gym, *_ = gym_env.reset(seed=0)
assert obs_gym in gym_env.observation_space, f"error for {env_name}"
act = gym_env.action_space.sample()
assert act in gym_env.action_space, f"error for {env_name}"
obs, reward, done, truncated, info = gym_env.step(act)
assert obs in gym_env.observation_space, f"error for {env_name}"
finally:
gym_env.close()
def test_issue_185_act_discrete_space(self):
for env_name in self.get_list_env():
if env_name == "blank":
continue
elif env_name == "l2rpn_neurips_2020_track1":
# takes too much time
continue
elif env_name == "l2rpn_neurips_2020_track2":
# takes too much time
continue
elif env_name == "rte_case118_example":
# takes too much time
continue
elif env_name == ENV_WITH_ALARM_NAME:
# takes too much time
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True) as env:
try:
gym_env = GymEnv(env)
gym_env.action_space = DiscreteActSpace(
gym_env.init_env.action_space
)
# gym_env.seed(0)
# gym_env.observation_space.seed(0)
# gym_env.action_space.seed(0)
gym_env.action_space.seed(0)
obs_gym, *_ = gym_env.reset(seed=0)
assert obs_gym in gym_env.observation_space, f"error for {env_name}"
act = gym_env.action_space.sample()
assert act in gym_env.action_space, f"error for {env_name}"
obs, reward, done, truncated, info = gym_env.step(act)
if obs not in gym_env.observation_space:
for k in obs:
if not obs[k] in gym_env.observation_space[k]:
raise RuntimeError(
f"Error for key {k} for env {env_name}"
)
finally:
gym_env.close()
if __name__ == "__main__":
unittest.main()
| 10,016 | 45.16129 | 153 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_187.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
import grid2op
from grid2op.dtypes import dt_float
from grid2op.Reward import RedispReward
from grid2op.Runner import Runner
class Issue187Tester(unittest.TestCase):
"""
this test ensure that every "test" environment can be converted to gym
this test suit goes beyond the simple error raised in the github issue.
"""
def setUp(self) -> None:
self.tol = 1e-5 # otherwise issues with converting to / from float32
def test_issue_187(self):
"""test the range of the reward class"""
for env_name in grid2op.list_available_test_env():
if env_name == "blank":
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(
env_name, test=True, reward_class=RedispReward
) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
assert (
reward <= env.reward_range[1]
), f"error for reward_max for {env_name}"
assert (
reward >= env.reward_range[0]
), f"error for reward_min for {env_name}"
def test_custom_reward(self):
"""test i can generate the reward and use it in the envs"""
reward_cls = RedispReward.generate_class_custom_params(
alpha_redisph=2,
min_load_ratio=0.15,
worst_losses_ratio=0.05,
min_reward=-10.0,
reward_illegal_ambiguous=0.0,
least_losses_ratio=0.015,
)
for env_name in grid2op.list_available_test_env():
if env_name == "blank":
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True, reward_class=reward_cls) as env:
obs = env.reset()
obs, reward, done, info = env.step(env.action_space())
# test that reward is in the correct range
assert (
reward <= env.reward_range[1]
), f"error reward > reward_max for {env_name}"
assert (
reward >= env.reward_range[0]
), f"error reward < reward_min for {env_name}"
# test the parameters are effectively changed
# what should be computed
_alpha_redisph = dt_float(2)
_min_load_ratio = dt_float(0.15)
_worst_losses_ratio = dt_float(0.05)
_min_reward = dt_float(-10.0)
_reward_illegal_ambiguous = dt_float(0.0)
_least_losses_ratio = dt_float(0.015)
worst_marginal_cost = np.max(env.gen_cost_per_MW)
worst_load = dt_float(np.sum(env.gen_pmax))
# it's not the worst, but definitely an upper bound
worst_losses = dt_float(_worst_losses_ratio) * worst_load
worst_redisp = _alpha_redisph * np.sum(
env.gen_pmax
) # not realistic, but an upper bound
max_regret = (worst_losses + worst_redisp) * worst_marginal_cost / 12.
reward_min = dt_float(_min_reward)
least_loads = dt_float(
worst_load * _min_load_ratio
) # half the capacity of the grid
least_losses = dt_float(
_least_losses_ratio * least_loads
) # 1.5% of losses
least_redisp = dt_float(0.0) # lower_bound is 0
base_marginal_cost = np.min(
env.gen_cost_per_MW[env.gen_cost_per_MW > 0.0]
)
min_regret = (least_losses + least_redisp) * base_marginal_cost / 12.
reward_max = dt_float((max_regret - min_regret) / least_loads)
assert (
abs(env.reward_range[1] - reward_max) <= self.tol
), f"wrong reward max computed for {env_name}: {env.reward_range[1]} vs {reward_max}"
assert (
abs(env.reward_range[0] - reward_min) <= self.tol
), f"wrong reward min computed for {env_name}: {env.reward_range[0]} vs {reward_min}"
def test_custom_reward_runner(self):
"""test i can generate the reward and use it in the envs"""
reward_cls = RedispReward.generate_class_custom_params(
alpha_redisph=2,
min_load_ratio=0.15,
worst_losses_ratio=0.05,
min_reward=-10.0,
reward_illegal_ambiguous=0.0,
least_losses_ratio=0.015,
)
env_name = "l2rpn_case14_sandbox"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
with grid2op.make(env_name, test=True, reward_class=reward_cls) as env:
obs = env.reset()
runner = Runner(**env.get_params_for_runner())
res = runner.run(nb_episode=2, nb_process=2)
if __name__ == "__main__":
unittest.main()
| 5,889 | 42.62963 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_196.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
import grid2op
from grid2op.gym_compat import GymEnv
from grid2op.gym_compat import ScalerAttrConverter
class Issue196Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_neurips_2020_track1", test=True)
env_gym = GymEnv(env)
ob_space = env_gym.observation_space
ob_space = ob_space.keep_only_attr(
["rho", "gen_p", "load_p", "topo_vect", "actual_dispatch"]
)
ob_space = ob_space.reencode_space(
"actual_dispatch",
ScalerAttrConverter(substract=0.0, divide=env.gen_pmax),
)
ob_space = ob_space.reencode_space(
"gen_p", ScalerAttrConverter(substract=0.0, divide=env.gen_pmax)
)
ob_space = ob_space.reencode_space(
"load_p", ScalerAttrConverter(substract=0.0, divide=-1.0)
)
env_gym.observation_space = ob_space
self.env_gym = env_gym
def test_issue_196_loadp(self):
assert np.all(
self.env_gym.observation_space["load_p"].low
<= self.env_gym.observation_space["load_p"].high
)
def test_issue_196_genp(self):
# not great test as it passes with the bug... but just in the case... cannot hurt
obs, *_ = self.env_gym.reset()
assert obs in self.env_gym.observation_space
| 2,008 | 37.634615 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_217.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.Chronics import ChangeNothing
from grid2op.tests.helper_path_test import *
class Issue217Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = os.path.join(PATH_DATA_TEST, "5bus_modif_grid")
self.env = grid2op.make(env_nm, test=True, chronics_class=ChangeNothing)
self.env.seed(0)
self.env.reset()
def test_env_working(self):
assert self.env.n_sub == 7
assert np.all(self.env.sub_info[[5, 6]] == 0)
| 1,075 | 37.428571 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_220.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import numpy as np
import grid2op
class Issue220Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
self.env.seed(0)
self.env.reset()
def test_flow_bus_matrix(self):
obs = self.env.reset()
res, _ = obs.flow_bus_matrix()
assert res.shape == (14, 14)
action = self.env.action_space()
action.change_line_status = [9]
# two powerlines will be disconnected: powerline 9 (action) and powerline 13 ("cascading failure")
new_obs, reward, done, info = self.env.step(action)
res, _ = new_obs.flow_bus_matrix()
assert res.shape == (14, 14)
| 1,289 | 36.941176 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_223.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.Chronics import ChangeNothing
from grid2op.tests.helper_path_test import *
try:
from grid2op.PlotGrid import PlotMatplot
CAN_PLOT = True
except ImportError as exc_:
CAN_PLOT = False
class Issue223Tester(unittest.TestCase):
def _skip_if_not_installed(self):
if not CAN_PLOT:
self.skipTest("matplotlib is not installed")
def reset_without_pp_futurewarnings(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
obs = self.env.reset()
return obs
def setUp(self) -> None:
if CAN_PLOT:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = os.path.join(PATH_DATA_TEST, "5bus_modif_grid")
self.env = grid2op.make(env_nm, test=True, chronics_class=ChangeNothing)
self.env.seed(0)
self.reset_without_pp_futurewarnings()
def test_env_working(self):
self._skip_if_not_installed()
with warnings.catch_warnings():
warnings.filterwarnings("error") # there should be no warning there
# in the issue, it crashes there
plot_helper = PlotMatplot(self.env.observation_space)
assert "sub_5" in plot_helper._grid_layout
assert "sub_6" in plot_helper._grid_layout
# now test i can plot an observation
fig = plot_helper.plot_obs(self.reset_without_pp_futurewarnings())
| 2,015 | 37.037736 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_224.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.Chronics import ChangeNothing
from grid2op.tests.helper_path_test import *
from grid2op.Runner import Runner
from grid2op.Parameters import Parameters
class Issue224Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
self.env = grid2op.make(env_nm, test=True, chronics_class=ChangeNothing)
self.env.seed(0)
self.env.reset()
def test_env_alarmtime_default(self):
"""test default values are correct"""
assert self.env.parameters.ALARM_WINDOW_SIZE == 12
assert self.env.parameters.ALARM_BEST_TIME == 12
runner = Runner(**self.env.get_params_for_runner())
env_runner = runner.init_env()
assert env_runner.parameters.ALARM_WINDOW_SIZE == 12
assert env_runner.parameters.ALARM_BEST_TIME == 12
def test_env_alarmtime_changed(self):
"""test everything is correct when something is modified"""
param = Parameters()
param.ALARM_WINDOW_SIZE = 99
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
env = grid2op.make(
env_nm, test=True, chronics_class=ChangeNothing, param=param
)
assert env.parameters.ALARM_WINDOW_SIZE == 99
assert env.parameters.ALARM_BEST_TIME == 12
runner = Runner(**env.get_params_for_runner())
env_runner = runner.init_env()
assert env_runner.parameters.ALARM_WINDOW_SIZE == 99
assert env_runner.parameters.ALARM_BEST_TIME == 12
param = Parameters()
param.ALARM_BEST_TIME = 42
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_neurips_2020_track1_with_alarm"
)
env = grid2op.make(
env_nm, test=True, chronics_class=ChangeNothing, param=param
)
assert env.parameters.ALARM_WINDOW_SIZE == 12
assert env.parameters.ALARM_BEST_TIME == 42
runner = Runner(**env.get_params_for_runner())
env_runner = runner.init_env()
assert env_runner.parameters.ALARM_WINDOW_SIZE == 12
assert env_runner.parameters.ALARM_BEST_TIME == 42
| 3,044 | 40.712329 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_235.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.Chronics import ChangeNothing
from grid2op.tests.helper_path_test import *
from grid2op.Observation import CompleteObservation
class Issue235TesterObs(CompleteObservation):
def __init__(self,
obs_env=None,
action_helper=None,
random_prng=None,
kwargs_env=None):
CompleteObservation.__init__(
self, obs_env, action_helper, random_prng=random_prng, kwargs_env=kwargs_env
)
self._is_updated = False
def update(self, env, with_forecast=True):
self._is_updated = True
super().update(env, with_forecast)
class Issue235Tester(unittest.TestCase):
"""
This bug was due to the environment that updated the observation even when it diverges.
In this test i checked that the `update` method of the observation is not called even when I simulate
an action that lead to divergence of the powerflow.
"""
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = "l2rpn_icaps_2021"
# from lightsim2grid import LightSimBackend
# backend=LightSimBackend(),
self.env = grid2op.make(
env_nm, test=True, observation_class=Issue235TesterObs
)
# now set the right observation class for the simulate action
hack_obs_cls = Issue235TesterObs.init_grid(type(self.env))
self.env._observation_space.obs_env.current_obs = hack_obs_cls()
self.env._observation_space.obs_env.current_obs_init = hack_obs_cls()
# now do regular gri2op stuff
self.env.seed(0)
self.env.reset()
def test_diverging_action(self):
final_dict = {
"generators_id": [(19, 1)],
"loads_id": [(30, 2)],
"lines_or_id": [(58, 1)],
"lines_ex_id": [(46, 1), (47, 2)],
}
action = self.env.action_space({"set_bus": final_dict})
obs = self.env.reset()
simobs, simr, simd, siminfo = obs.simulate(action, time_step=0)
assert simd
assert np.all(simobs.gen_p == 0.0)
assert not simobs._is_updated
| 2,702 | 36.541667 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_238.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.Chronics import ChangeNothing
from grid2op.tests.helper_path_test import *
from grid2op.Action import PowerlineSetAction
from grid2op.Opponent import WeightedRandomOpponent, BaseActionBudget
class Issue224Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = "l2rpn_case14_sandbox"
lines_attacked = ["6_7_18"]
rho_normalization = [1.0]
opponent_attack_cooldown = 2 # need to be at least 1
opponent_attack_duration = 12
opponent_budget_per_ts = 9999.0
opponent_init_budget = 9999.0
self.env = grid2op.make(
env_nm,
test=True,
# chronics_class=ChangeNothing,
opponent_attack_cooldown=opponent_attack_cooldown,
opponent_attack_duration=opponent_attack_duration,
opponent_budget_per_ts=opponent_budget_per_ts,
opponent_init_budget=opponent_init_budget,
opponent_action_class=PowerlineSetAction,
opponent_class=WeightedRandomOpponent,
opponent_budget_class=BaseActionBudget,
kwargs_opponent={
"lines_attacked": lines_attacked,
"rho_normalization": rho_normalization,
"attack_period": opponent_attack_cooldown,
},
)
self.env.seed(0)
self.env.reset()
def test_opponent(self):
obs = self.env.reset()
assert obs.line_status[18], "line 18 should be connected"
# TODO this test does not really test it...
# TODO but i would need an env with a connected powerline with exactly 0 flow on it !
# assert obs.rho[18] == 0., "line 18 should not have any flow"
res = self.env._opponent.attack(
obs, self.env.action_space(), self.env.action_space(), 100, False
)
assert len(res) == 2, "it should return something of length 2"
| 2,581 | 42.033333 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_245.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
from grid2op.tests.helper_path_test import *
from grid2op.Action import CompleteAction
class Issue245Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env_nm = "l2rpn_case14_sandbox"
self.env = grid2op.make(env_nm, test=True, action_class=CompleteAction)
self.env.seed(0)
self.env.reset()
def test_simulate(self):
# change the thermal limit to disconnect powerline 3, and only this one, after 3 steps
self.env.set_thermal_limit(
2.0
* np.array(
[
162.49806,
127.40141,
107.29365,
110.0 / 2.0,
107.90302,
48.58299,
135.80658,
434.52097,
252.74222,
649.2642,
56.013855,
183.57967,
324.4969,
79.42569,
319.6616,
100.69238,
46.787445,
73.96375,
895.7249,
563.3386,
],
dtype=dt_float,
)
)
# perform the 3 steps
obs = self.env.reset()
assert obs.line_status[3]
obs, *_ = self.env.step(self.env.action_space())
assert obs.line_status[3]
obs, *_ = self.env.step(self.env.action_space())
assert obs.line_status[3]
obs, *_ = self.env.step(self.env.action_space())
assert not obs.line_status[3]
# line 3 is now disconnected, i try to simulate an action that reconnects it (it should not work) !
act = self.env.action_space({"set_bus": {"lines_or_id": [(3, 1)]}})
*_, sim_info = obs.simulate(act)
assert (
len(sim_info["exception"]) > 0
), "there should be an exception because the action is illegal"
*_, info = self.env.step(act)
assert (
len(info["exception"]) > 0
), "there should be an exception because the action is illegal"
| 2,729 | 35.891892 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_274.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import grid2op
import unittest
import numpy as np
class Issue274Tester(unittest.TestCase):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_icaps_2021", test=True)
def test_same_opponent_state(self):
"""test that the opponent state is correctly copied"""
self.env.seed(3)
self.env.reset()
init_attack_times = 1 * self.env._opponent._attack_times
env_cpy = self.env.copy()
after_attack_times = 1 * self.env._opponent._attack_times
copy_attack_times = 1 * env_cpy._opponent._attack_times
assert np.all(init_attack_times == after_attack_times)
assert np.all(init_attack_times == copy_attack_times)
def test_same_opponent_space(self):
"""test that the opponent space state (in particular the current attack) is properly copied"""
self.env.seed(3)
self.env.reset()
import pdb
init_attack_times = 1 * self.env._opponent._attack_times
assert np.all(init_attack_times == [5, 105, 180])
for i in range(5):
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is None
obs, reward, done, info = self.env.step(self.env.action_space())
assert info["opponent_attack_line"] is not None
init_line_attacked = np.where(info["opponent_attack_line"])[0]
for i in range(2):
env_cpy = self.env.copy()
*_, info = self.env.step(self.env.action_space())
*_, info_cpy = env_cpy.step(self.env.action_space())
assert (
info["opponent_attack_line"] is not None
), f"no line attacked at iteration {i}"
assert (
info_cpy["opponent_attack_line"] is not None
), f"no line attacked at iteration {i} for the copy env"
line_attacked = np.where(info["opponent_attack_line"])[0]
cpy_line_attacked = np.where(info_cpy["opponent_attack_line"])[0]
assert (
init_line_attacked == line_attacked
), f"wrong line attack at iteration {i}"
assert (
init_line_attacked == cpy_line_attacked
), f"wrong line attack at iteration {i} for the copy env"
| 2,842 | 42.738462 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_281.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import grid2op
import warnings
from grid2op.Action import CompleteAction
from grid2op.gym_compat import GymEnv
class Issue281Tester(unittest.TestCase):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_storage", test=True, action_class=CompleteAction
)
def tearDown(self):
self.env.close()
def test_can_make(self):
"""test that the opponent state is correctly copied"""
gym_env = GymEnv(self.env)
if __name__ == "__main__":
unittest.main()
| 1,095 | 32.212121 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_282.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import grid2op
from grid2op.Action import CompleteAction
from grid2op.gym_compat import GymEnv
from grid2op.gym_compat import BoxGymActSpace
class Issue282Tester(unittest.TestCase):
def setUp(self):
self._default_act_attr_to_keep = ["redispatch", "curtail", "set_storage"]
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_storage", test=True, action_class=CompleteAction
)
self.env_gym = GymEnv(self.env)
self.env_gym.action_space.close()
self.env_gym.action_space = BoxGymActSpace(
self.env.action_space, attr_to_keep=self._default_act_attr_to_keep
)
self.env_gym.reset(seed=0) #reset and seed
def tearDown(self):
self.env.close()
self.env_gym.close()
def test_can_make(self):
"""test that the opponent state is correctly copied"""
act = self.env_gym.action_space.from_gym(self.env_gym.action_space.sample())
obs, reward, done, info = self.env.step(act)
assert len(info["exception"]) == 0, f"{info['exception'] = }"
if __name__ == "__main__":
unittest.main()
| 1,702 | 36.021739 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_283.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import grid2op
from grid2op.Rules.AlwaysLegal import AlwaysLegal
from grid2op.gym_compat import GymEnv
from grid2op.gym_compat import BoxGymActSpace
class Issue283Tester(unittest.TestCase):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"educ_case14_storage", test=True, gamerules_class=AlwaysLegal
)
self.env_gym = GymEnv(self.env)
self.env_gym.action_space.close()
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env_gym.action_space = BoxGymActSpace(self.env.action_space)
# self.env_gym.seed(0)
self.env_gym.reset(seed=0)
def tearDown(self):
self.env.close()
self.env_gym.close()
def test_can_make(self):
"""test that the opponent state is correctly copied"""
gym_act = self.env_gym.action_space.sample()
gym_act[
: self.env.n_line
] = 0.0 # do not change line status ! (otherwise it diverges)
act = self.env_gym.action_space.from_gym(gym_act)
obs, reward, done, info = self.env.step(act)
assert len(info["exception"]) == 0, f"{info['exception'] = }"
if __name__ == "__main__":
unittest.main()
| 1,814 | 34.588235 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_285.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import warnings
import re
import grid2op
from grid2op.Chronics import MultifolderWithCache
from grid2op.Runner import Runner
class Issue285Tester(unittest.TestCase):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"rte_case5_example", test=True, chronics_class=MultifolderWithCache
)
self.env.chronics_handler.real_data.set_filter(
lambda x: re.match(".*0$", x) is not None
)
self.env.chronics_handler.real_data.reset()
def tearDown(self):
self.env.close()
def test_runner_ok(self):
"""test that the runner works ok"""
runner = Runner(**self.env.get_params_for_runner())
res = runner.run(nb_episode=2, max_iter=5)
assert res[0][1] != res[1][1]
assert res[0][1] == "00"
assert res[1][1] == "10"
if __name__ == "__main__":
unittest.main()
| 1,451 | 32 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_313.py | # Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import unittest
import grid2op
from grid2op.Parameters import Parameters
from lightsim2grid import LightSimBackend
from grid2op.Action import PlayableAction
import warnings
import numpy as np
class Issu313Tester(unittest.TestCase):
def setUp(self):
param = Parameters()
param.NO_OVERFLOW_DISCONNECTION = True
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("educ_case14_storage",
backend=LightSimBackend(),
action_class=PlayableAction,
param=param,
test=True)
self.env.set_id(2)
self.env.seed(0)
self.env.reset()
self.env.fast_forward_chronics(215)
def tearDown(self):
self.env.close()
def test_gen_margin_up(self):
"""test that the runner works ok"""
act_prev = self.env.action_space()
act_prev.storage_p = [4.9, 9.9]
obs, reward, done, info = self.env.step(act_prev)
obs, reward, done, info = self.env.step(act_prev)
obs, reward, done, info = self.env.step(act_prev)
obs, reward, done, info = self.env.step(act_prev)
assert np.all(obs.gen_margin_up >= 0.)
# this is because the last generator (slack bus) has a pmax of 100. and a value of 100.05 ...
if __name__ == "__main__":
unittest.main()
| 1,911 | 35.769231 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_319.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
"""Script to reproduce and demonstrate the bug in the BackendAction class of grid2op."""
import pdb
import warnings
import unittest
import grid2op
import numpy as np
class Issue319Tester(unittest.TestCase):
def setUp(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(
"rte_case14_realistic",
test=True
)
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_backend_action_simple(self):
disc_lines = np.array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1])
self.env._backend_action.update_state(disc_lines)
assert np.all(self.env._backend_action.current_topo.values >= 1)
disc_lines[5] = 0
self.env._backend_action.update_state(disc_lines)
# line 0 is not disconnected
assert self.env._backend_action.current_topo.values[self.env.line_or_pos_topo_vect[0]] == 1
assert self.env._backend_action.current_topo.values[self.env.line_ex_pos_topo_vect[0]] == 1
# line 5 should be disconnected
assert self.env._backend_action.current_topo.values[self.env.line_or_pos_topo_vect[5]] == -1
assert self.env._backend_action.current_topo.values[self.env.line_ex_pos_topo_vect[5]] == -1
def test_in_real_scenario(self):
# change the thermal limit to fake a cascading failure
# on line 10 and 19
th_lim = 1.0 * self.env._thermal_limit_a
th_lim[[10, 19]] = 0.8 * np.array([17.683975, 635.8966])
self.env.set_thermal_limit(th_lim)
obs = self.env.reset()
obs, *_ = self.env.step(self.env.action_space())
obs, *_ = self.env.step(self.env.action_space())
# cascading failure should happen now !
obs, rew, done, info = self.env.step(self.env.action_space())
assert not done
assert np.all(info["disc_lines"][[10, 19]] == 0)
# line 0 is not disconnected
assert self.env._backend_action.current_topo.values[self.env.line_or_pos_topo_vect[0]] == 1
assert self.env._backend_action.current_topo.values[self.env.line_ex_pos_topo_vect[0]] == 1
# lines 10, 19 should be disconnected
assert np.all(self.env._backend_action.current_topo.values[self.env.line_or_pos_topo_vect[[10, 19]]] == -1)
assert np.all(self.env._backend_action.current_topo.values[self.env.line_ex_pos_topo_vect[[10, 19]]] == -1)
if __name__ == '__main__':
unittest.main()
| 3,141 | 46.606061 | 115 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_321.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import unittest
import grid2op
from grid2op.Parameters import Parameters
from grid2op.Action import PlayableAction
import numpy as np
class Issue321Tester(unittest.TestCase):
def test_curtail_limit_effective(self):
"""test that obs.curtailment_limit is above
obs.curtailment_limit_effective in this case
previously it was O. for some generators see the issue
"""
param = Parameters()
param.LIMIT_INFEASIBLE_CURTAILMENT_STORAGE_ACTION = True
env_name = "educ_case14_storage"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make(env_name, test=True,
action_class=PlayableAction, param=param)
env.seed(0)
env.set_id(0)
env.reset()
# Apply a curtailment action
action = env.action_space({'curtail': [(2, 0.1), (3, 0.15), (4, 0.2)]})
obs, _, _, _ = env.step(action)
# env does not act, they should be equal
assert np.all(obs.curtailment_limit == obs.curtailment_limit_effective)
def test_when_params_active_cutdown(self):
"""test the curtailment effective is above the curtailment
when we want to curtail too much at once"""
seed_ = 0
scen_nm = "2050-02-14_0"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_wcci_2022_dev",
test=True)
param = env.parameters
param.LIMIT_INFEASIBLE_CURTAILMENT_STORAGE_ACTION = True
env.seed(seed_)
env.set_id(scen_nm)
obs = env.reset()
all_zero = env.action_space(
{"curtail": [(el, 0.0) for el in np.where(env.gen_renewable)[0]]}
)
obs, reward, done, info = env.step(all_zero)
assert done
env.change_parameters(param)
env.seed(seed_)
env.set_id(scen_nm)
obs = env.reset()
obs, reward, done, info = env.step(all_zero)
assert not done
# stuff is activated, the real limit (effective) is above the
# limit in the action (env "cut down" curtailment)
assert np.all(obs.curtailment_limit <= obs.curtailment_limit_effective)
assert np.all(obs.curtailment_limit[env.gen_renewable] == 0.)
def test_when_params_active_limitup(self):
"""test the curtailment effective is below the curtailment limit
when too much curtailment has been removed "at once"
"""
seed_ = 0
scen_nm = "2050-02-14_0"
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_wcci_2022_dev",
test=True)
param = env.parameters
param.LIMIT_INFEASIBLE_CURTAILMENT_STORAGE_ACTION = True
env.seed(seed_)
env.set_id(scen_nm)
obs = env.reset()
# produce a list of actions that can curtail down to O.
# then remove all curtailment at once (and check it
# breaks the env)
first_ = env.action_space(
{"curtail": [(el, 0.15) for el in np.where(env.gen_renewable)[0]]}
)
second_ = env.action_space(
{"curtail": [(el, 0.09) for el in np.where(env.gen_renewable)[0]]}
)
third_ = env.action_space(
{"curtail": [(el, 0.04) for el in np.where(env.gen_renewable)[0]]}
)
all_zero = env.action_space(
{"curtail": [(el, 0.0) for el in np.where(env.gen_renewable)[0]]}
)
all_one = env.action_space(
{"curtail": [(el, 1.0) for el in np.where(env.gen_renewable)[0]]}
)
obs, reward, done, info = env.step(first_)
assert not done
obs, reward, done, info = env.step(second_)
assert not done
obs, reward, done, info = env.step(third_)
assert not done
obs, reward, done, info = env.step(all_zero)
assert not done
obs, reward, done, info = env.step(all_one)
assert done
# use this same list of actions, and make sure it does not break the
# env with the appropriate params (expected !)
# => this means the params is effective. And so the env prevent a
# removal of the curtailment too strong.
env.change_parameters(param)
env.seed(seed_)
env.set_id(scen_nm)
obs = env.reset()
obs, reward, done, info = env.step(first_)
assert not done
obs, reward, done, info = env.step(second_)
assert not done
obs, reward, done, info = env.step(third_)
assert not done
obs, reward, done, info = env.step(all_zero)
assert not done
obs, reward, done, info = env.step(all_one)
assert not done
# stuff is activated, the real limit (effective) is below the
# limit in the action: instead of having a curtailment of 1.,
# curtailment is a below, just enough not to break
assert np.all(obs.curtailment_limit[env.gen_renewable] == 1.)
gen_prod = obs.gen_p > 0.
assert np.all(obs.curtailment_limit[env.gen_renewable & gen_prod] >
obs.curtailment_limit_effective[env.gen_renewable & gen_prod])
if __name__ == "__main__":
unittest.main()
| 5,978 | 39.127517 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_327.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import unittest
import grid2op
import numpy as np
import pdb
class Issue327Tester(unittest.TestCase):
"""test that i can retrieve all the "graph" information if the observation is "done",
this made grid2op <= 1.7.0 versions fail"""
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def _aux_set_game_over(self):
act = self.env.action_space({"set_bus": {"loads_id": [(0, -1)]}})
obs, reward, done, info = self.env.step(act)
assert done
return obs
def test_get_energy_graph(self):
obs = self._aux_set_game_over()
with warnings.catch_warnings():
warnings.filterwarnings("error")
graph = obs.get_energy_graph()
assert graph.number_of_nodes() == 1
assert graph.number_of_edges() == 0
def test_flow_bus_matrix(self):
obs = self._aux_set_game_over()
flow_mat, (load_bus, prod_bus, stor_bus, lor_bus, lex_bus) = obs.flow_bus_matrix()
assert flow_mat.shape == (1,1)
assert flow_mat.sum() == 0.
def test_bus_connectivity_matrix(self):
obs = self._aux_set_game_over()
bus_bus_graph = obs.bus_connectivity_matrix(return_lines_index=False)
assert bus_bus_graph.shape == (1,1)
assert bus_bus_graph.sum() == 0.
def test_connectivity_matrix(self):
obs = self._aux_set_game_over()
connectivity_matrix = obs.connectivity_matrix()
assert np.all(connectivity_matrix == 0)
assert np.all(connectivity_matrix.shape == (self.env.dim_topo, self.env.dim_topo))
if __name__ == "__main__":
unittest.main()
| 2,454 | 36.19697 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_331.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import unittest
import grid2op
from grid2op.Exceptions import Grid2OpException
class Issue331Tester(unittest.TestCase):
def test_seed(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_case14_sandbox", test=True)
with self.assertRaises(Grid2OpException):
env.seed(2735729614) # crashes !
env.seed(2147483647) # just the limit
with self.assertRaises(Grid2OpException):
env.seed(2147483648) # crashes !
if __name__ == "__main__":
unittest.main()
| 1,167 | 34.393939 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_340.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import warnings
import unittest
import grid2op
from grid2op.Exceptions import Grid2OpException
import numpy as np
class Issue340Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_wcci_2022", test=True)
return super().setUp()
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_obs(self):
obs = self.env.reset()
obs.state_of(storage_id=0)
def test_act_add(self):
act0 = self.env.action_space({"curtail": [(0, 0.5)]})
act1 = self.env.action_space({"curtail": [(1, 0.5)]})
res = act0 + act1
assert np.all(res.curtail[[0,1]] == 0.5)
if __name__ == "__main__":
unittest.main()
| 1,376 | 32.585366 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_361.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
from grid2op.Runner import Runner
class Issue361Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_case14_sandbox", test=True)
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_copy(self):
env_cpy = self.env.copy()
assert hasattr(self.env.backend, "_my_kwargs")
assert hasattr(env_cpy.backend, "_my_kwargs")
env_cpy.close()
def test_runner(self):
env_cpy = self.env.copy()
runner = Runner(**env_cpy.get_params_for_runner())
res = runner.run(nb_episode=1, max_iter=10)
# this crashed above
env_cpy.close()
if __name__ == "__main__":
unittest.main()
| 1,405 | 32.47619 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_364.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import grid2op
import unittest
import warnings
from grid2op.Runner import Runner
class Issue364Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make("l2rpn_wcci_2022", test=True)
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
def test_copy(self):
act = self.env.action_space({"curtail": [(1, 0.)]})
dict_ = act.impact_on_objects()
assert act._modif_curtailment
assert dict_["curtailment"]["changed"]
assert not dict_["storage"]["changed"]
if __name__ == "__main__":
unittest.main()
| 1,226 | 34.057143 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_367.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import grid2op
import unittest
import warnings
from grid2op.tests.helper_path_test import *
class Issue367Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
self.env = grid2op.make(os.path.join(PATH_DATA_TEST, "test_issue_367"), test=True)
# self.env = grid2op.make("l2rpn_wcci_2022", test=True)
self.env.set_id(0)
self.env.seed(0)
param = self.env.parameters
param.NO_OVERFLOW_DISCONNECTION = True
self.env.change_parameters(param)
obs = self.env.reset()
def test_action(self):
gen_id = 2
dn = self.env.action_space()
for i in range(7):
obs, reward, done, info = self.env.step(dn)
if done:
raise RuntimeError(f"done at step {i}")
assert obs.target_dispatch[gen_id] == 0.0, f"should be 0., but is {obs.target_dispatch[gen_id]:.2f}"
act = self.env.action_space()
act.redispatch = [(gen_id, -3.5)]
obs, reward, done, info = self.env.step(act)
assert not done
assert not info['is_dispatching_illegal']
assert obs.target_dispatch[gen_id] == -3.5, f"should be -3.5, but is {obs.target_dispatch[gen_id]:.2f}"
act = self.env.action_space()
act.redispatch = [(gen_id, +3.5)]
obs, reward, done, info = self.env.step(act)
assert not done
assert obs.target_dispatch[gen_id] == 0., f"should be 0., but is {obs.target_dispatch[gen_id]:.2f}"
act = self.env.action_space()
act.redispatch = [(gen_id, +1.5)]
obs, reward, done, info = self.env.step(act)
assert not done
assert not info['is_dispatching_illegal']
assert abs(obs.target_dispatch[gen_id] - 1.5) <= 1e-2, f"should be 1.5, but is {obs.target_dispatch[gen_id]:.2f}"
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
if __name__ == "__main__":
unittest.main()
| 2,584 | 37.014706 | 121 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_369.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import grid2op
import unittest
import warnings
import re
from grid2op.Chronics import MultifolderWithCache
from grid2op.tests.helper_path_test import *
class Issue367Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# Creation of the environment
self.env = grid2op.make("l2rpn_wcci_2022_dev",
chronics_class=MultifolderWithCache,
test=True) # No bug wihout the MultifolderWithCache argument here
self.env.chronics_handler.real_data.set_filter(lambda x: re.match(".*2050-02-14_0", x) is not None) # We test on a randomly chosen chronic for the example
self.env.chronics_handler.reset()
self.env.set_id(0)
self.env.seed(0)
param = self.env.parameters
param.NO_OVERFLOW_DISCONNECTION = True
self.env.change_parameters(param)
self.obs = self.env.reset()
def test_date(self):
assert self.obs.year == 2050
assert self.obs.month == 2
assert self.obs.day == 14
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
if __name__ == "__main__":
unittest.main()
| 1,830 | 35.62 | 166 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_374.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import grid2op
import unittest
import warnings
import re
from grid2op.Parameters import Parameters
class Issue367Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# Creation of the environment
param = Parameters()
param.NB_TIMESTEP_COOLDOWN_SUB = 3
param.NB_TIMESTEP_COOLDOWN_LINE = 3
param.NO_OVERFLOW_DISCONNECTION = True
self.env = grid2op.make('l2rpn_wcci_2022', param=param)
self.env.set_id(0)
self.env.seed(0)
self.obs = self.env.reset()
def test_cooldown(self):
# second, get some action that has no actual effect on the grid
action_space = self.env.action_space
env = self.env
do_nothing = action_space()
# take an action
set_sub_10 = action_space.get_all_unitary_topologies_set(action_space, sub_id=10)
set_sub10_to_bus1 = set_sub_10[5]
# do the action to trigger the cooldown
obs, _, done, info = env.step(set_sub10_to_bus1)
assert obs.time_before_cooldown_sub[10] == 3
assert info['exception'] == []
# check cooldown
obs, _, done, info = env.step(do_nothing)
assert obs.time_before_cooldown_sub[10] == 2
assert info['exception'] == []
# check i cannot simulate
obs_, _, done, info = obs.simulate(set_sub10_to_bus1)
assert info['exception'] != [], "simulate should have raised an error"
# check cooldown
obs, _, done, info = env.step(do_nothing)
assert obs.time_before_cooldown_sub[10] == 1
assert info['exception'] == []
# check i cannot simulate
obs_, _, done, info = obs.simulate(set_sub10_to_bus1)
assert obs_.time_before_cooldown_sub[10] == 0
assert info['exception'] != [], "simulate should have raised an error"
# check i cannot "step"
obs, _, done, info = env.step(set_sub10_to_bus1)
assert obs.time_before_cooldown_sub[10] == 0
assert info['exception'] != [], "step should have raised an error"
# check i can simulate
obs_, _, done, info = obs.simulate(set_sub10_to_bus1)
assert obs_.time_before_cooldown_sub[10] == 3
assert info['exception'] == []
# check i can "step"
obs, _, done, info = env.step(set_sub10_to_bus1)
assert obs.time_before_cooldown_sub[10] == 3
assert info['exception'] == []
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
if __name__ == "__main__":
unittest.main()
| 3,234 | 35.348315 | 112 | py |
Grid2Op | Grid2Op-master/grid2op/tests/test_issue_377.py | # Copyright (c) 2019-2022, RTE (https://www.rte-france.com)
# See AUTHORS.txt and https://github.com/rte-france/Grid2Op/pull/319
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import pdb
import numpy as np
import grid2op
import unittest
import warnings
import re
from grid2op.Parameters import Parameters
class Issue367Tester(unittest.TestCase):
def setUp(self) -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
# Creation of the environment
param = Parameters()
param.NB_TIMESTEP_COOLDOWN_SUB = 3
param.NB_TIMESTEP_COOLDOWN_LINE = 3
param.NO_OVERFLOW_DISCONNECTION = True
self.env = grid2op.make('l2rpn_wcci_2022', param=param)
self.env.set_id(0)
self.env.seed(0)
self.obs = self.env.reset()
def test_cooldown(self):
thermal_limits = self.env.get_thermal_limit()
# Get the simulator
sim = self.obs.get_simulator()
# Manually compute rho using thermal limits
rho_old = sim.current_obs.a_or / thermal_limits
assert np.max(np.abs(sim.current_obs.rho.max() - rho_old.max())) <= 1e-5
# Simulate 1 do_nothing action, with loads/gens/etc. staying the same
do_nothing = self.env.action_space()
new_sim = sim.predict(do_nothing)
# Manually compute new rho, since the rho from the simulator is wrong.
rho_new = new_sim.current_obs.a_or / thermal_limits
assert np.max(np.abs(new_sim.current_obs.rho.max() - rho_new.max())) <= 1e-5
def tearDown(self) -> None:
self.env.close()
return super().tearDown()
if __name__ == "__main__":
unittest.main()
| 2,082 | 33.147541 | 112 | py |