# This Notebook will develop how to build an Agent and assess its performance.¶

Try me out interactively with:

Objective

This notebook will cover the basics of the information that can be retrieved about the state of the powergrid.

Examples of "expert agents" that can take actions based on some fixed rules, will be given for illustration purpose. More generic types of Agents, relying for example on machine learning / deep learning will be covered in the notebook 04_TrainingAnAgent.

This notebook will also cover the description of the Observation class, which is useful to take some actions.

Execute the cell below by removing the # character if you use google colab !

Cell will look like:

!pip install grid2op[optional]  # for use with google colab (grid2Op is not installed by default)


In [ ]:
# !pip install grid2op[optional]  # for use with google colab (grid2Op is not installed by default)

In [ ]:
import os
import sys
import numpy as np
import grid2op

In [ ]:
res = None
try:
except ModuleNotFoundError:
res


## I) Description of the observations¶

NB In this paragraph we will cover the observation class. For more information about it, we recommend to have a look at the official documentation, or here or in the Observations.py files for more information. Only basic concepts are detailed in this notebook.

### I.A) Getting an observation¶

An observation can be accessed by calling env.step(). The next cell is dedicated to creating an environment and getting an observation instance. We use the default rte_case14_realistic environment from Grid2Op framework.

In [ ]:
env = grid2op.make(test=True)
obs = env.reset()


obs now contains the initial state of the grid.

### I.B) Information contained in an Observation¶

In this notebook we will detail only the "CompleteObservation". Grid2Op allows to model different kinds of observations. For example, some observations could have incomplete data, or noisy data, etc. CompleteObservation gives the full state of the powergrid, without any noise. It's the default type of observation used.

#### a) Some of its attributes¶

An observation has calendar data (eg the time stamp of the observation):

In [ ]:
obs.year, obs.month, obs.day, obs.hour_of_day, obs.minute_of_hour, obs.day_of_week


It has some powergrid generic information (that are static: the same environment has always these attributes, that have always the same values, but of course different environments can have different values)

In [ ]:
print("Number of generators of the powergrid: {}".format(obs.n_gen))
print("Number of powerline of the powergrid: {}".format(obs.n_line))
print("Number of elements connected to each substations in the powergrid: {}".format(obs.sub_info))
print("Total number of elements: {}".format(obs.dim_topo))


It has some information about the generators (each generator can be viewed as a point in a 3-dimensional space)

In [ ]:
print("Generators active production: {}".format(obs.gen_p))
print("Generators reactive production: {}".format(obs.gen_q))
print("Generators voltage setpoint : {}".format(obs.gen_v))


It has some information about the loads (each load is a point in a 3-dimensional space, too)

In [ ]:
print("Loads active consumption: {}".format(obs.load_p))
print("Loads voltage (voltage magnitude of the bus to which it is connected) : {}".format(obs.load_v))


In this setting, a powerline can be viewed as a point in an 8-dimensional space:

• active flow
• reactive flow
• voltage magnitude
• current flow

for both its origin and its extremity.

For example, suppose the powerline line1 is connecting two node A and B. There are two separate values for the active flow on line1 : the active flow from A to B (origin) and the active flow from B to A (extremity).

These powerline features can be accessed with :

In [ ]:
print("Origin active flow: {}".format(obs.p_or))
print("Origin reactive flow: {}".format(obs.q_or))
print("Origin current flow: {}".format(obs.a_or))
print("Origin voltage (voltage magnitude to the bus to which the origin end is connected): {}".format(obs.v_or))
print("Extremity active flow: {}".format(obs.p_ex))
print("Extremity reactive flow: {}".format(obs.q_ex))
print("Extremity current flow: {}".format(obs.a_ex))
print("Extremity voltage (voltage magnitude to the bus to which the origin end is connected): {}".format(obs.v_ex))


Another powerline feature is the $\rho$ ratio, ie. for each powerline, the ratio between the current flow in the powerline and its thermal limit. It can be accessed with:

In [ ]:
obs.rho


The observation (obs) also stores information on the topology and the state of the powerline.

