Repository navigation
Conversation
…Action and gym Box support Signed-off-by: Mohsen Dastpak <moh.dastpak@gmail.com>
Not up to standards ⛔
|
|
Hello, Thanks a lot for this contribution. Just so you know I ask an instance of Claude to make a review of this PR. As far as I could tell it raised some interesting things that will follow. In case it's wrong don't hesitate to tell 😊 I'll re review it after the few foxes Claude proposed. Thanks again Benjamin |
BDonnot
left a comment
There was a problem hiding this comment.
🤖 Review by Claude (Claude Opus 5.5, an AI assistant), posted at the maintainer's request (see the comment above).
Hi @moda707, and welcome! Thanks a lot for this contribution. Shunt control is a real gap for voltage-control studies, and this PR is in good shape. A few things I particularly liked:
- the description is clear and honest about the scope (continuous setpoints, no section count, unbounded gym keys);
- the new properties follow the existing
redispatch/set_buspatterns, including the rollback on invalid input; - the tests go beyond plumbing, e.g. they check that a capacitive / inductive setpoint actually raises / lowers the voltages;
- the docs and the CHANGELOG are updated.
I ran your 18 tests locally and they all pass. I then looked for edge cases. Every problem described in the inline comments was reproduced on a running environment before posting, and every fix or test I suggest was tried locally. The related existing test modules still pass with the fixes applied.
Severity scale used in the comments
- high: can make
env.stepraise in a common setup - medium: wrong or surprising behaviour in a realistic but narrower setup
- low: limited impact
- nit: polish, entirely optional
Several findings are pre-existing grid2op issues that your new API simply makes easier to reach. They are marked as such: they are not your fault, and it's completely fine to say if you'd rather leave them to the maintainers.
| Topic | Severity | Origin |
|---|---|---|
Changing the bus of some (not all) shunts crashes env.step with PandaPowerBackend |
high | pre-existing |
shunt_p / shunt_q / shunt_bus getters raise TypeError without shunt data (and break BoxGymActSpace.from_gym) |
medium | this PR |
BoxGymObsSpace _shunt_* keys fail in to_gym without shunt data |
medium | this PR |
Shunt bus changes ignored by MAX_SUB_CHANGED / substation cooldown |
medium | pre-existing gap, design question |
GymEnv(env) gets an empty action space with ShuntAction |
medium | pre-existing |
== ignores shunt_bus |
low | pre-existing |
to_vect() cache not refreshed after a setter |
low | shared pattern |
sample() never samples shunt actions |
low | n/a |
print(act) doesn't show shunt changes |
low | n/a |
Error-message names, shunt_bus rounding note, docs wording, type hints |
nit | this PR |
If anything here looks wrong to you, please say so; I may well have misread something. And don't hesitate to ask if a suggestion is unclear. Thanks again for the work!
Generated by Claude Code
| return res | ||
|
|
||
| @shunt_bus.setter | ||
| def shunt_bus(self, values): |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: high · pre-existing in grid2op, now easy to reach through the new API
Changing the bus of some shunts (more than one, but not all of them) makes env.step raise a numpy ValueError with PandaPowerBackend. The cause is not in your code. It is in PandaPowerBackend.apply_action, where a mask sized to the changed shunts is combined with a mask sized to all shunts:
sh_service = shunt_bus.values[shunt_bus.changed] != -1 # shape (n_changed,)
...
chg_and_in_service = sh_service & shunt_bus.changed # shape (n_shunt,) -> broadcasting errorNobody noticed it before because l2rpn_case14_sandbox has a single shunt, and a single changed shunt happens to broadcast. Your shunt_bus setter, ShuntAction and the gym shunt_bus key now make it easy to reach, for example on l2rpn_idf_2023 (14 shunts):
env = grid2op.make("l2rpn_idf_2023", test=True, action_class=ShuntAction)
env.reset(seed=0, options={"time serie id": 0})
act = env.action_space()
act.shunt_bus = [(0, 1), (1, 1)]
env.step(act) # ValueError: operands could not be broadcast together with shapes (2,) (14,)It can be fixed in one line by building the mask on all shunts:
chg_and_in_service = shunt_bus.changed & (shunt_bus.values != -1)A test on a grid with several shunts would protect it, for example:
from grid2op.Rules import AlwaysLegal
def test_shunt_bus_several_shunts(self):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
env = grid2op.make("l2rpn_idf_2023", test=True, action_class=ShuntAction,
gamerules_class=AlwaysLegal, # only test the backend here
_add_to_name=type(self).__name__)
try:
obs = env.reset(seed=0, options={"time serie id": 0})
act = env.action_space()
act.shunt_bus = [(0, 1), (1, 1)] # 2 of the 14 shunts (they all start disconnected)
obs, reward, done, info = env.step(act)
assert not done
assert (obs._shunt_bus[[0, 1]] == 1).all()
finally:
env.close()I ran this test locally: it fails with the ValueError on this branch and passes with the one-line fix. Since the bug predates your PR, it's completely fine to say if you'd rather leave this one to the maintainers.
Generated by Claude Code
There was a problem hiding this comment.
Shunt bus mask in PandaPowerBackend: you were right, it broke as soon as only some of the shunts changed bus. It's fixed and tested on l2rpn_idf_2023, which has several shunts. There's a CHANGELOG entry since the bug was already there before this PR.
| :class:`grid2op.Action.ShuntAction` or :class:`grid2op.Action.CompleteAction`). | ||
|
|
||
| """ | ||
| res = 1.0 * self._shunt_p |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: medium · introduced by this PR
On a backend without shunt data (shunts_data_available == False, e.g. EducPandaPowerBackend), self._shunt_p is None. Reading the property then raises a bare TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'. The same happens for shunt_q (line 7562) and shunt_bus (line 7584).
This also affects BoxGymActSpace.from_gym, which calls hasattr(res, "shunt_q"). hasattr only swallows AttributeError, so the TypeError escapes. A space like BoxGymActSpace(env.action_space, attr_to_keep=["redispatch", "shunt_q"]) builds fine (you nicely sized the shunt part to 0 in that case) but then fails on every from_gym call.
Returning an empty array when there is no shunt data fixes both, since from_gym already skips 0-length parts:
@property
def shunt_p(self) -> np.ndarray:
"""..."""
if self._shunt_p is None:
# backend without shunt data
return np.zeros(0, dtype=dt_float)
res = 1.0 * self._shunt_p
res.flags.writeable = False
return resUse np.zeros(0, dtype=dt_int) for shunt_bus. I tried this locally: act.shunt_q then returns [], and from_gym works on a no-shunt backend. A small test with backend=EducPandaPowerBackend() and action_class=CompleteAction would cover it. Raising a clear IllegalAction would also be a reasonable choice, but then from_gym would need its own guard.
Generated by Claude Code
There was a problem hiding this comment.
Getters without shunt data: they now return an empty vector instead of raising.
| else: | ||
| tol_redisp = 1e-2 | ||
| extra_for_losses = _compute_extra_power_for_losses(ob_sp) | ||
| nb_shunt = ob_sp_cls.n_shunt if ob_sp_cls.shunts_data_available else 0 |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: medium · introduced by this PR
The observation side has the same situation. With a backend without shunt data, the observation never gets the _shunt_p / _shunt_q / _shunt_v / _shunt_bus attributes, because they are only created when shunts_data_available. So BoxGymObsSpace(env.observation_space, attr_to_keep=["rho", "_shunt_q"]) builds with a 0-sized part. The first to_gym(obs) then raises RuntimeError('Unknown attribute "_shunt_q".'), because of the hasattr(grid2op_observation, attr_nm) check in to_gym.
You chose to size these parts to 0, which I think is the right call. One way to make that consistent is to skip empty parts in to_gym:
for attr_nm, where_to_put in zip(self._attr_to_keep, self._dims):
if where_to_put == prev:
# nothing to fill (eg. shunt attributes with a backend without shunt data)
continue
if attr_nm in self.__func:
...I tried it locally: to_gym then returns the rho part only. Raising a clear error in __init__ when a _shunt_* key is requested without shunt data would also be fine. It's mostly a matter of taste.
Generated by Claude Code
There was a problem hiding this comment.
empty attributes are now skipped.empty attributes are now skipped.
| from grid2op.Action.playableAction import PlayableAction | ||
|
|
||
|
|
||
| class ShuntAction(PlayableAction): |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: medium · pre-existing gap that ShuntAction makes relevant; partly a design question
The legality rules don't see changes to shunt_bus. _dont_affect_topology() and get_topological_impact() ignore the shunts, so MAX_SUB_CHANGED and the substation cooldown (NB_TIMESTEP_COOLDOWN_SUB) never apply to them. With CompleteAction this mattered little, since that class is not meant for agents. With ShuntAction, an agent can reconnect or move every shunt of the grid in a single step, and do it again at the next step. Detachment raised the same question, which is why it was added to _subs_impacted.
Whether moving a shunt should count as a "substation action" is a modelling choice, so it's worth confirming with the maintainers first. If the answer is yes, here is a sketch I tested locally:
def _dont_affect_topology(self) -> bool:
return (
(not self._modif_set_bus)
# ... unchanged ...
and (not self._modif_detach_storage)
and (not self._shunt_bus_modified())
)
def _shunt_bus_modified(self) -> bool:
return (
type(self).shunts_data_available
and self._private_shunt_bus is not None
and bool((self._private_shunt_bus != 0).any())
)and in get_topological_impact, next to the detachment block:
if self._shunt_bus_modified():
_subs_impacted[cls.shunt_to_subid[self._private_shunt_bus != 0]] = TrueWith DefaultRules and MAX_SUB_CHANGED = 1, moving 2 shunts at 2 substations then becomes illegal. Moving 1 is legal and starts that substation's cooldown. shunt_p / shunt_q changes would stay outside the rules, like redispatching.
One heads-up so it doesn't confuse you if you try this: on an environment with alerts (e.g. l2rpn_idf_2023), an illegal action of a class that does not allow raise_alert currently makes env.step raise IllegalAction("Impossible to send alerts with this action type."). That is a pre-existing grid2op bug (it also happens with PowerlineSetAction), not something in your code. I've reported it to the maintainers separately. Also note that l2rpn_idf_2023 uses per-area rules, so two substations in different areas can legitimately both be changed.
Generated by Claude Code
There was a problem hiding this comment.
I didn't change anything here on purpose. At the moment shunt_bus doesn't count in _dont_affect_topology, get_topological_impact, MAX_SUB_CHANGED or the substation cooldowns. Whether switching a shunt should count as a topology action feels like your call more than mine. If you'd like it counted, your _shunt_bus_modified sketch looks like the right way to do it, and I'm happy to add it to this PR.
| vect = act.to_vect() | ||
| assert vect.shape == (self.env.action_space.n,) | ||
| act2 = self.env.action_space.from_vect(vect) | ||
| assert act == act2 |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: low · pre-existing in grid2op, not caused by your PR
Just a heads-up: act == act2 does not actually compare shunt_bus. In _aux_eq_shunts, the line for the "other" action reads self instead of other:
oth_sh_bus = self._private_shunt_bus if self._private_shunt_bus is not None else cls._build_attr("_shunt_bus")So two actions that differ only by shunt_bus (say (0, 1) vs (0, -1)) compare equal. Your explicit act2.shunt_bus[0] == 1 check two lines below is what really protects this test, so your test is fine as it is.
If you'd like to fix it while you're here, it's a one-word change:
oth_sh_bus = other._private_shunt_bus if other._private_shunt_bus is not None else cls._build_attr("_shunt_bus")with a test such as:
a = self.env.action_space()
a.shunt_bus = [(0, 1)]
b = self.env.action_space()
b.shunt_bus = [(0, -1)]
assert not (a == b)I checked locally that this test fails today and passes with the fix. It's also totally fine to leave it to the maintainers.
Generated by Claude Code
There was a problem hiding this comment.
good catch, the comparison was reading self twice. Fixed, with a CHANGELOG entry.
| (nb_shunt,), | ||
| dt_float, | ||
| ), | ||
| "shunt_bus": ( |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: nit (optional)
BoxGymActSpace warns when a discrete attribute (set_bus, set_line_status, ...) is put in a Box, because from_gym rounds it. shunt_bus is discrete too (-1 / 0 / 1..n_busbar_per_sub) and gets rounded the same way. It is not in ATTR_DISCRETE, though, so users get no hint about this.
If you want the warning, a local change avoids touching the shared ATTR_DISCRETE tuple, which the discrete spaces also use:
for el in ATTR_DISCRETE + ("shunt_bus",):
if el in attr_to_keep:
warnings.warn(...)That's around line 236. One caveat: the warning text recommends MultiDiscreteActSpace, which doesn't support shunts yet, as you noted in the description. So a short sentence in your docs/gym.rst note ("shunt_bus values are rounded to the nearest integer") might be the simpler option. Either is fine.
Generated by Claude Code
There was a problem hiding this comment.
I didn't add one. The rounding happens only in BoxGymActSpace.from_gym, applies to every integer field, and is already documented there. Looking into it, I found something related that you might want to know about. The direct API silently drops decimals: act.shunt_bus = [(0, 1.5)] gives 1, and load_set_bus does the same because the two share _aux_affect_object_int. I'd expect an error there instead. Fixing it would change the behaviour of every *_set_bus setter, so I think it deserves its own issue. What do you think?
| ============================================================================= ========= ============ | ||
|
|
||
| (*) The shunts can only be modified if the backend supports them and with an action type that allows it, | ||
| for example :class:`ShuntAction` (that only allows to modify the shunts) or :class:`CompleteAction`. |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: nit (docs wording)
A small wording suggestion. CompleteAction's own docstring says it "cannot (and should not) be used by an Agent", and it also exposes injections, hazards and maintenance. Someone looking for an agent-facing way to control shunts could read this sentence as a recommendation to use it. Maybe something like:
(*) The shunts can only be modified if the backend supports them and with an action type that allows it.
For an agent, use :class:`ShuntAction` (that only allows to modify the shunts). :class:`CompleteAction`
also allows it, but it is meant for the environment, not for agents.Generated by Claude Code
There was a problem hiding this comment.
updated. ShuntAction is now presented for agents and CompleteAction for the environment.
| return res | ||
|
|
||
| @shunt_p.setter | ||
| def shunt_p(self, values): |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: nit (style, optional)
CONTRIBUTING.md encourages type hints on new code, especially public APIs. The existing setters (redispatch, set_bus, curtail, ...) don't have them either, so you're consistent with the file. If you'd like to add them on the three new setters:
@shunt_p.setter
def shunt_p(self, values: Union[np.ndarray, list, tuple, dict]) -> None:
self._aux_affect_shunt(values, "_shunt_p", "shunt_p")Union would need to be added to the from typing import ... line at the top of the file. Entirely optional.
Generated by Claude Code
| env_name = "l2rpn_case14_sandbox" | ||
| # the default action type does not allow to modify the shunts | ||
| env = grid2op.make(env_name, action_class=ShuntAction) | ||
| gym_env = GymEnv(env) |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: medium · pre-existing mapping issue, made visible by ShuntAction
With ShuntAction, GymEnv(env) gets an empty Dict action space (before you replace it): gym_env.action_space.sample() is {}, so every step is do-nothing. The cause is mapping_vect_auth_keys. It maps _shunt_p / _shunt_q / _shunt_bus to "shunt_p" / "shunt_q" / "shunt_bus", but the authorized key is "shunt", so GymActionSpace._fill_dict_act_space drops them. This already happens with CompleteAction today, so it isn't your bug, but for ShuntAction those are the only attributes.
The example here works because the action space is replaced right after, so this is about people who use the default GymEnv(env). Here is a fix I tested locally:
# baseAction.py, in mapping_vect_auth_keys
"_shunt_p": "shunt",
"_shunt_q": "shunt",
"_shunt_bus": "shunt",It also needs bounds for the bus in GymActionSpace._fill_dict_act_space. Otherwise the sampled buses are random int32 values and the action is ambiguous:
elif attr_nm == "_set_topo_vect" or attr_nm == "_shunt_bus":
my_type = type(self)._BoxType(low=-1,
high=act_cls.n_busbar_per_sub,
shape=shape, dtype=dt)With both changes, GymEnv(env).action_space has the keys shunt_bus, shunt_p and shunt_q, and a sampled action steps without being ambiguous or illegal. The existing gym test modules (test_gymnasium_compat, test_issue_665, test_alert_gym_compat, ...) still pass with it. This change also adds the three keys for existing CompleteAction gym users, so it probably deserves its own line in the CHANGELOG.
Generated by Claude Code
There was a problem hiding this comment.
Thanks, applied your fix. shunt_bus is now bounded between -1 and n_busbar_per_sub. CHANGELOG entry added.
| self._aux_affect_shunt(values, "_shunt_p", "shunt_p") | ||
|
|
||
| @property | ||
| def shunt_q(self) -> np.ndarray: |
There was a problem hiding this comment.
🤖 From Claude (Claude Opus 5.5) · Severity: low (cosmetic)
print(act) for an action that only changes shunts currently reads like a do-nothing action, because __str__ (and impact_on_objects) have no shunt section:
This action will:
- NOT change anything to the injections
- NOT perform any redispatching action
- NOT modify any storage capacity
- NOT perform any curtailment
- NOT force any line status
...
Now that shunts are an agent lever, it would help users to see them. Here is a sketch for __str__, right after the curtailment block, that I tested locally:
# shunts (only printed when the action modifies them, so that the output is unchanged otherwise)
if type(self).shunts_data_available and self._modif_shunt:
res.append("\t - Modify the shunts in the following way:")
for sh_id, name_ in enumerate(type(self).name_shunt):
if self._private_shunt_p is not None and np.isfinite(self._private_shunt_p[sh_id]):
res.append(f'\t \t - Set the active power of shunt "{name_}" to {self._private_shunt_p[sh_id]:.2f} MW')
if self._private_shunt_q is not None and np.isfinite(self._private_shunt_q[sh_id]):
res.append(f'\t \t - Set the reactive power of shunt "{name_}" to {self._private_shunt_q[sh_id]:.2f} MVAr')
if self._private_shunt_bus is not None and self._private_shunt_bus[sh_id] == -1:
res.append(f'\t \t - Disconnect shunt "{name_}"')
elif self._private_shunt_bus is not None and self._private_shunt_bus[sh_id] > 0:
res.append(f'\t \t - Connect shunt "{name_}" to busbar {self._private_shunt_bus[sh_id]}')It prints, for example:
- Modify the shunts in the following way:
- Set the reactive power of shunt "shunt_8_0" to -25.00 MVAr
- Connect shunt "shunt_8_0" to busbar 1
It only adds lines when the action modifies shunts, so the tests that compare the printed text exactly (test_Action, test_Storage, test_Curtailment, test_alert_obs_act) still pass. Totally optional for this PR.
Generated by Claude Code
There was a problem hiding this comment.
shunt changes are now shown, only when the action actually modifies a shunt, so other actions print exactly as before.
Fixes from the review of the shunt control PR: - PandaPowerBackend: changing the bus of only some of the shunts no longer raises a ValueError (the mask had the wrong shape) - the shunt_p, shunt_q and shunt_bus getters return an empty vector when the backend has no shunt data, instead of raising a TypeError - BoxGymObsSpace.to_gym skips the attributes that have no element - the _shunt_* attributes map to the "shunt" key, so the default gym action space now contains the shunts, with shunt_bus bounded between -1 and n_busbar_per_sub - comparing two actions now looks at the shunt bus of both of them - setting a shunt resets the cached vector, so to_vect() is up to date - print(act) shows the shunt modifications - clearer error message when a wrong shunt id is given - type hints on the shunt setters - document that sampling does not cover the shunts yet, and that agents should use ShuntAction rather than CompleteAction Signed-off-by: Mohsen Dastpak <moh.dastpak@gmail.com>
|
Hi Benjamin, |
Summary
Makes the shunts usable as a control lever, which is needed for voltage control studies. The shunt fields already existed in the action vector but could only be set through the
"shunt"dictionary key; there was no property API, no action classrestricted to them and no gym support.
Changes
BaseAction: newshunt_p,shunt_q,shunt_busproperties and setters, following thesame pattern as
redispatch/set_bus(accepted inputs, read-only getters, rollback andAmbiguousActionon invalid input,IllegalActionwhen the backend has no shunt data orthe action type does not allow
"shunt").grid2op.Action.ShuntAction: an action that can only modify the shunts(
authorized_keys = {"shunt"}).PlayableActionforbids shunts andCompleteActionalso allows topology / redispatch / injections, so neither isolates shunt control.
BoxGymActSpace:shunt_p,shunt_q,shunt_buskeys (not part of the default list,they must be requested explicitly).
BoxGymObsSpace:_shunt_p,_shunt_q,_shunt_v,_shunt_buskeys.docs/user/action.rst,docs/gym.rst) and CHANGELOG under 1.12.7.Scope and limitations
shunt_q(andshunt_p) is a real-valued setpoint inMVAr (MW) per shunt, written as is to the backend. Discrete shunt sections (switched banks
with a number of steps, i.e. pandapower's
step/max_step) are not modelled: grid2ophas no notion of a section count, and this PR does not add one. Users who need stepped banks
can build a discrete action set on top of it (one action per section level, each one setting
shunt_qtolevel * q_per_step).PandaPowerBackend, pandapower multipliesq_mvarby the shuntstep, so on a gridwhere a shunt has
step != 1the setpoint is applied per section. This is existing backendbehaviour, unchanged here.
shunt_*action keys are unbounded (shunt ratings are not part of the griddescription), so they should be rescaled with
multiply/add.DiscreteActSpace/MultiDiscreteActSpacedo not enumerate shunt actions.could be a follow-up.
Tests
grid2op/tests/test_shunt_action.py(18 tests): properties, dict/property equivalence, inputrollback, voltage effect of a capacitive/inductive setpoint,
ShuntActionkey restrictions,vector round-trip, sampling, stepping, and the gym action/observation spaces.
The action, observation, gym-compat and backend test modules pass locally. Three failures
also happen on unmodified
dev_1.12.7on Windows and are unrelated to this PR:test_chain_converter(defaultgym and gymnasium, hardcoded RNG values) andtest_alert_gym_compat.test_print_alert(string format).Backward compatibility
Additive only: no change to the action vector layout, existing action classes or default
gym spaces.