Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 97 additions & 6 deletions getting_started/08_PlottingCapabilities.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,17 @@
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib\n",
"import matplotlib as mpl\n",
"import shutil\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt # pip install matplotlib\n",
"import seaborn as sns # pip install seaborn\n",
"import plotly.graph_objects as go # pip install plotly\n",
"import imageio # pip install imageio\n",
"\n",
"max_iter = 5 # to save time we only assess performance on 30 iterations"
"max_iter = 5 # To save time we only assess performance on 30 iterations"
]
},
{
Expand All @@ -87,7 +89,7 @@
"source": [
"import grid2op\n",
"env_name = \"l2rpn_case14_sandbox\"\n",
"env = grid2op.make(env_name, test=True)"
"env = grid2op.make(env_name, test=True, n_busbar=3)"
]
},
{
Expand Down Expand Up @@ -174,7 +176,7 @@
"metadata": {},
"outputs": [],
"source": [
"fig_obs2 = plot_helper.plot_obs(obs, line_info=\"p\", load_info=\"v\")"
"fig_obs2 = plot_helper.plot_obs(obs, line_info=\"p\", load_info=\"v\", gen_info=None)"
]
},
{
Expand Down Expand Up @@ -231,6 +233,85 @@
"This plotting utility is a very useful tool to detect what happened, especially just before a game over."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Matplotlib - Full Customization\n",
"In PlotMatplot it is also possible to customize:\n",
"* The size of image (width and height)\n",
"* The resolution of the image (dpi)\n",
"* The size of the markers representing loads, generators, energy storage and busbars\n",
"* The color map used to color markers and/or powerlines\n",
"* The normalization of the color map\n",
"* The attribute used to color markers and/or powerlines (e.g. \"rho\" for ratio of thermal limit)\n",
"* The attribute used to display information next to the markers / powerlines (e.g. \"v\" for voltage and \"p\" for active power)\n",
"\n",
"You can either do so when first instantiating the helper PlotMatplot(), which will ensure the same process is applied each time you plot an observation. Otherwise, you can pass it as a kwarg to .plot_obs(...) for a specific observation to customize that one."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example: Double the size of markers\n",
"plot_helper = PlotMatplot(env.observation_space, sub_radius=16, gen_radius=18, load_radius=18, bus_radius=12)\n",
"plot_helper.plot_obs(obs);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example: Use built-in matplotlib colormap (as str)\n",
"print(f\"Available Colormaps: {[k for k in mpl.colormaps.keys() if not k.endswith('_r')]}\")\n",
"plot_helper = PlotMatplot(env.observation_space, load_color=\"inferno\", load_color_attr=\"load_p\", gen_id=True, gen_color=\"berlin\", gen_color_attr=\"v\", bus_color=\"inferno_r\")\n",
"plot_helper.plot_obs(obs, gen_info=\"v\");"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example: Changing the normalization on the colormaps (BoundaryNorm)\n",
"# Note: Using a list of numbers with a continuous cmap name will NOT work, since BoundaryNorm expects a discrete cmap\n",
"plot_helper = PlotMatplot(env.observation_space, line_color_norm=[0.0, 0.25, 0.5, 0.75, 1.0], \n",
" line_color=[\"darkgreen\", \"green\", \"yellow\", \"orange\", \"red\"], \n",
" line_color_attr=\"rho\")\n",
"plot_helper.plot_obs(obs);\n",
"\n",
"# Example: Changing the normalization on the colormaps (Custom Norm: PowerNorm)\n",
"plot_helper = PlotMatplot(env.observation_space, line_color_norm=mpl.colors.PowerNorm(vmin=0.0, vmax=np.max(obs.p_or), gamma=0.5),\n",
" line_color=\"cividis\", \n",
" line_color_attr=\"p\")\n",
"plot_helper.plot_obs(obs);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example: Changing the normalization on the colormaps (Normalize (linear))\n",
"plot_helper = PlotMatplot(env.observation_space, load_color_norm=[0.0, np.max(obs.load_p)], \n",
" load_color=\"twilight\", \n",
" load_color_attr=\"p\")\n",
"plot_helper.plot_obs(obs);\n",
"\n",
"# Example: Changing the normalization on the colormaps (BoundaryNorm)\n",
"plot_helper = PlotMatplot(env.observation_space, gen_color_norm=mpl.colors.PowerNorm(vmin=np.min(obs.gen_pmin), vmax=np.max(obs.gen_pmax), gamma=0.5), \n",
" gen_color=\"twilight\", \n",
" gen_color_attr=\"p\")\n",
"plot_helper.plot_obs(obs);"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -267,6 +348,7 @@
" return res\n",
" \n",
"myagent = CustomRandom(env.action_space)\n",
"myagent.seed(0)\n",
"obs = env.reset()\n",
"reward = env.reward_range[0]\n",
"done = False\n",
Expand All @@ -282,6 +364,15 @@
" break"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"myagent.action_space._get_possible_action_types()"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -447,7 +538,7 @@
"source": [
"import sys\n",
"print(\"To install it, either uncomment the cell bellow, or type, in a command prompt:\\n{}\".format(\n",
" (\"\\t{} -m pip install -m pip install -U git+https://github.com/grid2op/grid2viz --user\".format(sys.executable))))"
" (\"\\t{} -m pip install git+https://github.com/grid2op/grid2viz --user\".format(sys.executable))))"
]
},
{
Expand Down Expand Up @@ -510,7 +601,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "venv (3.13.5.final.0)",
"language": "python",
"name": "python3"
},
Expand All @@ -524,7 +615,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down
4 changes: 2 additions & 2 deletions grid2op/Action/baseAction.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,8 +1259,8 @@ def _aux_process_n_busbar_per_sub(cls):

