Skip to content

Add LookaheadLineOpponent and an independent_timing option for WeightedRandomOpponent - #795

Open
prawalpokharel wants to merge 1 commit into
Grid2op:dev_1.12.7from
prawalpokharel:paired-opponent-timing
Open

prawalpokharel wants to merge 1 commit into
Grid2op:dev_1.12.7from
prawalpokharel:paired-opponent-timing

Conversation

@prawalpokharel

Copy link
Copy Markdown
added removed
Python (grid2op package) +159 -5
Tests (grid2op/tests) +217 -0
Docs + changelog + notebooks +10 -0
total +386 -5

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

  • WeightedRandomOpponent accepts independent_timing in kwargs_opponent (default False). When it is True, 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.
  • The line choice in WeightedRandomOpponent.attack moves into a _choose_attack(observation, status) method, so a subclass only has to override that.
  • New LookaheadLineOpponent, which overrides _choose_attack. For each connected attackable line it simulates the disconnection with obs.get_simulator(), on the grid state of the current observation, and attacks the line that gives the highest max rho. 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 ignores rho_normalization.
  • The simulator runs once per candidate, only at the step where an attack starts. These power flows are not added to env.nb_highres_called. If the observation has no simulator (forecasts deactivated, or a backend that cannot be copied), the opponent raises an OpponentError that says so.
  • One paragraph in docs/user/opponent.rst, after the "oracle opponent" part.

Why

In the comparison described in #793 (simulated week-long episodes on l2rpn_case14_sandbox and l2rpn_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 in docs/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

  • New test_LookaheadLineOpponent.py (9 tests): a weighted-random and a lookahead opponent with independent_timing=True attack 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.
  • With default arguments, WeightedRandomOpponent attacked the same lines at the same steps as on dev_1.12.7 in 20 seeded episodes of up to 600 steps on a custom 14-bus setup, and in 20 on the bundled test copy of l2rpn_neurips_2020_track1.
  • I did not run the full CI suite.

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)
@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@BDonnot

BDonnot commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

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 BDonnot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_attack is a sensible extension point. You were careful that the default WeightedRandomOpponent makes 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:

  1. 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.
  2. lookaheadLineOpponent.py:91: a missing simulator crashes env.step in the middle of the step, possibly hundreds of steps in. It would be better to detect this at init / reset.
  3. lookaheadLineOpponent.py:106: a converged=False that doesn't come from the attack (a redispatch adjustment failure in the simulator) makes all candidates tie at inf, so the first line always wins.
  4. lookaheadLineOpponent.py:109: NaN in rho breaks the comparison.
  5. lookaheadLineOpponent.py:86: the ranking uses the state of step t, while the attack hits the grid of step t+1 (env_action / agent_action are available but not used). It's a design question, but it's worth settling now because it affects the signature of the _choose_attack hook.
  6. lookaheadLineOpponent.py:105: cost. Each evaluation makes N+1 backend copies and N+1 power flows.
  7. lookaheadLineOpponent.py:99: overwriting the private _highres_sim_counter. It works, but it's fragile. Better to support it in get_simulator.
  8. lookaheadLineOpponent.py:76: type hints are missing on the new public init, and a user-given rho_normalization is 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_attack hook is a better shape than putting everything into WeightedRandomOpponent, 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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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(), when previous_fails is True (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 a self._last_choice attribute, reset in reset() 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 when budget obviously 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 returns None). 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

Comment on lines +91 to +95
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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_env is the env, so you can look at whether it has an observation env / forecasts enabled. Raise the OpponentError there, at make() time. If deactivate_forecast() can be called after make(), also re-check in reset(), which runs at every env.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

Comment on lines +106 to +107
if not result.converged or result.current_obs is None:
score = np.inf

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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" predict with 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 current rho of the candidates) instead of ranking by inf.
  • And/or only count a candidate as inf when the failure is a power flow divergence (look at result.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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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"]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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_action and env_action to 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_action and pass them as simulator.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 a PlayableAction, the attack a PowerlineSetAction).

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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 a Simulator (one backend copy) and runs set_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

Comment on lines +96 to +99
# 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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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 the Simulator class;
  • it relies on get_simulator() already undoing its own count, which it does by writing the name-mangled _HighResSimCounter__nb_highres_called;
  • the HighResSimCounter import 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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants