Skip to content

Commit ef2b98c

Browse files
committed
fixing some bugs in the forecast env
Signed-off-by: DONNOT Benjamin <[email protected]>
1 parent 02a71af commit ef2b98c

File tree

6 files changed

+470
-22
lines changed

6 files changed

+470
-22
lines changed

grid2op/Backend/backend.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from abc import ABC, abstractmethod
1616
import numpy as np
1717
import pandas as pd
18-
from typing import Tuple, Optional, Any, Dict, Union
18+
from typing import Tuple, Optional, Any, Dict, Type, Union
1919

2020
try:
2121
from typing import Self
@@ -38,6 +38,7 @@
3838
from grid2op.Space import GridObjects, ElTypeInfo, DEFAULT_N_BUSBAR_PER_SUB, DEFAULT_ALLOW_DETACHMENT
3939
import grid2op.Observation # for type hints
4040
import grid2op.Action # for type hints
41+
import grid2op.Action._BackendAction # for type hints
4142

4243

4344
# TODO method to get V and theta at each bus, could be in the same shape as check_kirchoff
@@ -118,8 +119,8 @@ class Backend(GridObjects, ABC):
118119
IS_BK_CONVERTER : bool = False
119120

120121
# action to set me
121-
my_bk_act_class : "Optional[grid2op.Action._backendAction._BackendAction]" = None
122-
_complete_action_class : "Optional[grid2op.Action.CompleteAction]" = None
122+
my_bk_act_class : "Optional[Type[grid2op.Action._BackendAction._BackendAction]]" = None
123+
_complete_action_class : "Optional[Type[grid2op.Action.CompleteAction]]" = None
123124

