Repository navigation
Add LookaheadLineOpponent and an independent_timing option for WeightedRandomOpponent - #795
prawalpokharel wants to merge 1 commit into
Conversation
WeightedRandomOpponent can now draw its attack times from a random generator of their own (independent_timing=True), so two opponents that only differ in how they choose the line attack at the same steps of a seeded episode. The default keeps one generator for both, as before. The line choice moves into a _choose_attack method that subclasses can override. LookaheadLineOpponent uses that hook: it disconnects the attackable line whose simulated disconnection (obs.get_simulator(), on the grid state of the current observation) gives the highest maximum usage rate. A power flow that does not converge counts as the strongest attack. Its power flows are not added to the agent's simulation count, and it raises an OpponentError when the observation has no simulator. Signed-off-by: Prawal Pokharel <57414987+prawalpokharel@users.noreply.github.com> Assisted-by: Claude Code (claude-opus-5-5)
Not up to standards ⛔
|
|
Hello, I asked an instance of Claude to do a review, the comments will follow. Do not hesitate to answer them or disagree with it. Benjamin |
BDonnot
left a comment
There was a problem hiding this comment.
Hi @prawalpokharel, and welcome to grid2op! 👋
I'm Claude Code, an AI coding assistant. A maintainer asked me to review this PR, and these comments were written by me, not typed by them.
Thanks a lot for this contribution. It's a well-prepared first PR:
- The PR description is excellent. It links the motivation (#793), reports results honestly, including the case where plain betweenness beats the lookahead, and states what you did and didn't run.
- Moving the line choice into
_choose_attackis a sensible extension point. You were careful that the defaultWeightedRandomOpponentmakes exactly the same random draws as before, and you checked it on seeded episodes. That's the kind of care that makes a change easy to accept. - Using stub simulators in the tests (ties, divergence, no RNG use) is a good way to test the decision logic without depending on the power flow numbers.
That said, there are a few things to address before this can be merged. I've left them as inline comments. In rough order of importance:
weightedRandomOpponent.py:184: the lookahead reruns at every step while the opponent lacks budget. An attack rejected for budget leaves_next_attack_time <= 0, so_choose_attack(and all its simulations) runs again at each step until the budget is enough. I counted 56 calls for a single attack in one setup. This is the main blocker.lookaheadLineOpponent.py:91: a missing simulator crashesenv.stepin the middle of the step, possibly hundreds of steps in. It would be better to detect this atinit/reset.lookaheadLineOpponent.py:106: aconverged=Falsethat doesn't come from the attack (a redispatch adjustment failure in the simulator) makes all candidates tie atinf, so the first line always wins.lookaheadLineOpponent.py:109: NaN inrhobreaks the comparison.lookaheadLineOpponent.py:86: the ranking uses the state of step t, while the attack hits the grid of step t+1 (env_action/agent_actionare available but not used). It's a design question, but it's worth settling now because it affects the signature of the_choose_attackhook.lookaheadLineOpponent.py:105: cost. Each evaluation makes N+1 backend copies and N+1 power flows.lookaheadLineOpponent.py:99: overwriting the private_highres_sim_counter. It works, but it's fragile. Better to support it inget_simulator.lookaheadLineOpponent.py:76: type hints are missing on the new publicinit, and a user-givenrho_normalizationis dropped without a warning.
Each comment suggests one or more fixes. They are suggestions, not the only acceptable answer, so feel free to push back if you see it differently. For 1 to 4, a small regression test each would be great (your _stub_simulator helper already does most of the work).
Some housekeeping:
- On your question in the description: I think the subclass plus
_choose_attackhook is a better shape than putting everything intoWeightedRandomOpponent, so no need to change that. - DCO is green 👍. Codacy reports "action required"; I didn't look at its details, but it's worth a glance. The CHANGELOG conflict with #794 that you mentioned is fine, whichever PR is merged second can rebase.
Thanks again, and looking forward to the next iteration!
Generated by Claude Code
| if not status.sum(): | ||
| return None, 0 | ||
|
|
||
| attack = self._choose_attack(observation, status) |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
_choose_attack runs again at every step while the opponent is short of budget. This is the most important point in the review.
OpponentSpace.attack only checks the cost after opponent.attack() has returned (duration * self.compute_budget(attack) > final_budget → attack = None, previous_fails = True). After a rejection, tell_attack_continues isn't called, so _next_attack_time stays <= 0. On the next step we arrive here again and choose a line again, and so on until the budget is enough.
The base class already worked this way, but there it only cost one choice() draw per step, so nobody noticed. With LookaheadLineOpponent, every one of those steps means a simulator build plus N predict(do_copy=True) calls. In a quick reproduction on l2rpn_case14_sandbox (opponent_init_budget=0, opponent_budget_per_ts=0.1, duration 6, attack_period=12, the 8 lines from your test), _choose_attack ran 56 times (steps 5 to 60) for a single attack. This also means the class docstring is wrong where it says "The simulator is only used at the step where an attack starts".
Some ways to fix it, roughly from least to most invasive:
- In
attack(), whenprevious_failsisTrue(the previous step's attack was rejected), reuse the attack chosen last time if its line is still connected, and skip_choose_attack. That needs aself._last_choiceattribute, reset inreset()and copied in_custom_deepcopy_for_copy. The choice then reflects the grid when the attack time came. I think that fits "decide at the attack time" well, but it's a design decision, so please say so in the docstring. - Alternatively, let
attack()skip the choice whenbudgetobviously can't pay for any attack. The catch is that the opponent doesn't know the cost function (it belongs to the budget class) or the duration (it returnsNone). So this one needs more plumbing, and I'd go with the first option.
Either way, a regression test would be valuable: a low opponent_init_budget / opponent_budget_per_ts, and _choose_attack wrapped with unittest.mock.patch.object(..., wraps=...) to count its calls per attack. With the default independent_timing=False, please also check that the base WeightedRandomOpponent still makes exactly the same random draws as before. Caching the choice would change its draws too, so you may want to restrict the caching to the subclass, or to independent_timing=True.
Generated by Claude Code
| try: | ||
| simulator = observation.get_simulator() | ||
| except BaseObservationError as exc: | ||
| raise OpponentError("LookaheadLineOpponent needs `obs.get_simulator()`, which is not available here " | ||
| "(are the forecasts deactivated, or is the backend impossible to copy?)") from exc |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
Thanks for the clear error message, and for documenting the deactivate_forecast() / GymEnv case in the docstring. It would still be better to detect the problem earlier, because of where this error is raised.
_choose_attack runs inside BaseEnv.step → _aux_handle_attack → OpponentSpace.attack. That happens after _update_actions() has already moved the chronics forward, and nothing on the way catches the exception. So a misconfigured env runs normally until the first attack time, which can be hundreds of steps in, then env.step raises and leaves the env half-stepped. A Runner or an RL training loop just crashes. Elsewhere in grid2op the rule is that step doesn't raise and problems are reported in info["exception"], so this would be a surprise for users.
Possible directions:
- Check in
init()that the simulator is available:partial_envis the env, so you can look at whether it has an observation env / forecasts enabled. Raise theOpponentErrorthere, atmake()time. Ifdeactivate_forecast()can be called aftermake(), also re-check inreset(), which runs at everyenv.reset(). - And/or, at attack time, fall back to a documented behaviour (no attack, or the parent's weighted random choice) with a
warnings.warn, instead of raising mid-step.
The current test_clear_error_without_simulator calls _choose_attack directly. A test that goes through env.reset() / env.step() would cover what the user actually sees.
Generated by Claude Code
| if not result.converged or result.current_obs is None: | ||
| score = np.inf |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
Treating a diverging power flow as the strongest attack makes sense for a line disconnection. However, converged=False doesn't always come from the power flow. Simulator.predict also returns converged=False (with an InvalidRedispatching error) when its own generator adjustment (_adjust_controlable_gen, an SLSQP solve) fails. That can happen as soon as the agent has redispatched (target_dispatch.sum() != 0), and the failure doesn't depend on which line is disconnected. The same goes for a base state that doesn't converge in the simulator to begin with.
In those cases every candidate gets inf, they all tie, and the first line in lines_attacked is always chosen, whatever its real impact is. That would quietly bias your comparison results.
Suggestions:
- Run one "reference"
predictwith a do-nothing action first. If it doesn't converge either, the failure doesn't come from the attacks, so fall back to something sensible (for example the parent's choice, or the currentrhoof the candidates) instead of ranking byinf. - And/or only count a candidate as
infwhen the failure is a power flow divergence (look atresult.error/ the exception type), not a redispatch infeasibility.
A stub-based test like your _stub_simulator covers this easily: every candidate returns converged=False, and the test checks that the result isn't simply "first line".
Generated by Claude Code
| if not result.converged or result.current_obs is None: | ||
| score = np.inf | ||
| else: | ||
| score = float(np.max(result.current_obs.rho)) |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
A small but easy-to-miss one: np.max propagates NaN. If a backend reports NaN flows for some line after a disconnection (for example an element isolated in an otherwise converged power flow), score is nan. Then score > best_score + tol is False for every comparison:
- if the first candidate is NaN, it becomes
best_attack, and no later candidate can ever replace it; - if a later candidate is NaN, it is silently ignored.
Using np.nanmax, or mapping a non-finite rho to np.inf (a NaN flow is a strong sign the attack broke something), would make this robust. A one-line stub test with rho=np.full(n_line, np.nan) for the first candidate would pin it down.
Generated by Claude Code
| independent_timing=independent_timing, | ||
| **kwargs) | ||
|
|
||
| def _choose_attack(self, observation: "BaseObservation", status: np.ndarray) -> Optional["BaseAction"]: |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
This is a question about modelling more than a bug, but I think it matters for the results you report in #793. The candidates are ranked on the state of observation t, while the attack is applied on the grid of step t+1.
_aux_handle_attack runs after _update_actions(). env_action (that is, env._env_modification, which attack() receives but doesn't pass on) already holds the t+1 load_p, load_q, prod_p, prod_v and maintenance. The agent's action of the same step (agent_action) is applied together with the attack. The opponent ignores both, so when loads ramp fast, when a maintenance starts at t+1, or when the agent's action changes the topology, the line chosen can differ from the most damaging line on the grid that is actually attacked.
The opponent API is designed to see t+1. The attack docstring even says "it can view time step t+1", so using it would be legitimate. Some options:
- Pass
agent_actionandenv_actionto the hook, for example_choose_attack(observation, status, agent_action, env_action). The base implementation can simply ignore them. Doing this now costs almost nothing, while changing the hook signature after release is painful. - In the lookahead, read the t+1 injections from
env_actionand pass them assimulator.predict(act=attack + agent_action, new_gen_p=..., new_load_p=..., new_load_q=...). Check that combining the actions doesn't fail on the action class (the agent action is aPlayableAction, the attack aPowerlineSetAction).
If you prefer to keep the "state of observation t" design, that's a defensible choice too. In that case, please say so explicitly in the class docstring and the changelog (you already mention "on the grid state of the current observation", which is good), and give the reason.
Generated by Claude Code
| best_score = -np.inf | ||
| for position in np.flatnonzero(status): | ||
| attack = self._attacks[position] | ||
| result = simulator.predict(act=attack, do_copy=True) |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
About performance: each attack evaluation does N+1 backend copies and N+1 power flows for N connected candidates:
obs.get_simulator()builds aSimulator(one backend copy) and runsset_state, which does one power flow whose result is never used here;- then every
predict(..., do_copy=True)deep-copies the backend again before running its own power flow.
With PandaPowerBackend, a deepcopy of the pandapower net often costs more than the power flow itself. Together with the budget-rejection loop (see my comment on weightedRandomOpponent.py), this can repeat at every step.
Since the simulator is only used inside this method, you don't need to protect it from modification. One idea: build it once and call predict(do_copy=False) for each candidate, restoring the state between candidates (for example with simulator.set_state(observation, do_powerflow=False) or an equivalent, so check what set_state supports and what do_copy=False actually mutates). Another: keep a single "pristine" simulator and copy() it per candidate, which at least removes the extra power flow.
A small timing check (per-attack cost before/after, on l2rpn_case14_sandbox) in the PR description would be enough. No benchmark test is needed.
Generated by Claude Code
| # lazy import to prevent circular references | ||
| from grid2op.Observation.highresSimCounter import HighResSimCounter | ||
| # the opponent's power flows should not count as simulations made by the agent | ||
| simulator._highres_sim_counter = HighResSimCounter() |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
You're right that the opponent's power flows must not count in env.nb_highres_called, and test_opponent_simulations_are_not_counted_as_the_agent_ones checks that nicely. The way it's done is fragile, though:
- it overwrites a private attribute (
simulator._highres_sim_counter) from outside theSimulatorclass; - it relies on
get_simulator()already undoing its own count, which it does by writing the name-mangled_HighResSimCounter__nb_highres_called; - the
HighResSimCounterimport runs on every call.
If Simulator ever changes how it stores or shares its counter (copy() already shares it, for example), the opponent's simulations will silently be counted again.
The Simulator constructor already accepts a counter (Simulator(backend=..., _highres_sim_counter=...)). It would be cleaner to support this where the counter is set: for example an optional argument on BaseObservation.get_simulator(...) that gives the simulator its own counter, or a small public helper for "a simulator that is not counted". That also helps other users who call get_simulator from outside the agent (custom rewards, for example). If you'd rather not touch BaseObservation in this PR, a comment explaining why the override is needed and a link to a follow-up issue would be OK for now. Moving the import to module level would also help, unless it really creates a circular import.
Generated by Claude Code
|
|
||
| _TIE_TOL = 1e-9 | ||
|
|
||
| def init(self, partial_env, lines_attacked=(), attack_period=12 * 24, independent_timing=False, **kwargs): |
There was a problem hiding this comment.
(Claude Code, the AI assistant reviewing this PR for a maintainer.)
A minor style point: the project asks for type hints on new public code, and _choose_attack already has them. Could you add them to this init too? For example partial_env: "BaseEnv", lines_attacked: Sequence[str] = (), attack_period: int = 12 * 24, independent_timing: bool = False, and -> None. Please also hint the new independent_timing parameter in WeightedRandomOpponent.init. You don't need to annotate the rest of that older method.
A related detail: here init silently drops a user-provided rho_normalization. Since the docstring says it's ignored, a warnings.warn when it's passed would help people who copy a WeightedRandomOpponent config and expect it to have an effect.
Generated by Claude Code
Follow-up to #793. I said there that I would wait for your view before opening a PR. I'm opening it now so the code can be read next to the proposal. If you'd prefer a different shape, for example everything inside
WeightedRandomOpponent, I'll change it, or close this.This PR and #794 both add a line to the 1.12.7 section of
CHANGELOG.rst, so whichever is merged second will need a one-line rebase.What this PR does
WeightedRandomOpponentacceptsindependent_timinginkwargs_opponent(defaultFalse). When it isTrue, the attack times come from their own random generator, seeded from the opponent's generator at each reset. Two opponents that differ only in how they choose the line then attack at the same steps of a seeded episode, as long as each still has a connected attackable line when its attack time comes. With the default, the opponent makes exactly the same random draws as before.WeightedRandomOpponent.attackmoves into a_choose_attack(observation, status)method, so a subclass only has to override that.LookaheadLineOpponent, which overrides_choose_attack. For each connected attackable line it simulates the disconnection withobs.get_simulator(), on the grid state of the current observation, and attacks the line that gives the highest maxrho. A power flow that does not converge counts as the strongest attack, and near ties go to the line listed first. It uses no random number to choose, and it ignoresrho_normalization.env.nb_highres_called. If the observation has no simulator (forecasts deactivated, or a backend that cannot be copied), the opponent raises anOpponentErrorthat says so.docs/user/opponent.rst, after the "oracle opponent" part.Why
In the comparison described in #793 (simulated week-long episodes on
l2rpn_case14_sandboxandl2rpn_neurips_2020_track1_small, with a do-nothing and a reconnecting agent), the lookahead was the strongest of the eight line-choice rules on both grids with both agents: about 12 h of survival on the 14-bus grid and 13 to 14 h on the NeurIPS grid, out of a week. It is not always the strongest, though. In an extra 14-bus run restricted to the six lines of the case14 example indocs/user/opponent.rst, plain betweenness beat it. I reran 40 of those lookahead episodes (10 per grid and agent) with this class and got the same attacks and survival.Tests
test_LookaheadLineOpponent.py(9 tests): a weighted-random and a lookahead opponent withindependent_timing=Trueattack at the same steps; the opponent's simulations are not counted as the agent's;env.copy()keeps the timing state; the chosen line matches a direct simulator comparison; disconnected lines are skipped; a power flow that does not converge wins; near ties go to the first listed line; choosing uses no random number; a clear error without a simulator.python -m unittest grid2op.tests.test_Opponent: 41 tests pass.WeightedRandomOpponentattacked the same lines at the same steps as ondev_1.12.7in 20 seeded episodes of up to 600 steps on a custom 14-bus setup, and in 20 on the bundled test copy ofl2rpn_neurips_2020_track1.