/
SerializableActionSpace.py
1591 lines (1311 loc) · 61.4 KB
/
SerializableActionSpace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems.
import warnings
import numpy as np
import itertools
from typing import Dict, List
from grid2op.dtypes import dt_int, dt_float, dt_bool
from grid2op.Exceptions import AmbiguousAction, Grid2OpException
from grid2op.Space import SerializableSpace
from grid2op.Action.BaseAction import BaseAction
class SerializableActionSpace(SerializableSpace):
"""
This class allows serializing/ deserializing the action space.
It should not be used inside an :attr:`grid2op.Environment.Environment` , as some functions of the action might not
be compatible with the serialization, especially the checking of whether or not an action is legal or not.
Attributes
----------
actionClass: ``type``
Type used to build the :attr:`SerializableActionSpace.template_act`
_template_act: :class:`BaseAction`
An instance of the "*actionClass*" provided used to provide higher level utilities, such as the size of the
action (see :func:`Action.size`) or to sample a new Action (see :func:`grid2op.Action.Action.sample`)
"""
SET_STATUS_ID = 0
CHANGE_STATUS_ID = 1
SET_BUS_ID = 2
CHANGE_BUS_ID = 3
REDISPATCHING_ID = 4
STORAGE_POWER_ID = 5
RAISE_ALARM_ID = 6
RAISE_ALERT_ID = 7
ERR_MSG_WRONG_TYPE = ('The action to update using `ActionSpace` is of type "{}" '
'"which is not the type of action handled by this action space "'
'("{}")')
def __init__(self, gridobj, actionClass=BaseAction, _init_grid=True):
"""
INTERNAL USE ONLY
.. warning:: /!\\\\ Internal, do not use unless you know what you are doing /!\\\\
The :class:`grid2op.Environment.Environment` is responsible for the creation of the
action space. Do not attempt to make one yourself.
Parameters
----------
gridobj: :class:`grid2op.Space.GridObjects`
Representation of the underlying powergrid.
actionClass: ``type``
Type of action used to build :attr:`Space.SerializableSpace._template_obj`. It should derived from
:class:`BaseAction`.
"""
SerializableSpace.__init__(
self, gridobj=gridobj, subtype=actionClass, _init_grid=_init_grid
)
self.actionClass = self.subtype
self._template_act = self.actionClass()
@staticmethod
def from_dict(dict_):
"""
INTERNAL USE ONLY
.. warning:: /!\\\\ Internal, do not use unless you know what you are doing /!\\\\
Allows the de-serialization of an object stored as a dictionary (for example in the case of JSON saving).
Parameters
----------
dict_: ``dict``
Representation of an BaseAction Space (aka SerializableActionSpace) as a dictionary.
Returns
-------
res: :class:``SerializableActionSpace``
An instance of an action space matching the dictionary.
"""
tmp = SerializableSpace.from_dict(dict_)
CLS = SerializableActionSpace.init_grid(tmp)
res = CLS(gridobj=tmp, actionClass=tmp.subtype, _init_grid=False)
return res
def _get_possible_action_types(self):
rnd_types = []
cls = type(self)
if "set_line_status" in self.actionClass.authorized_keys:
rnd_types.append(cls.SET_STATUS_ID)
if "change_line_status" in self.actionClass.authorized_keys:
rnd_types.append(cls.CHANGE_STATUS_ID)
if "set_bus" in self.actionClass.authorized_keys:
rnd_types.append(cls.SET_BUS_ID)
if "change_bus" in self.actionClass.authorized_keys:
rnd_types.append(cls.CHANGE_BUS_ID)
if "redispatch" in self.actionClass.authorized_keys:
rnd_types.append(cls.REDISPATCHING_ID)
if self.n_storage > 0 and "storage_power" in self.actionClass.authorized_keys:
rnd_types.append(cls.STORAGE_POWER_ID)
if self.dim_alarms > 0 and "raise_alarm" in self.actionClass.authorized_keys:
rnd_types.append(cls.RAISE_ALARM_ID)
if self.dim_alerts > 0 and "raise_alert" in self.actionClass.authorized_keys:
rnd_types.append(cls.RAISE_ALERT_ID)
return rnd_types
def supports_type(self, action_type):
"""
Returns if the current action_space supports the current action type.
Parameters
----------
action_type: ``str``
One of "set_line_status", "change_line_status", "set_bus", "change_bus", "redispatch",
"storage_power", "set_storage", "curtail" or "curtail_mw"
A string representing the action types you want to inspect.
Returns
-------
``True`` if you can use the `action_type` to create an action, ``False`` otherwise.
Examples
---------
To know if you can use the `act.set_bus` property to change the bus of an element, you can use:
.. code-block:: python
import grid2op
from grid2op.Converter import ConnectivityConverter
env = grid2op.make("rte_case14_realistic", test=True)
can_i_use_set_bus = env.action_space.supports_type("set_bus") # this is True
env2 = grid2op.make("educ_case14_storage", test=True)
can_i_use_set_bus = env2.action_space.supports_type("set_bus") # this is False
# this environment do not allow for topological changes but only action on storage units and redispatching
"""
name_action_types = [
"set_line_status",
"change_line_status",
"set_bus",
"change_bus",
"redispatch",
"storage_power",
"set_storage",
"curtail",
"curtail_mw",
"raise_alarm",
"raise_alert"
]
assert action_type in name_action_types, (
f"The action type provided should be in {name_action_types}. "
f"You provided {action_type} which is not supported."
)
if action_type == "storage_power":
return (self.n_storage > 0) and (
"set_storage" in self.actionClass.authorized_keys
)
elif action_type == "set_storage":
return (self.n_storage > 0) and (
"set_storage" in self.actionClass.authorized_keys
)
elif action_type == "curtail_mw":
return "curtail" in self.actionClass.authorized_keys
else:
return action_type in self.actionClass.authorized_keys
def _sample_set_line_status(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
rnd_line = self.space_prng.randint(self.n_line)
rnd_status = self.space_prng.choice([1, -1])
rnd_update["set_line_status"] = [(rnd_line, rnd_status)]
return rnd_update
def _sample_change_line_status(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
rnd_line = self.space_prng.randint(self.n_line)
rnd_update["change_line_status"] = [rnd_line]
return rnd_update
def _sample_set_bus(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
rnd_sub = self.space_prng.randint(self.n_sub)
sub_size = self.sub_info[rnd_sub]
rnd_topo = self.space_prng.choice([-1, 0, 1, 2], sub_size)
rnd_update["set_bus"] = {"substations_id": [(rnd_sub, rnd_topo)]}
return rnd_update
def _sample_change_bus(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
rnd_sub = self.space_prng.randint(self.n_sub)
sub_size = self.sub_info[rnd_sub]
rnd_topo = self.space_prng.choice([0, 1], sub_size).astype(dt_bool)
rnd_update["change_bus"] = {"substations_id": [(rnd_sub, rnd_topo)]}
return rnd_update
def _sample_redispatch(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
gens = np.arange(self.n_gen)[self.gen_redispatchable]
rnd_gen = self.space_prng.choice(gens)
rd = -self.gen_max_ramp_down[rnd_gen]
ru = self.gen_max_ramp_up[rnd_gen]
rnd_gen_disp = (ru - rd) * self.space_prng.random() + rd
rnd_disp = np.zeros(self.n_gen)
rnd_disp[rnd_gen] = rnd_gen_disp
rnd_update["redispatch"] = rnd_disp
rnd_update["redispatch"] = rnd_update["redispatch"].astype(dt_float)
return rnd_update
def _sample_storage_power(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
stor_unit = np.arange(self.n_storage)
rnd_sto = self.space_prng.choice(stor_unit)
rd = -self.storage_max_p_prod[rnd_sto]
ru = self.storage_max_p_absorb[rnd_sto]
rnd_sto_prod = (ru - rd) * self.space_prng.random() + rd
res = np.zeros(self.n_gen)
res[rnd_sto] = rnd_sto_prod
rnd_update["storage_power"] = res
rnd_update["storage_power"] = rnd_update["storage_power"].astype(dt_float)
return rnd_update
def _sample_raise_alarm(self, rnd_update=None):
""".. warning::
/!\\\\ Only valid with "l2rpn_icaps_2021" environment /!\\\\
"""
if rnd_update is None:
rnd_update = {}
rnd_area = self.space_prng.randint(self.dim_alarms)
rnd_update["raise_alarm"] = [rnd_area]
return rnd_update
def _sample_raise_alert(self, rnd_update=None):
if rnd_update is None:
rnd_update = {}
rnd_alerted_lines = self.space_prng.choice([True, False], self.dim_alerts).astype(dt_bool)
rnd_update["raise_alert"] = rnd_alerted_lines
return rnd_update
def sample(self):
"""
A utility used to sample a new random :class:`BaseAction`.
The sampled action is unitary: It has an impact on a single line/substation/generator.
There is no guarantee concerning the "legality" of the action (see the description of the
Action module for more information about illegal action).
It will only act by doing action supported by the action space. For example, if the action space
does not support "redispatching" then this method will NOT sample any redispatching action.
Returns
-------
res: :class:`BaseAction`
A random action sampled from the :attr:`ActionSpace.actionClass`
Examples
---------
The first usage is to sample uniform **unary** actions, you can do this with the
following:
.. code-block:: python
import grid2op
env = grid2op.make()
# and now you can sample from the action space
random_action = env.action_space.sample()
*Note* that the random action can be illegal depending on the game rules defined in the
rules :class:`grid2op.Rules`
If for some reason you want to sample more complex actions, you can do this the following way:
.. code-block:: python
import grid2op
env = grid2op.make()
# and now you can sample from the action space
random_action = env.action_space()
for i in range(5):
# my resulting action will be a complex action
# that will be the results of applying 5 random actions
random_action += env.action_space.sample()
print(random_action)
"""
rnd_act = self.actionClass()
# get the type of actions I am allowed to perform
rnd_types = self._get_possible_action_types()
# Cannot sample this space, return do nothing
if not len(rnd_types):
return rnd_act
# this sampling
rnd_type = self.space_prng.choice(rnd_types)
if rnd_type == self.SET_STATUS_ID:
rnd_update = self._sample_set_line_status()
elif rnd_type == self.CHANGE_STATUS_ID:
rnd_update = self._sample_change_line_status()
elif rnd_type == self.SET_BUS_ID:
rnd_update = self._sample_set_bus()
elif rnd_type == self.CHANGE_BUS_ID:
rnd_update = self._sample_change_bus()
elif rnd_type == self.REDISPATCHING_ID:
rnd_update = self._sample_redispatch()
elif rnd_type == self.STORAGE_POWER_ID:
rnd_update = self._sample_storage_power()
elif rnd_type == self.RAISE_ALARM_ID:
rnd_update = self._sample_raise_alarm()
elif rnd_type == self.RAISE_ALERT_ID:
rnd_update = self._sample_raise_alert()
else:
raise Grid2OpException(
"Impossible to sample action of type {}".format(rnd_type)
)
rnd_act.update(rnd_update)
return rnd_act
def disconnect_powerline(self, line_id=None, line_name=None, previous_action=None):
"""
Utilities to disconnect a powerline more easily.
Parameters
----------
line_id: ``int``
The powerline to be disconnected.
line_name: ``str``
Name of the powerline. Note that either line_id or line_name should be provided. If both are provided, it is
an error, if none are provided it is an error.
previous_action: :class:`BaseAction`
If you want to stack up multiple actions.
Returns
-------
res: :class:`BaseAction`
The action that will disconnect the powerline.
Notes
------
If you use `previous_action` it will modify the action **in place** which means that
`previous_action` will be modified by this method.
Examples
---------
You can use it this way:
.. code-block:: python
import grid2op
env = grid2op.make()
# and now you can disconnect line 0
disco_line_0 = env.action_space.disconnect_powerline(line_id=0)
# or line with name "0_4_1"
disco_line_1 = env.action_space.disconnect_powerline(line_name="0_4_1")
# and you can disconnect both line 2 and 3 with:
disco_line_2 = env.action_space.disconnect_powerline(line_id=2)
disco_line_2_and_3 = env.action_space.disconnect_powerline(line_id=3, previous_action=disco_line_2)
print(disco_line_2_and_3)
# be careful, "disco_line_2" is affected and is in fact equal to "disco_line_2_and_3"
# after the last call!
"""
if line_id is None and line_name is None:
raise AmbiguousAction(
'You need to provide either the "line_id" or the "line_name" of the powerline '
"you want to disconnect"
)
if line_id is not None and line_name is not None:
raise AmbiguousAction(
'You need to provide only of the "line_id" or the "line_name" of the powerline '
"you want to disconnect"
)
if line_id is None:
line_id = np.where(self.name_line == line_name)[0]
if not len(line_id):
raise AmbiguousAction(
'Line with name "{}" is not on the grid. The powerlines names are:\n{}'
"".format(line_name, self.name_line)
)
if previous_action is None:
res = self.actionClass()
else:
if not isinstance(previous_action, self.actionClass):
raise AmbiguousAction(
type(self).ERR_MSG_WRONG_TYPE.format(type(previous_action), self.actionClass)
)
res = previous_action
if line_id > self.n_line:
raise AmbiguousAction(
"You asked to disconnect powerline of id {} but this id does not exist. The "
"grid counts only {} powerline".format(line_id, self.n_line)
)
res.update({"set_line_status": [(line_id, -1)]})
return res
def reconnect_powerline(
self, bus_or, bus_ex, line_id=None, line_name=None, previous_action=None
):
"""
Utilities to reconnect a powerline more easily.
Note that in case "bus_or" or "bus_ex" are not the current bus to which the powerline is connected, they
will be affected by this action.
Notes
------
This utility requires you to specify on which bus you want to connect each end
("*origin*" or "*extremity*") of the powerline you want to reconnect.
If you don't want to specify them, you can set them to ``0`` and it will reconnect them
to the last known buses to which they were connected (this is automatically done by the
Environment since version `0.8.0`).
If you use `previous_action` it will modify the action **in place** which means that
`previous_action` will be modified by this method.
Parameters
----------
line_id: ``int``
The powerline to be disconnected.
bus_or: ``int``
On which bus to reconnect the powerline at its origin end
bus_ex: ``int``
On which bus to reconnect the powerline at its extremity end
previous_action
Returns
-------
res: :class:`BaseAction`
The action that will reconnect the powerline.
Examples
---------
You can use it this way:
.. code-block:: python
import grid2op
env = grid2op.make()
# and now you can reconnect line 0
reco_line_0 = env.action_space.reconnect_powerline(line_id=0, bus_or=1, bus_ex=0)
# or line with name "0_4_1" to bus 1 on its "origin" end and bus 2 on its "extremity" end
reco_line_1 = env.action_space.reconnect_powerline(line_name="0_4_1", bus_or=1, bus_ex=2)
# and you can reconnect both line 2 and 3 with:
reco_line_2 = env.action_space.reconnect_powerline(line_id=2, bus_or=1, bus_ex=2)
reco_line_2_and_3 = env.action_space.reconnect_powerline(line_id=3,
bus_or=0, bus_ex=1,
previous_action=reco_line_2)
print(reco_line_2_and_3)
# be careful, "reco_line_2" is affected and is in fact equal to "reco_line_2_and_3"
# after the last call!
"""
if line_id is None and line_name is None:
raise AmbiguousAction(
'You need to provide either the "line_id" or the "line_name" of the powerline '
"you want to reconnect"
)
if line_id is not None and line_name is not None:
raise AmbiguousAction(
'You need to provide only of the "line_id" or the "line_name" of the powerline '
"you want to reconnect"
)
if line_id is None:
line_id = np.where(self.name_line == line_name)[0]
if previous_action is None:
res = self.actionClass()
else:
if not isinstance(previous_action, self.actionClass):
raise AmbiguousAction(
type(self).ERR_MSG_WRONG_TYPE.format(type(previous_action), self.actionClass)
)
res = previous_action
if line_id > self.n_line:
raise AmbiguousAction(
"You asked to disconnect powerline of id {} but this id does not exist. The "
"grid counts only {} powerline".format(line_id, self.n_line)
)
res.update(
{
"set_line_status": [(line_id, 1)],
"set_bus": {
"lines_or_id": [(line_id, bus_or)],
"lines_ex_id": [(line_id, bus_ex)],
},
}
)
return res
def change_bus(
self,
name_element,
extremity=None,
substation=None,
type_element=None,
previous_action=None,
):
"""
Utilities to change the bus of a single element if you give its name. **NB** Changing a bus has the effect to
assign the object to bus 1 if it was before that connected to bus 2, and to assign it to bus 2 if it was
connected to bus 1. It should not be mixed up with :func:`ActionSpace.set_bus`.
If the parameter "*previous_action*" is not ``None``, then the action given to it is updated (in place) and
returned.
Parameters
----------
name_element: ``str``
The name of the element you want to change the bus
extremity: ``str``
"or" or "ex" for origin or extremity, ignored if an element is not a powerline.
substation: ``int``, optional
Its substation ID, if you know it will increase the performance. Otherwise, the method will search for it.
type_element: ``str``, optional
Type of the element to look for. It is here to speed up the computation. One of "line", "gen" or "load"
previous_action: :class:`Action`, optional
The (optional) action to update. It should be of the same type as :attr:`ActionSpace.actionClass`
Notes
------
If you use `previous_action` it will modify the action **in place** which means that
`previous_action` will be modified by this method.
Returns
-------
res: :class:`BaseAction`
The action with the modification implemented
Raises
------
res :class:`grid2op.Exception.AmbiguousAction`
If *previous_action* has not the same type as :attr:`ActionSpace.actionClass`.
Examples
---------
You can use it this way:
.. code-block:: python
import grid2op
env = grid2op.make()
# change bus of element named 'gen_1_0'
change_gen_0 = env.action_space.change_bus('gen_1_0', type_element="gen")
# you are not forced to specify the element types
change_load_1 = env.action_space.change_bus('load_2_1')
# dealing with powerline, you can affect one of its extremity
# (handy when you don't know on which substation it is located)
change_line_8_or = env.action_space.change_bus('5_11_8', extremity="or")
# and you can combine the action with
change_line_14_ex = env.action_space.change_bus('12_13_14', extremity="ex")
change_line_14_ex_load_2 = env.action_space.change_bus("load_3_2",
previous_action=change_line_14_ex)
print(change_line_14_ex_load_2)
# be careful, "change_line_14_ex" is affected and is in fact equal to
# "change_line_14_ex_load_2"
# after the last call!
"""
if previous_action is None:
res = self.actionClass()
else:
if not isinstance(previous_action, self.actionClass):
raise AmbiguousAction(
type(self).ERR_MSG_WRONG_TYPE.format(type(previous_action), self.actionClass)
)
res = previous_action
dict_, to_sub_pos, my_id, my_sub_id = self._extract_dict_action(
name_element, extremity, substation, type_element, res
)
arr_ = dict_["change_bus"]
me_id_ = to_sub_pos[my_id]
arr_[me_id_] = True
res.update({"change_bus": {"substations_id": [(my_sub_id, arr_)]}})
return res
def _extract_database_powerline(self, extremity):
if extremity[:2] == "or":
to_subid = self.line_or_to_subid
to_sub_pos = self.line_or_to_sub_pos
to_name = self.name_line
elif extremity[:2] == "ex":
to_subid = self.line_ex_to_subid
to_sub_pos = self.line_ex_to_sub_pos
to_name = self.name_line
elif extremity is None:
raise Grid2OpException(
"It is mandatory to know on which ends you want to change the bus of the powerline"
)
else:
raise Grid2OpException(
'unknown extremity specifier "{}". Extremity should be "or" or "ex"'
"".format(extremity)
)
return to_subid, to_sub_pos, to_name
def _extract_dict_action(
self,
name_element,
extremity=None,
substation=None,
type_element=None,
action=None,
):
to_subid = None
to_sub_pos = None
to_name = None
if type_element is None:
# i have to look through all the objects to find it
if name_element in self.name_load:
to_subid = self.load_to_subid
to_sub_pos = self.load_to_sub_pos
to_name = self.name_load
elif name_element in self.name_gen:
to_subid = self.gen_to_subid
to_sub_pos = self.gen_to_sub_pos
to_name = self.name_gen
elif name_element in self.name_line:
to_subid, to_sub_pos, to_name = self._extract_database_powerline(
extremity
)
else:
AmbiguousAction(
'Element "{}" not found in the powergrid'.format(name_element)
)
elif type_element == "line":
to_subid, to_sub_pos, to_name = self._extract_database_powerline(extremity)
elif type_element[:3] == "gen" or type_element[:4] == "prod":
to_subid = self.gen_to_subid
to_sub_pos = self.gen_to_sub_pos
to_name = self.name_gen
elif type_element == "load":
to_subid = self.load_to_subid
to_sub_pos = self.load_to_sub_pos
to_name = self.name_load
else:
raise AmbiguousAction(
'unknown type_element specifier "{}". type_element should be "line" or "load" '
'or "gen"'.format(extremity)
)
my_id = None
for i, nm in enumerate(to_name):
if nm == name_element:
my_id = i
break
if my_id is None:
raise AmbiguousAction(
'Element "{}" not found in the powergrid'.format(name_element)
)
my_sub_id = to_subid[my_id]
dict_ = action.effect_on(substation_id=my_sub_id)
return dict_, to_sub_pos, my_id, my_sub_id
def set_bus(
self,
name_element,
new_bus,
extremity=None,
substation=None,
type_element=None,
previous_action=None,
):
"""
Utilities to set the bus of a single element if you give its name. **NB** Setting a bus has the effect to
assign the object to this bus. If it was before that connected to bus 1, and you assign it to bus 1 (*new_bus*
= 1) it will stay on bus 1. If it was on bus 2 (and you still assign it to bus 1) it will be moved to bus 2.
1. It should not be mixed up with :func:`ActionSpace.change_bus`.
If the parameter "*previous_action*" is not ``None``, then the action given to it is updated (in place) and
returned.
Parameters
----------
name_element: ``str``
The name of the element you want to change the bus
new_bus: ``int``
Id of the new bus to connect the object to.
extremity: ``str``
"or" or "ext" for origin or extremity, ignored if the element is not a powerline.
substation: ``int``, optional
Its substation ID, if you know it will increase the performance. Otherwise, the method will search for it.
type_element: ``str``, optional
Type of the element to look for. It is here to speed up the computation. One of "line", "gen" or "load"
previous_action: :class:`Action`, optional
The (optional) action to update. It should be of the same type as :attr:`ActionSpace.actionClass`
Returns
-------
res: :class:`BaseAction`
The action with the modification implemented
Raises
------
AmbiguousAction
If *previous_action* has not the same type as :attr:`ActionSpace.actionClass`.
Examples
---------
You can use it this way:
.. code-block:: python
import grid2op
env = grid2op.make()
# set bus of element named 'gen_1_0' to bus 2
setbus_gen_0 = env.action_space.set_bus('gen_1_0', new_bus=2, type_element="gen")
# are not forced to specify the element types (example with load set to bus 1)
setbus_load_1 = env.action_space.set_bus('load_2_1', new_bus=1)
# dealing with powerline, you can affect one of its extremity
# (handy when you don't know on which substation it is located)
setbus_line_8_or = env.action_space.set_bus('5_11_8', new_bus=1, extremity="or")
# and you can combine the actions with:
setbus_line_14_ex = env.action_space.set_bus('12_13_14', new_bus=2, extremity="ex")
setbus_line_14_ex_load_2 = env.action_space.set_bus("load_3_2", new_bus=1,
previous_action=setbus_line_14_ex)
print(setbus_line_14_ex_load_2)
# be careful, "setbus_line_14_ex" is affected and is in fact equal to
# "setbus_line_14_ex_load_2"
# after the last call!
"""
if previous_action is None:
res = self.actionClass()
else:
res = previous_action
dict_, to_sub_pos, my_id, my_sub_id = self._extract_dict_action(
name_element, extremity, substation, type_element, res
)
dict_["set_bus"][to_sub_pos[my_id]] = new_bus
res.update({"set_bus": {"substations_id": [(my_sub_id, dict_["set_bus"])]}})
return res
def get_set_line_status_vect(self):
"""
Computes and returns a vector that can be used in the "set_status" keyword if building an :class:`BaseAction`
Returns
-------
res: :class:`numpy.array`, dtype:dt_int
A vector that doesn't affect the grid, but can be used in "set_line_status"
"""
return self._template_act.get_set_line_status_vect()
def get_change_line_status_vect(self):
"""
Computes and return a vector that can be used in the "change_line_status" keyword if building an :class:`BaseAction`
Returns
-------
res: :class:`numpy.array`, dtype:dt_bool
A vector that doesn't affect the grid, but can be used in "change_line_status"
"""
return self._template_act.get_change_line_status_vect()
@staticmethod
def get_all_unitary_line_set(action_space):
"""
Return all unitary actions that "set" powerline status.
For each powerline, there are 5 such actions:
- disconnect it
- connected it origin at bus 1 and extremity at bus 1
- connected it origin at bus 1 and extremity at bus 2
- connected it origin at bus 2 and extremity at bus 1
- connected it origin at bus 2 and extremity at bus 2
Parameters
----------
action_space: :class:`grid2op.BaseAction.ActionSpace`
The action space used.
Returns
-------
res: ``list``
The list of all "set" action acting on powerline status
"""
res = []
# powerline switch: disconnection
for i in range(action_space.n_line):
res.append(action_space.disconnect_powerline(line_id=i))
# powerline switch: reconnection
for bus_or in [1, 2]:
for bus_ex in [1, 2]:
for i in range(action_space.n_line):
act = action_space.reconnect_powerline(
line_id=i, bus_ex=bus_ex, bus_or=bus_or
)
res.append(act)
return res
@staticmethod
def get_all_unitary_line_set_simple(action_space):
"""
Return all unitary actions that "set" powerline status but in a
more simple way than :func:`SerializableActionSpace.get_all_unitary_line_set`
For each powerline, there are 2 such actions:
- disconnect it
- connected it (implicitly to the last known busbar where each
side used to be connected)
It has the main advantages to "only" add 2 actions per powerline
instead of 5.
Parameters
----------
action_space: :class:`grid2op.BaseAction.ActionSpace`
The action space used.
Returns
-------
res: ``list``
The list of all "set" action acting on powerline status
"""
res = []
# powerline set: disconnection
for i in range(action_space.n_line):
res.append(action_space({"set_line_status": [(i,-1)]}))
# powerline set: reconnection
for i in range(action_space.n_line):
res.append(action_space({"set_line_status": [(i, +1)]}))
return res
@staticmethod
def get_all_unitary_alarm(action_space):
"""
.. warning::
/!\\\\ Only valid with "l2rpn_icaps_2021" environment /!\\\\
"""
res = []
for i in range(action_space.dim_alarms):
status = np.full(action_space.dim_alarms, fill_value=False, dtype=dt_bool)
status[i] = True
res.append(action_space({"raise_alarm": status}))
return res
@staticmethod
def get_all_unitary_alert(action_space):
"""
Return all unitary actions that raise an alert on powerlines.
.. warning:: There will be one action per combination of attackable lines, so basically, if
you can raise alerts on 10 powerline, you will end up with 2**10 actions.
If you got 22 attackable lines, then you got 2**22 actions... probably a TERRIBLE IDEA !
"""
res = []
possible_values = [False, True]
if action_space.dim_alerts:
for status in itertools.product(possible_values, repeat=type(action_space).dim_alerts):
res.append(action_space({"raise_alert": np.array(status, dtype=dt_bool)}))
return res
@staticmethod
def get_all_unitary_line_change(action_space):
"""
Return all unitary actions that "change" powerline status.
For each powerline, there is only one such action that consist in change its status.
Parameters
----------
action_space: :class:`grid2op.BaseAction.ActionSpace`
The action space used.
Returns
-------
res: ``list``
The list of all "change" action acting on powerline status
"""
res = []
for i in range(action_space.n_line):
status = action_space.get_change_line_status_vect()
status[i] = True
res.append(action_space({"change_line_status": status}))
return res
@staticmethod
def get_all_unitary_topologies_change(action_space, sub_id=None):
"""
This methods allows to compute and return all the unitary topological changes that can be performed on a
powergrid.
The changes will be performed using the "change_bus" method. It excludes the "do nothing" action
Parameters
----------
action_space: :class:`grid2op.BaseAction.ActionSpace`
The action space used.
sub_id: ``int``, optional
The substation ID. If ``None`` it is done for all substations.
Notes
-----
This might take a long time on large grid (possibly 10-15 mins for the IEEE 118 for example)
Returns
-------
res: ``list``
The list of all the topological actions that can be performed.
Examples
---------
You can use it this way:
.. code-block:: python
import grid2op
env = grid2op.make()
# all "change bus" action for all the substations
all_change_actions = env.action_space.get_all_unitary_topologies_change(env.action_space)
# you can only study "change_bus" action for a given substation (can dramatically improve the computation time)
all_change_actions_sub4 = env.action_space.get_all_unitary_topologies_change(env.action_space, sub_id=4)
"""
res = []
S = [0, 1]
for sub_id_, num_el in enumerate(action_space.sub_info):
if sub_id is not None:
if sub_id_ != sub_id:
continue
already_set = set()