In [ ]:
obs.timestep_overflow # the number of timestep each of the powerline is in overflow (1 powerline per component)
obs.line_status # the status of each powerline: True connected, False disconnected
obs.topo_vect  # the topology vector the each element (generator, load, each end of a powerline) to which the object
# is connected: 1 = bus 1, 2 = bus 2.


In grid2op, all objects (end of a powerline, load or generator) can be either disconnected, connected to the first bus of its substation, or connected to the second bus of its substation.

topo_vect is the vector containing the connection information, it is part of the observation. If an object is disconnected, then its corresponding component in topo_vect will be -1. If it's connected to the first bus of its substation, its component will be 1 and if it's connected to the second bus, its component will be 2.

For example, if you want to know at which bus the "load 2" is connected, you can do:

In [ ]:
load_id = 2


Or alternatively

In [ ]:
obs.load_bus[load_id]


NB of course the obs.gen_bus, obs.line_or_bus, obs.line_ex_bus or obs.storage_bus are also defined.

#### b) Representation as "a graph"¶

The powergrid is a graph. This "topology vector" is an efficient (in term of memory and speed) way to represent this graph. Hopefully, some utilities functions in grid2op allows to build these graphs rapidly.

We say "these graphs" because "the" graph of the grid can mean different things. Yes, you have a lot of information whith something like:

In [ ]:
from grid2op.PlotGrid import PlotMatplot
plot_helper = PlotMatplot(env.observation_space)
_ = plot_helper.plot_obs(obs)


#### i) connectivity matrix¶

the connectivity matrix which has as many rows / columns as the number of elements in the powergrid (remember that an element is either an end of a powerline, or a generator or a load) and that tells if 2 elements are connected to one another or not:

