Differentiable powerflow (pytorch)

A batch of powerflows, differentiable with respect to its injections, as a pytorch operation: a loss computed on the results of thousands of AC powerflows can be back-propagated to the loads and generators that produced them.

import torch
from lightsim2grid.network import init_from_pandapower
from lightsim2grid.differentiable import BatchCPUPowerFlow

grid = init_from_pandapower(some_pandapower_net)
pf = BatchCPUPowerFlow.init_from_grid(grid, nb_thread=8)

load_p = torch.tensor(..., requires_grad=True)    # (n_scenarios, n_load), MW
V = pf(load_p=load_p)                             # complex (n_scenarios, n_bus)

loss = pf.compute_flows(V).i_or_a.relu().sum()    # eg an overload penalty
loss.backward()
load_p.grad                                       # (n_scenarios, n_load)

pytorch is not a dependency of lightsim2grid: this subpackage is the only thing that needs it, and it is never imported by import lightsim2grid. Install it with pip install lightsim2grid[torch], or just pip install torch.

What is differentiable

Inputs are (n_scenarios, n_elements) tensors; None means “the grid’s own value, in every row”. Row i is one independent scenario, with its own injections and its own set of disconnected elements.

input

meaning

gradient

load_p

active load, MW

yes

load_q

reactive load, MVAr

yes

gen_p

generator active setpoint, MW

yes

sgen_p

static generator active power, MW

yes

gen_v

generator voltage setpoint, pu

not yet [1]

line_status

True = connected

no (discrete)

trafo_status

True = connected

no (discrete)

gen_status

True = connected

no (discrete)

shunt_status

True = connected

no (discrete)

load_status

True = connected

no (discrete)

The statuses follow grid2op’s convention (True means connected), and a row that trips a generator gets the whole treatment the C++ already implements: the lost MW go to the slack, the distributed slack is re-weighted without the machine, and a bus whose last voltage-regulating generator is gone becomes PQ for that row. A tripped shunt leaves the row’s admittance matrix, a tripped load its injection; an element a row disconnects has no gradient in that row (its value there changes nothing).

Why it is not expensive

The gradient comes from the adjoint method (the implicit function theorem), not from differentiating the Newton-Raphson iterations. Each row costs one transposed solve on top of the forward – and that cost does not depend on how many inputs are being differentiated, nor on how wide V is.

Two things make it cheap here, both of them properties the batch algorithms already had:

  • every row of a batch shares one Jacobian sparsity pattern, so the whole batch keeps one symbolic factorization;

  • KLU answers the transposed system out of the factorization of \(J\) itself (klu_tsolve), so no transposed matrix is ever built.

The price is memory: the converged Jacobian of every row is kept, which is n_scenarios * nnz(J) floats. On a large grid with a large batch that is gigabytes – BatchCPUPowerFlow.adjoint_memory_bytes() reports it, and it is worth reading before scaling a batch up.

Rows that fail

A row that did not converge, or that a contingency islanded, comes back as NaN rather than as zeros – zeros are a plausible-looking voltage, NaN is not – and its gradient is zero. BatchCPUPowerFlow.converged() says which rows those are, so a loss can mask them out.

Detailed documentation

Reverse-mode differentiation of a batch of powerflows, for pytorch.

Not imported by lightsim2grid itself: torch is an optional dependency, so this subpackage is reached explicitly.

from lightsim2grid.differentiable import BatchCPUPowerFlow

Classes:

BatchCPUPowerFlow(sweep, grid, *[, ...])

A batch of AC powerflows, differentiable with respect to its injections.

BranchFlows(p_or_mw, q_or_mvar, p_ex_mw, ...)

what compute_branch_flows() returns, all of shape (n_scenarios, n_branch) with the powerlines first and the transformers after, in grid order.

Functions:

compute_branch_flows(V, y_11, y_12, y_21, ...)

Flows at both ends of every branch, differentiable with respect to V.

class lightsim2grid.differentiable.BatchCPUPowerFlow(sweep, grid, *, handle_disconnected_grid=False, max_iter=10, tol=1e-08, v_init=None)[source]

A batch of AC powerflows, differentiable with respect to its injections.

Build it with init_from_grid(), then call it like a function (or use forward()). See the module docstring.

Methods:

adjoint_memory_bytes()

Bytes the kept Jacobians of the last call occupy.

compute_flows(V[, connected])

Branch flows from V, differentiable -- powerlines then transformers.