124125
ERR_INIT_POWERFLOW : str = "Power cannot be computed on the first time step, please check your data."
125126
ERR_DETACHMENT : str = ("One or more {} were isolated from the grid "
@@ -1972,7 +1973,7 @@ def update_from_obs(self,
19721973
}
19731974

19741975
if cls.shunts_data_available and type(obs).shunts_data_available:
1975-
if cls.n_shunt > 0 and "_shunt_bus" not in type(obs).attr_list_set:
1976+
if cls.n_shunt > 0 and "_shunt_bus" not in (type(obs).attr_list_set | set(type(obs).attr_list_json)):
19761977
raise BackendError(
19771978
"Impossible to set the backend to the state given by the observation: shunts data "
19781979
"are not present in the observation."
@@ -1993,6 +1994,7 @@ def update_from_obs(self,
19931994
act.update(dict_)
19941995
backend_action += act
19951996
self.apply_action(backend_action)
1997+
backend_action.reset() # already processed by the backend
19961998
return backend_action
19971999

19982000
def assert_grid_correct(self, _local_dir_cls=None) -> None:

grid2op/Backend/pandaPowerBackend.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -858,7 +858,6 @@ def apply_action(self, backendAction: Union["grid2op.Action._backendAction._Back
858858
"""
859859
if backendAction is None:
860860
return
861-
862861
cls = type(self)
863862

864863
(

grid2op/Environment/baseEnv.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3550,7 +3550,11 @@ def step(self, action: BaseAction) -> Tuple[BaseObservation,
35503550
# and this regardless of the
35513551
_ = action.get_topological_impact(powerline_status, _store_in_cache=True, _read_from_cache=False)
35523552

3553-
is_legal, reason = self._game_rules(action=action, env=self)
3553+
if self._last_obs is not None:
3554+
is_legal, reason = self._game_rules(action=action, env=self)
3555+
else:
3556+
is_legal = True
3557+
reason = None
35543558
if not is_legal:
35553559
# action is replace by do nothing
35563560
action.reset_cache_topological_impact()
@@ -4640,11 +4644,6 @@ def _reset_to_orig_state(self, obs):
46404644

46414645
# soft overflow
46424646
self._timestep_overflow[:] = obs.timestep_overflow
4643-
4644-
# previous "connected" state of all elements
4645-
self._previous_conn_state.update_from_other(obs._prev_conn) # already done with _cst_prev_XXX
4646-
self._backend_action.last_topo_registered.values[:] = obs._prev_conn._topo_vect
4647-
# self._backend_action.current_topo.values[:] = obs._prev_conn._topo_vect
46484647

46494648
def forecasts(self):
46504649
# ensure that the "env.chronics_handler.forecasts" is called at most once per step

grid2op/Environment/environment.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,9 @@ def reset_grid(self,
955955
If the thermal has been modified, it also modify them into the new backend.
956956
957957
"""
958+
# force the first observation to be generated properly
959+
self._last_obs = None
960+
958961
# the real powergrid of the environment
959962
self.backend.reset(self._init_grid_path)
960963

@@ -972,6 +975,9 @@ def reset_grid(self,
972975
self._backend_action.last_topo_registered.values[:] = self._init_obs._prev_conn._topo_vect
973976
else:
974977
self._backend_action = self._backend_action_class()
978+
979+
if self._init_obs is not None:
980+
self._reset_to_orig_state(self._init_obs)
975981

976982
init_action = None
977983
if not self._parameters.IGNORE_INITIAL_STATE_TIME_SERIE:
@@ -983,9 +989,15 @@ def reset_grid(self,
983989
else:
984990
# do as if everything was connected to busbar 1
985991
# TODO logger: log that
986-
init_action = self._helper_action_env({"set_bus": np.ones(type(self).dim_topo, dtype=dt_int)})
987-
if type(self).shunts_data_available:
988-
init_action += self._helper_action_env({"shunt": {"set_bus": np.ones(type(self).n_shunt, dtype=dt_int)}})
992+
if self._init_obs is None:
993+
init_action = self._helper_action_env({"set_bus": np.ones(type(self).dim_topo, dtype=dt_int)})
994+
if type(self).shunts_data_available:
995+
init_action += self._helper_action_env({"shunt": {"set_bus": np.ones(type(self).n_shunt, dtype=dt_int)}})
996+
else:
997+
init_action = self._helper_action_env({"set_bus": self._init_obs.topo_vect})
998+
if type(self).shunts_data_available:
999+
init_action += self._helper_action_env({"shunt": {"set_bus": self._init_obs._shunt_bus}})
1000+
9891001
if init_action is None:
9901002
# default behaviour for grid2op < 1.10.2
9911003
init_action = self._helper_action_env({})
@@ -1003,7 +1015,7 @@ def reset_grid(self,
10031015
raise Grid2OpException(f"kwargs `method` used to set the initial state of the grid "
10041016
f"is not understood (use one of `combine` or `ignore` and "
10051017
f"not `{method}`)")
1006-
init_action._set_topo_vect.nonzero()
1018+
10071019
*_, fail_to_start, info = self.step(init_action)
10081020
if fail_to_start:
10091021
raise Grid2OpException(
@@ -1383,6 +1395,7 @@ def reset(self,
13831395

13841396
if options is not None and "init datetime" in options:
13851397
self.chronics_handler.set_current_datetime(options["init datetime"])
1398+
13861399
self.reset_grid(init_state, method)
13871400
if self.viewer_fig is not None:
13881401
del self.viewer_fig
@@ -1423,11 +1436,6 @@ def reset(self,
14231436
# and reset also the "simulated env" in the observation space
14241437
self._observation_space.reset(self)
14251438
self._observation_space.set_real_env_kwargs(self)
1426-
1427-
self._last_obs = None # force the first observation to be generated properly
1428-
1429-
if self._init_obs is not None:
1430-
self._reset_to_orig_state(self._init_obs)
14311439
return self.get_obs()
14321440

14331441
def render(self, mode="rgb_array"):

grid2op/tests/test_forecast_env.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@ def _aux_normal_obs(self, obs, line_id=0):
3232
for_env = obs.get_forecast_env()
3333
for_obs = for_env.reset()
3434
assert (for_obs.topo_vect == obs.topo_vect).all(), f"{(for_obs.topo_vect != obs.topo_vect).nonzero()}"
35-
3635
for_obs = for_env.reset(options={"init state": {"set_line_status": [(line_id, -1)]}})
37-
assert (for_obs.topo_vect != obs.topo_vect).sum() == 2
36+
assert (for_obs.topo_vect != obs.topo_vect).sum() == 2, f"{(for_obs.topo_vect != obs.topo_vect).nonzero()}"
3837
assert for_obs.topo_vect[type(self.env).line_or_pos_topo_vect[line_id]] == -1
3938
assert for_obs.topo_vect[type(self.env).line_ex_pos_topo_vect[line_id]] == -1
4039

0 commit comments

Comments
 (0)