if "change_bus" in cls.authorized_keys:
cls.authorized_keys.remove("change_bus")
if "_private_change_bus_vect" in cls.attr_list_vect:
cls.attr_list_vect.remove("_private_change_bus_vect")
if "_change_bus_vect" in cls.attr_list_vect:
cls.attr_list_vect.remove("_change_bus_vect")

@classmethod
def process_grid2op_compat(cls):
Expand Down
71 changes: 37 additions & 34 deletions grid2op/Agent/agentWithConverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,44 +115,47 @@ def __init__(self, action_space, action_space_converter=None, **kwargs_converter

if action_space_converter is None:
BaseAgent.__init__(self, action_space)
else:
if isinstance(action_space_converter, type):
if issubclass(action_space_converter, Converter):
action_space_converter_this_env_class = (
action_space_converter.init_grid(action_space)
)
this_action_space = action_space_converter_this_env_class(
action_space
)
BaseAgent.__init__(self, this_action_space)
else:
raise Grid2OpException(
"Impossible to make an BaseAgent with a converter of type {}. "
"Please use a converter deriving from grid2op.ActionSpaceConverter.Converter."
"".format(action_space_converter)
)
elif isinstance(action_space_converter, Converter):
if isinstance(
action_space_converter._template_act,
self.init_action_space.actionClass,
):
BaseAgent.__init__(self, action_space_converter)
else:
raise Grid2OpException(
"Impossible to make an BaseAgent with the provided converter of type {}. "
"It doesn't use the same type of action as the BaseAgent's action space."
"".format(action_space_converter)
)
return

self._build_my_act_space(action_space, action_space_converter)
self.action_space.init_converter(**kwargs_converter)

def _build_my_act_space(self, action_space, action_space_converter):
if isinstance(action_space_converter, type):
if issubclass(action_space_converter, Converter):
action_space_converter_this_env_class = (
action_space_converter.init_grid(action_space)
)
this_action_space = action_space_converter_this_env_class(
action_space
)
BaseAgent.__init__(self, this_action_space)
else:
raise Grid2OpException(
'You try to initialize and BaseAgent with an invalid converter "{}". It must'
'either be a type deriving from "Converter", or an instance of a class'
"deriving from it."
"Impossible to make an BaseAgent with a converter of type {}. "
"Please use a converter deriving from grid2op.ActionSpaceConverter.Converter."
"".format(action_space_converter)
)

self.action_space.init_converter(**kwargs_converter)

elif isinstance(action_space_converter, Converter):
if isinstance(
action_space_converter._template_act,
self.init_action_space.actionClass,
):
BaseAgent.__init__(self, action_space_converter)
else:
raise Grid2OpException(
"Impossible to make an BaseAgent with the provided converter of type {}. "
"It doesn't use the same type of action as the BaseAgent's action space."
"".format(action_space_converter)
)
else:
raise Grid2OpException(
'You try to initialize and BaseAgent with an invalid converter "{}". It must'
'either be a type deriving from "Converter", or an instance of a class'
"deriving from it."
"".format(action_space_converter)
)

def convert_obs(self, observation):
"""
This function convert the observation, that is an object of class :class:`grid2op.Observation.BaseObservation`
Expand Down
16 changes: 8 additions & 8 deletions grid2op/Converter/IdToAct.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,55 +175,55 @@ def init_converter(self, all_actions=None, **kwargs):
# add the do nothing action, always
self.all_actions.append(super().__call__())
tmp_act_cls = type(self._template_act)
if "_set_line_status" in tmp_act_cls.attr_list_vect:
if "set_line_status" in tmp_act_cls.authorized_keys:
# lines 'set'
include_ = True
if "set_line_status" in kwargs:
include_ = kwargs["set_line_status"]
if include_:
self.all_actions += self.get_all_unitary_line_set(self)

if "_switch_line_status" in tmp_act_cls.attr_list_vect:
if "change_line_status" in tmp_act_cls.authorized_keys:
# lines 'change'
include_ = True
if "change_line_status" in kwargs:
include_ = kwargs["change_line_status"]
if include_:
self.all_actions += self.get_all_unitary_line_change(self)

if "_set_topo_vect" in tmp_act_cls.attr_list_vect:
if "set_bus" in tmp_act_cls.authorized_keys:
# topologies 'set'
include_ = True
if "set_topo_vect" in kwargs:
include_ = kwargs["set_topo_vect"]
if include_:
self.all_actions += self.get_all_unitary_topologies_set(self)

if "_change_bus_vect" in tmp_act_cls.attr_list_vect:
if "change_bus" in tmp_act_cls.authorized_keys:
# topologies 'change'
include_ = True
if "change_bus_vect" in kwargs:
include_ = kwargs["change_bus_vect"]
if include_:
self.all_actions += self.get_all_unitary_topologies_change(self)

if "_redispatch" in tmp_act_cls.attr_list_vect:
if "redispatch" in tmp_act_cls.authorized_keys:
# redispatch (transformed to discrete variables)
include_ = True
if "redispatch" in kwargs:
include_ = kwargs["redispatch"]
if include_:
self.all_actions += self.get_all_unitary_redispatch(self)

if "_curtail" in tmp_act_cls.attr_list_vect:
if "curtail" in tmp_act_cls.authorized_keys:
# redispatch (transformed to discrete variables)
include_ = True
if "curtail" in kwargs:
include_ = kwargs["curtail"]
if include_:
self.all_actions += self.get_all_unitary_curtail(self)

if "_storage_power" in tmp_act_cls.attr_list_vect:
if "set_storage" in tmp_act_cls.authorized_keys:
# redispatch (transformed to discrete variables)
include_ = True
if "storage" in kwargs:
Expand Down
Loading