converged()

(n_scenarios,) bool: whether each row's powerflow converged.

forward([load_p, load_q, gen_p, sgen_p, ...])

Solve one scenario per row; returns complex V of shape (n_scenarios, n_bus) in per unit, in grid bus numbering (the same numbering the grid's own accessors use). The inputs::.

init_from_grid(grid, *[, nb_thread, ...])

Build from an LSGrid.

Attributes:

sweep

timers, limit violations, the adjoint's own linear-solver counters).

adjoint_memory_bytes()[source]

Bytes the kept Jacobians of the last call occupy. Grows as n_scenarios * nnz(J): worth watching before scaling a batch up.

compute_flows(V, connected=None)[source]

Branch flows from V, differentiable – powerlines then transformers.

Returns a BranchFlows. By default a branch is taken as connected where the last forward() had it connected; pass connected (n_scen, n_branch) to say otherwise.

converged()[source]

(n_scenarios,) bool: whether each row’s powerflow converged. A row that did not is NaN in V and gets a zero gradient.

forward(load_p=None, load_q=None, gen_p=None, sgen_p=None, gen_v=None, line_status=None, trafo_status=None, gen_status=None, shunt_status=None, load_status=None)[source]

Solve one scenario per row; returns complex V of shape (n_scenarios, n_bus) in per unit, in grid bus numbering (the same numbering the grid’s own accessors use). The inputs:

load_p, load_q : (n_scen, n_load) MW / MVAr        differentiable
gen_p          : (n_scen, n_gen)  MW               differentiable
sgen_p         : (n_scen, n_sgen) MW               differentiable
gen_v          : (n_scen, n_gen)  vm_pu            differentiable; generators on
                                                   one bus must agree, see above
line_status    : (n_scen, n_line)  bool, True = connected
trafo_status   : (n_scen, n_trafo) bool, True = connected
gen_status     : (n_scen, n_gen)   bool, True = connected
shunt_status   : (n_scen, n_shunt) bool, True = connected
load_status    : (n_scen, n_load)  bool, True = connected; a disconnected
                                   load's power leaves the row, so its
                                   load_p / load_q gradient there is 0

None means “whatever the grid itself says”, in every row. At least one input must be given: it is what fixes the number of scenarios.

classmethod init_from_grid(grid, *, nb_thread=1, handle_disconnected_grid=False, algorithm=None, max_iter=10, tol=1e-08, v_init=None, init_from_n_powerflow=False)[source]

Build from an LSGrid.

The grid does not have to be solved first: every batch begins with its own “n” warm-up powerflow. algorithm defaults to the fastest Newton-Raphson the build has (KLU when it was compiled in); it must be one of the AC NR family, since the adjoint is a solve against that Jacobian.

property sweep

timers, limit violations, the adjoint’s own linear-solver counters).

Type:

The underlying ScenarioSweepCPP (escape hatch

class lightsim2grid.differentiable.BranchFlows(p_or_mw, q_or_mvar, p_ex_mw, q_ex_mvar, i_or_a, i_ex_a)

what compute_branch_flows() returns, all of shape (n_scenarios, n_branch) with the powerlines first and the transformers after, in grid order. “or” / “ex” are grid2op’s names for the two ends: the origin side (side 1, the high voltage side of a transformer) and the extremity side.

Attributes:

i_ex_a

Alias for field number 5

i_or_a

Alias for field number 4

p_ex_mw

Alias for field number 2

p_or_mw

Alias for field number 0

q_ex_mvar

Alias for field number 3

q_or_mvar

Alias for field number 1

i_ex_a

Alias for field number 5

i_or_a

Alias for field number 4

p_ex_mw

Alias for field number 2

p_or_mw

Alias for field number 0

q_ex_mvar

Alias for field number 3

q_or_mvar

Alias for field number 1

lightsim2grid.differentiable.compute_branch_flows(V, y_11, y_12, y_21, y_22, bus_or, bus_ex, bus_vn_kv, sn_mva, connected=None)[source]

Flows at both ends of every branch, differentiable with respect to V.

V : complex (n_scenarios, n_bus), per unit, in GRID bus numbering y_* : complex (n_branch,), the branch’s Kron-reduced admittances bus_or / bus_ex : int (n_branch,), the grid bus at each end bus_vn_kv : real (n_bus,), nominal voltage of each bus connected : bool (n_scenarios, n_branch) or None (everything connected)