\left\{ \begin{aligned} \text{conn mat}[i,j] = 0 & ~\text{element i and j are NOT connected to the same bus}\\ \text{conn mat}[i,j] = 1 & ~\text{element i and j are connected to the same bus, or i and j are both ends of the same powerline}\\ \end{aligned} \right.

NB If two objects are not connected at the same substation, they are necessarily not connected together, except if these elements are the two side of the same powerline.

In [ ]:
# if "as_csr_matrix" is set to True, then the result will be given as a csr scipy sparse matrix
mat = obs.connectivity_matrix(as_csr_matrix=False)
mat


And if you want to know to which object a given element is connected you can do the following (we take the exemple of trying to recover to which element load 5 is connected)

In [ ]:
load_id = 5
obs.grid_objects_types[which_connected,]


This will give you a matrix with as many rows as the number of elements that are connected to the element (in this case 5) with:

• the first column indicate the substation. All the objects connected to a given element necessarily belong to the same substation, in our example substation 8.
• the second column encodes for "load". If there is a "-1" it means the element is NOT a load, otherwise it gives the load. Here, looking at the last row, when can know that currently load 5 is... connected to load 5. It will always be the case, except if the element is disconnected of course.
• the third column encodes for "generator". In this case, all this column is "-1" it means the load 5 is not currently directly connected to a generator.
• fourth column encodes for "origin side of powerline". Here we see that our load 5 is connected to powerline (origin side) with ids 10, 11 and 19
• fifth column encodes for "extremity side of powerline". We can see that our load 5 is connecte to powerline (extremity side) 16
• finally last (sixth) column encodes for storage units. This load 5 is not directly connected to any storage unit here.

You can check that everything is consistent with the plot above.

- has always the same dimension, regardless of the topology of the powergrid
- binary matrix
- all elements are represented and easily accessible
- symmetric matrix



Drawbacks:

- do not contain any information regarding the flows, generations, loads, storage units etc.
- large matrix



#### ii) bus connectivity matrix¶

Another representation of the "graph" of the powergrid is through "bus-bus" matrix, that says if at least one powerline connect two bus together or not.

In grid2op this is called "bus_connectivity_matrix".

This bus connectivity matrix has as many rows / columns as the number of active buses of the powergrid. It should be understood as follows:

\left\{ \begin{aligned} \text{bus conn mat}[i,j] = 0 & ~\text{if no powerline connects bus i to bus j}\\ \text{bus conn mat}[i,j] = 1 & ~\text{if at least one powerline connects bus i to bus j (or i == j)}\\ \end{aligned} \right.
In [ ]:
obs.bus_connectivity_matrix(as_csr_matrix=False)


• "small" matrix
• binary matrix
• symmetric matrix

Drawbacks:

• do not contain any information regarding the flows, generations, loads, storage units etc.
• it's not easy to know which powerline connects which buses
• it's not easy to know which element is connected to which buses (though the obs.bus_connectivity_matrix(return_lines_index=True) might help in this case)
• its dimension changes: you can have 2, or 1 bus at any given substation.

#### iii) "flow bus" matrix¶

Finally, you can introduce informations about flows (eg label) on your graph.

This "flow bus matrix" has the following properties:

• like the above "bus connectivity matrix" it has as many rows / columns as the number of different bus on a power
• the diagonal coefficients are the power injected at this bus, which is defined at the sum of the generators connected at this bus minus the sum of the loads connected at this bus
• the non diagonal coefficient [i, j] (i different from j then) is the amount of power flowing from bus i to bus j.

In grid2op, you can do the following:

In [ ]:
mat, (load_bus, gen_bus, stor_bus, lor_bus, lex_bus) = obs.flow_bus_matrix(active_flow=True, as_csr_matrix=False)
mat, (load_bus, gen_bus, stor_bus, lor_bus, lex_bus) = obs.flow_bus_matrix(active_flow=True, as_csr_matrix=False)
mat


Let's dive a bit on the arguments there:

• mat is the flow bus matrix
• load_bus indicates for each load, to which bus it is connected
• gen_bus indicates for each generator, to which bus it is connected
• stor_bus indicates for each load, to which bus it is connected
• lor_bus indicates for each line (origin side), to which bus it is connected
• lex_bus indicates for each line (extremity side), to which bus it is connected

Let's take the same example as above with the load id 5.

In [ ]:
load_id = 5
line_id = lines_or_id[0]
print(f"It is connected to the bus id {this_load_bus} of the matrix")
print(f"And we can see the diagonal coefficient of the \"flow bus matrix\" "\
print(f"Also we can see that powerlines {lines_or_id} have their origin side connected at this bus.")
print(f"And powerlines {lines_ex_id} have their extremity side connected at this bus.")
print(f"And, for example, if we look at powerline {line_id}, that connects bus {lor_bus[line_id]} "\
f"to bus {lex_bus[line_id]} we can see that:")
print(f"The flow from bus {lor_bus[line_id]} to {lex_bus[line_id]} is "\
f"{mat[lor_bus[line_id], lex_bus[line_id]]:.2f}MW")
print(f"For information, the flow at the origin side of this line {line_id} is {obs.p_or[line_id]:.2f}MW. "\
f"And this is not a coincidence.")
print()
print(f"Also, we want to emphasize that this matrix is NOT symmetrical, for example:")
print(f"\t the power from bus {lor_bus[line_id]} to {lex_bus[line_id]} is "\
f"{mat[lor_bus[line_id], lex_bus[line_id]]:.5f} MW")
print(f"\t the power from bus {lex_bus[line_id]} to {lor_bus[line_id]} is "\
f"{mat[lex_bus[line_id], lor_bus[line_id]]:.5f} MW")


So you can see that the power from a bus to another is signed (if it's positive from 8 to 9 it means that the flow is going from 9 to 8: power is injected at bus 8 from bus 9)

And also, the two values (power injected at one side, from another) do not sum at 0. This is because there are losses on the grid, mainly due to Joule's effect.

• "small" matrix
• contain lots of information regarding the flows, generators, loads, storage units etc.

Drawbacks:

• it's not easy to know which powerline connects which buses, even though the "lor_bus", "lex_bus", "stor_bus" etc. can be used to retrieve it [bus in any case it will be agregated]
• it's not easy to know which elements are connected to which others
• its dimension changes: you can have 2, or 1 bus at any given substation.
• real number matrix
• non symmetric matrix

NB The power in alternative current contains two dimension called "active" and "reactive". We detailed here the example of the "active flow" matrix that is accessed with obs.flow_bus_matrix(active_flow=True) (active flows uses obs.p_or, obs.p_ex, obs.load_p, obs.gen_p and obs.storage_power). You can retrieve the "reactive flow" matrix with obs.flow_bus_matrix(active_flow=False) (reactive flows uses obs.q_or, obs.q_ex, obs.load_q, obs.gen_q and nothing for the storage reactive power).

#### iv) networkx graph¶

Lastly, the grid2op framework also offers the possibility to "convert" a given observation as a graph (representing as a networkx graph).

This graphs has the following properties:

• it counts as many nodes as the number of buses of the grid
• it counts less edges than the number of lines of the grid (two lines connecting the same buses are "merged" into one single edges)
• nodes have attributes:

• "p": the active power produced at this node (negative means the sum of power produce minus power absorbed is negative)
• "q": the reactive power produced at this node
• "v": the voltage magnitude at this node
• "cooldown": how much longer you need to wait before being able to merge / split or change this node
• edges have attributes too:

• "rho": the relative flow on this powerline
• "cooldown": the number of step you need to wait before being able to act on this powerline
• "status": whether this powerline is connected or not
• "thermal_limit": maximum flow allowed on the the powerline (this is the "a_or" flow)
• "timestep_overflow": number of time steps during which the powerline is on overflow
• "p_or": active power injected at this node at the "origin side".
• "p_ex": active power injected at this node at the "extremity side".
• "q_or": reactive power injected at this node at the "origin side".
• "q_ex": reactive power injected at this node at the "extremity side".
• "a_or": current flow injected at this node at the "origin side".
• "a_ex": current flow injected at this node at the "extremity side".

IMPORTANT NOTE the "origin" and "extremity" of the networkx graph is not necessarily the same as the one in grid2op. The "origin" side will always be the nodes with the lowest id. For example, if an edges connects the bus 6 to the bus 8, then the "origin" of this powerline is bus 6 (eg p_or of this edge is the power injected at bus 6) and the "extremity" side is bus 8.

An example is given in:

In [ ]:
import networkx
graph = obs.as_networkx()
graph


And you can use any networkx methods you want with this graph, for example, you can plot it

In [ ]:
networkx.draw_networkx(graph,
with_labels=False,
# I want to plot the "rho" value for edges
edge_color=[graph.edges[el]["rho"] for el in graph.edges],
# i use the position computed with grid2op
# NB: this code only works if the number of bus per substation is 1 !
pos=[plot_helper._grid_layout[sub_nm] for sub_nm in obs.name_sub]
)

In [ ]:
graph = obs.as_networkx()
for node_id in graph.nodes:
# check the or / ex convention is ok (kirchoff's law)
p_ = graph.nodes[node_id]["p"]
q_ = graph.nodes[node_id]["q"]

# get the edges
edges = graph.edges(node_id)
p_line = 0  # all active power injected at this nodes on all powerlines
q_line = 0  # all reactive power injected at this nodes on all powerlines
for (k1, k2) in edges:
# now retrieve the active / reactive power injected at this node (looking at either *_or or *_ex
# depending on the direction of the powerline: remember that the "origin" is always the lowest
# bus id.
if k1 < k2:
# the current inspected node is the lowest, so on the "origin" side
p_line += graph.edges[(k1, k2)]["p_or"]
q_line += graph.edges[(k1, k2)]["q_or"]
else:
# the current node is the largest, so on the "extremity" side
p_line += graph.edges[(k1, k2)]["p_ex"]
q_line += graph.edges[(k1, k2)]["q_ex"]
assert abs(p_line - p_) <= 1e-5
assert abs(q_line - q_) <= 1e-5


#### c) Some other handy methods¶

The observation can be converted to / from a flat numpy array. This function is useful for interacting with machine learning libraries or to store it, but it probably makes it less readable for a human. The function proceeds by stacking all the features mentionned above in a single numpy.float64 vector.

In [ ]:
vector_representation_of_observation = obs.to_vect()
vector_representation_of_observation


An observation can be copied, of course:

In [ ]:
obs2 = obs.copy()


Or reset:

In [ ]:
obs2.reset()
print(obs2.gen_p)


In [ ]:
obs2.from_vect(vector_representation_of_observation)
obs2.gen_p


It is also possible to assess whether two observations are equal or not:

In [ ]:
obs == obs2


#### d) Simulate¶

As opposed to most RL problems, in this framework we add the possibility to "simulate" the impact of a possible action on the power grid. This helps calculating roll-outs in the RL setting, and can be close to "model-based" reinforcement learning approaches (except that nothing more has to be learned).

This "simulate" method uses the available forecast data (forecasts are made available by the same way we loaded the data here, with the class GridStateFromFileWithForecasts. For this class, only forecasts for 1 time step are provided, but this might be adapted in the future).

Note that this simulate function can use a different simulator than the one used by the Environment. Fore more information, we encourage you to read the official documentation, or if it has been built locally (recommended), to consult this page.

This function will:

1. apply the forecasted injection on the powergrid
2. run a powerflow with the decidated simulate powerflow simulator
3. return:
1. the anticipated observation (after the action has been taken)
2. the anticipated reward (of this simulated action)
3. whether or not there has been an error

From a user point of view, this is the main difference with the previous pypownet framework. In pypownet, this "simulation" used to be performed directly by the environment, thus giving direct access of the environment's future data to the agent, which could break the RL framework since the agent is only supposed to know about the current state of the environment (it was not the case in the first edition of the Learning to Run A Power Network as the Environment was fully observable). In grid2op, the simulation is now performed from the current state of the environment and it is imperfect since it does not have access to future information.

Here is an example of some features of the observation, in the current state and in the simulated next state :

In [ ]:
do_nothing_act = env.action_space({})
obs_sim, reward_sim, is_done_sim, info_sim = obs.simulate(do_nothing_act)

In [ ]:
obs.gen_p

In [ ]:
obs_sim.gen_p


#### e) obs + act¶

In gri2op >= 1.5 we also introduced a method that can be used to rapidly assess what would be the effect of a given "action" (see next notebook for a more detailed explanation of the actions) on the grid.

To use it, you can use the obs.connectivity_matrix() and obs.bus_connectivity_matrix() function combined with the grid2op obs + act implementation.

An example is given here:

In [ ]:
action_description = {}
act = env.action_space(action_description)
resulting_partial_obs = obs + act
resulting_partial_obs.connectivity_matrix()


NB This is not commutative: obs + act is not the same as act + obs (the later will crash by the way).

NB This obs + act method is much faster than the env.step(act) method or the obs.simulate(act) method, but the resulting "partial observation" is not complete at all. For example, it do not contains any information on the flows, nor the loads or generators etc. do not have anything regaring the time (date, hour of day etc.). We recommend to use it only combined with the partial_obs.connectivity_matrix() or partial_obs.bus_connectivity_matrix()

## II) Taking actions based on the observation¶

In this section we will make our first Agent that will act based on these observations.

All Agents must derive from the grid2op.Agent class. The main function to implement for the Agents is the "act" function (more information can be found on the official documentation or here ).

Basically, the Agent receives a reward and an observation, and chooses a new action. Some different Agents are pre-defined in the grid2op package. We won't talk about them here (for more information, see the documentation or the Agent.py file), but rather we will make a custom Agent.

This Agent will select among:

• doing nothing
• disconnecting the powerline having the higher relative flows
• reconnecting a powerline disconnected
• disconnecting the powerline having the lower relative flows

by using simulate on the corresponding actions, and choosing the one that has the highest predicted reward.

Note that this kind of Agent is not particularly smart and is given only as an example.

In [ ]:
from grid2op.Agent import BaseAgent
import numpy as np

class MyAgent(BaseAgent):
def __init__(self, action_space):
# python required method to code
BaseAgent.__init__(self, action_space)
self.do_nothing = self.action_space({})
self.print_next = False

def act(self, observation, reward, done=False):
i_max = np.argmax(observation.rho)
new_status_max = np.zeros(observation.rho.shape, dtype=int)
new_status_max[i_max] = -1
act_max = self.action_space({"set_line_status": new_status_max})

i_min = np.argmin(observation.rho)
new_status_min = np.zeros(observation.rho.shape, dtype=int)
if observation.rho[i_min] > 0:
# all powerlines are connected, i try to disconnect this one
new_status_min[i_min] = -1
act_min = self.action_space({"set_line_status": new_status_min})
else:
# at least one powerline is disconnected, i try to reconnect it
new_status_min[i_min] = 1
#             act_min = self.action_space({"set_status": new_status_min})
act_min = self.action_space({"set_line_status": new_status_min,
"set_bus": {"lines_or_id": [(i_min, 1)], "lines_ex_id": [(i_min, 1)]}})

_, reward_sim_dn, *_ = observation.simulate(self.do_nothing)
_, reward_sim_max, *_ = observation.simulate(act_max)
_, reward_sim_min, *_ = observation.simulate(act_min)

if reward_sim_dn >= reward_sim_max and reward_sim_dn >= reward_sim_min:
self.print_next = False
res = self.do_nothing
elif reward_sim_max >= reward_sim_min:
self.print_next = True
res = act_max
else:
self.print_next = True
res = act_min
return res


We compare this Agent with the Donothing agent (already coded) on the 3 episodes made available with this package. To make this comparison more interesting, it's better to use the L2RPN rewards (L2RPNReward).

In [ ]:
from grid2op.Runner import Runner
from grid2op.Agent import DoNothingAgent
from grid2op.Reward import L2RPNReward
from grid2op.Chronics import GridStateFromFileWithForecasts

max_iter = 10  # to make computation much faster we will only consider 50 time steps instead of 287
runner = Runner(**env.get_params_for_runner(),
agentClass=DoNothingAgent
)
res = runner.run(nb_episode=1, max_iter=max_iter)

print("The results for DoNothing agent are:")
for _, chron_name, cum_reward, nb_time_step, max_ts in res:
msg_tmp = "\tFor chronics with id {}\n".format(chron_name)
msg_tmp += "\t\t - cumulative reward: {:.6f}\n".format(cum_reward)
msg_tmp += "\t\t - number of time steps completed: {:.0f} / {:.0f}".format(nb_time_step, max_ts)
print(msg_tmp)

In [ ]:
runner = Runner(**env.get_params_for_runner(),
agentClass=MyAgent
)
res = runner.run(nb_episode=1, max_iter=max_iter)
print("The results for the custom agent are:")
for _, chron_name, cum_reward, nb_time_step, max_ts in res:
msg_tmp = "\tFor chronics with id {}\n".format(chron_name)
msg_tmp += "\t\t - cumulative reward: {:.6f}\n".format(cum_reward)
msg_tmp += "\t\t - number of time steps completed: {:.0f} / {:.0f}".format(nb_time_step, max_ts)
print(msg_tmp)


As we can see, both agents obtain the same score here, but there would be a difference if we didn't limit the episode length to 10 time steps.

NB Disabling the time limit for the episode can be done by setting max_iter=-1 in the previous cells. Here, setting max_iter=10 is only done so that this notebook can run faster, but increasing or disabling the time limit would allow us to spot differences in the agents' performances.

The same can be done for the PowerLineSwitch agent :

In [ ]:
from grid2op.Agent import PowerLineSwitch
runner = Runner(**env.get_params_for_runner(),
agentClass=PowerLineSwitch
)
res = runner.run(nb_episode=1, max_iter=max_iter)
print("The results for the PowerLineSwitch agent are:")
for _, chron_name, cum_reward, nb_time_step, max_ts in res:
msg_tmp = "\tFor chronics with id {}\n".format(chron_name)
msg_tmp += "\t\t - cumulative reward: {:.6f}\n".format(cum_reward)
msg_tmp += "\t\t - number of time steps completed: {:.0f} / {:.0f}".format(nb_time_step, max_ts)
print(msg_tmp)


NB As of grid2op version 1.5, you can also retrieve all the state of all the step of the episodes by passing the flag add_detailed_output=True to the runner.run(..., add_detailed_output=True)