-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathBaseAction.py
5521 lines (4730 loc) · 228 KB
/
BaseAction.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 copy
import numpy as np
import warnings
from typing import Tuple
from grid2op.dtypes import dt_int, dt_bool, dt_float
from grid2op.Exceptions import *
from grid2op.Space import GridObjects
# TODO time delay somewhere (eg action is implemented after xxx timestep, and not at the time where it's proposed)
# TODO have the "reverse" action, that does the opposite of an action. Will be hard but who know ? :eyes:
# TODO ie: action + (rev_action) = do_nothing_action
# TODO consistency in names gen_p / prod_p and in general gen_* prod_*
class BaseAction(GridObjects):
"""
This is a base class for each :class:`BaseAction` objects.
As stated above, an action represents conveniently the modifications that will affect a powergrid.
It is not recommended to instantiate an action from scratch. The recommended way to get an action is either by
modifying an existing one using the method :func:`BaseAction.update` or to call and :class:`ActionSpace` object that
has been properly set up by an :class:`grid2op.Environment`.
BaseAction can be fully converted to and back from a numpy array with a **fixed** size.
An action can modify the grid in multiple ways.
It can change :
- the production and voltage setpoint of the generator units
- the amount of power consumed (for both active and reactive part) for load
- disconnect powerlines
- change the topology of the _grid.
To be valid, an action should be convertible to a tuple of 5 elements:
- the first element is the "injections" vector: representing the way generator units and loads are modified
- It is, in turn, a dictionary with the following keys (optional)
- "load_p" a vector of the same size of the load, giving the modification of the loads active consumption
- "load_q" a vector of the same size of the load, giving the modification of the loads reactive consumption
- "prod_p" a vector of the same size of the generators, giving the modification of the productions active
setpoint production
- "prod_v" a vector of the same size of the generators, giving the modification of the productions voltage
setpoint
- the second element is made of force line status. It is made of a vector of size :attr:`BaseAction._n_lines`
(the number of lines in the powergrid) and is interpreted as:
- -1 force line disconnection
- +1 force line reconnection
- 0 do nothing to this line
- the third element is the switch line status vector. It is made of a vector of size :attr:`BaseAction.n_line`
and is
interpreted as:
- ``True``: change the line status
- ``False``: don't do anything
- the fourth element set the buses to which the object is connected. It's a vector of integers with the following
interpretation:
- 0 -> don't change
- 1 -> connect to bus 1
- 2 -> connect to bus 2
- -1 -> disconnect the object.
- the fifth element changes the buses to which the object is connected. It's a boolean vector interpreted as:
- ``False``: nothing is done
- ``True``: change the bus eg connect it to bus 1 if it was connected to bus 2 or connect it to bus 2 if it was
connected to bus 1. NB this is only active if the system has only 2 buses per substation (that's the case for
the L2RPN challenge).
- the sixth element is a vector, representing the redispatching. Component of this vector is added to the
generators active setpoint value (if set) of the first elements.
**NB** the difference between :attr:`BaseAction._set_topo_vect` and :attr:`BaseAction._change_bus_vect` is the
following:
- If a component of :attr:`BaseAction._set_topo_vect` is 1, then the object (load, generator or powerline)
will be moved to bus 1 of the substation to which it is connected. If it is already to bus 1 nothing will be
done.
If it's on another bus it will connect it to bus 1. It's disconnected, it will reconnect it and connect it
to bus 1.
- If a component of :attr:`BaseAction._change_bus_vect` is True, then the object will be moved from one bus to
another.
If the object were on bus 1
it will be moved on bus 2, and if it were on bus 2, it will be moved on bus 1. If the object were
disconnected,
then this does nothing.
The conversion to the action into an understandable format by the backend is performed by the "update" method,
that takes into account a dictionary and is responsible to convert it into this format.
It is possible to overload this class as long as the overloaded :func:`BaseAction.__call__` operator returns the
specified format, and the :func:`BaseAction.__init__` method has the same signature.
This format is then digested by the backend and the powergrid is modified accordingly.
Attributes
----------
_set_line_status: :class:`numpy.ndarray`, dtype:int
For each powerline, it gives the effect of the action on the status of it. It should be understood as:
- -1: disconnect the powerline
- 0: don't affect the powerline
- +1: reconnect the powerline
_switch_line_status: :class:`numpy.ndarray`, dtype:bool
For each powerline, it informs whether the action will switch the status of a powerline of not. It should be
understood as followed:
- ``False``: the action doesn't affect the powerline
- ``True``: the action affects the powerline. If it was connected, it will disconnect it. If it was
disconnected, it will reconnect it.
_dict_inj: ``dict``
Represents the modification of the injection (productions and loads) of the power _grid. This dictionary can
have the optional keys:
- "load_p" to set the active load values (this is a numpy array with the same size as the number of load
in the power _grid with Nan: don't change anything, else set the value
- "load_q": same as above but for the load reactive values
- "prod_p": same as above but for the generator active setpoint values. It has the size corresponding
to the number of generators in the test case.
- "prod_v": same as above but set the voltage setpoint of generator units.
_set_topo_vect: :class:`numpy.ndarray`, dtype:int
Similar to :attr:`BaseAction._set_line_status` but instead of affecting the status of powerlines, it affects the
bus connectivity at a substation. It has the same size as the full topological vector
(:attr:`BaseAction._dim_topo`)
and for each element it should be understood as:
- 0 -> don't change
- 1 -> connect to bus 1
- 2 -> connect to bus 2
- -1 -> disconnect the object.
_change_bus_vect: :class:`numpy.ndarray`, dtype:bool
Similar to :attr:`BaseAction._switch_line_status` but it affects the topology at substations instead of the
status of
the powerline. It has the same size as the full topological vector (:attr:`BaseAction._dim_topo`) and each
component should mean:
- ``False``: the object is not affected
- ``True``: the object will be moved to another bus. If it was on bus 1 it will be moved on bus 2, and if
it was on bus 2 it will be moved on bus 1.
authorized_keys: :class:`set`
The set indicating which keys the actions can understand when calling :func:`BaseAction.update`
_subs_impacted: :class:`numpy.ndarray`, dtype:bool
This attributes is either not initialized (set to ``None``) or it tells, for each substation, if it is impacted
by the action (in this case :attr:`BaseAction._subs_impacted`\[sub_id\] is ``True``) or not
(in this case :attr:`BaseAction._subs_impacted`\[sub_id\] is ``False``)
_lines_impacted: :class:`numpy.ndarray`, dtype:bool
This attributes is either not initialized (set to ``None``) or it tells, for each powerline, if it is impacted
by the action (in this case :attr:`BaseAction._lines_impacted`\[line_id\] is ``True``) or not
(in this case :attr:`BaseAction._subs_impacted`\[line_id\] is ``False``)
attr_list_vect: ``list``, static
The authorized key that are processed by :func:`BaseAction.__call__` to modify the injections
attr_list_vect_set: ``set``, static
The authorized key that is processed by :func:`BaseAction.__call__` to modify the injections
_redispatch: :class:`numpy.ndarray`, dtype:float
Amount of redispatching that this action will perform. Redispatching will increase the generator's active
setpoint
value. This will be added to the value of the generators. The Environment will make sure that every physical
constraint is met. This means that the agent provides a setpoint, but there is no guarantee that the setpoint
will be achievable. Redispatching action is cumulative, this means that if at a given timestep you ask +10 MW
on a generator, and on another you ask +10 MW then the total setpoint for this generator that the environment
will try to implement is +20MW.
_storage_power: :class:`numpy.ndarray`, dtype:float
Amount of power you want each storage units to produce / absorbs. Storage units are in "loads"
convention. This means that if you ask for a positive number, the storage unit will absorb
power from the grid (=it will charge) and if you ask for a negative number, the storage unit
will inject power on the grid (storage unit will discharge).
_curtail: :class:`numpy.ndarray`, dtype:float
For each renewable generator, allows you to give a maximum value (as ratio of Pmax, *eg* 0.5 =>
you limit the production of this generator to 50% of its Pmax) to renewable generators.
.. warning::
In grid2op we decided that the "curtailment" type of actions consists in directly providing the
upper bound you the agent allowed for a given generator. It does not reflect the amount
of MW that will be "curtailed" but will rather provide a limit on the number of
MW a given generator can produce.
Examples
--------
Here are example on how to use the action, for more information on what will be the effect of each,
please refer to the explanatory notebooks.
You have two main methods to build actions, as showed here:
.. code-block:: python
import grid2op
env_name = ...
env = grid2op.make(env_name)
# first method:
action_description = {...} # see below
act = env.action_space(action_description)
# second method
act = env.action_space()
act.PROPERTY = MODIF
The description of action as a dictionary is the "historical" method. The method using the properties
has been added to simplify the API.
To connect / disconnect powerline, using the "set" action, you can:
.. code-block:: python
# method 1
act = env.action_space({"set_line_status": [(line_id, new_status), (line_id, new_status), ...]})
# method 2
act = env.action_space()
act.line_set_status = [(line_id, new_status), (line_id, new_status), ...]
typically: 0 <= line_id <= env.n_line and new_status = 1 or -1
To connect / disconnect powerline using the "change" action type, you can:
.. code-block:: python
# method 1
act = env.action_space({"change_line_status": [line_id, line_id, ...]})
# method 2
act = env.action_space()
act.line_change_status = [line_id, line_id, ...]
typically: 0 <= line_id <= env.n_line
To modify the busbar at which an element is connected you can (if using set, to use "change" instead
replace "set_bus" in the text below by "change_bus" **eg** `nv.action_space({"change_bus": ...})`
or `act.load_change_bus = ...` ):
.. code-block:: python
# method 1
act = env.action_space({"set_bus":
{"lines_or_id": [(line_id, new_bus), (line_id, new_bus), ...],
"lines_ex_id": [(line_id, new_bus), (line_id, new_bus), ...],
"loads_id": [(load_id, new_bus), (load_id, new_bus), ...],
"generators_id": [(gen_id, new_bus), (gen_id, new_bus), ...],
"storages_id": [(storage_id, new_bus), (storage_id, new_bus), ...]
}
})
# method 2
act = env.action_space()
act.line_or_set_bus = [(line_id, new_bus), (line_id, new_bus), ...]
act.line_ex_set_bus = [(line_id, new_bus), (line_id, new_bus), ...]
act.load_set_bus = [(load_id, new_bus), (load_id, new_bus), ...]
act.gen_set_bus = [(gen_id, new_bus), (gen_id, new_bus), ...]
act.storage_set_bus = [(storage_id, new_bus), (storage_id, new_bus), ...]
Of course you can modify one type of object at a time (you don't have to specify all "lines_or_id",
"lines_ex_id", "loads_id", "generators_id", "storages_id"
You can also give the topologies you want at each substations with:
.. code-block:: python
# method 1
act = env.action_space({"set_bus":{
"substations_id": [(sub_id, topo_sub), (sub_id, topo_sub), ...]
}})
# method 2
act = env.action_space()
act.sub_set_bus = [(sub_id, topo_sub), (sub_id, topo_sub), ...]
In the above typically 0 <= sub_id < env.n_sub and topo_sub is a vector having the right dimension (
so if a substation has 4 elements, then topo_sub should have 4 elements)
It has to be noted that `act.sub_set_bus` will return a 1d vector representing the topology
of the grid as "set" by the action, with the convention, -1 => disconnect, 0 => don't change,
1=> set to bus 1 and 2 => set object to bus 2.
In order to perform redispatching you can do as follow:
.. code-block:: python
# method 1
act = env.action_space({"redispatch": [(gen_id, amount), (gen_id, amount), ...]})
# method 2
act = env.action_space()
act.redispatch = [(gen_id, amount), (gen_id, amount), ...]
Typically 0<= gen_id < env.n_gen and `amount` is a floating point between gen_max_ramp_down and
gen_min_ramp_down for the generator modified.
In order to perform action on storage units, you can:
.. code-block:: python
# method 1
act = env.action_space({"set_storage": [(storage_id, amount), (storage_id, amount), ...]})
# method 2
act = env.action_space()
act.set_storage = [(storage_id, amount), (storage_id, amount), ...]
Typically `0 <= storage_id < env.n_storage` and `amount` is a floating point between the maximum
power and minimum power the storage unit can absorb / produce.
Finally, in order to perform curtailment action on renewable generators, you can:
.. code-block:: python
# method 1
act = env.action_space({"curtail": [(gen_id, amount), (gen_id, amount), ...]})
# method 2
act = env.action_space()
act.curtail = [(gen_id, amount), (gen_id, amount), ...]
Typically `0 <= gen_id < env.n_gen` and `amount` is a floating point between the 0. and 1.
giving the limit of power you allow each renewable generator to produce (expressed in ratio of
Pmax). For example if `gen_id=1` and `amount=0.7` it means you limit the production of
generator 1 to 70% of its Pmax.
"""
authorized_keys = {
"injection",
"hazards",
"maintenance",
"set_line_status",
"change_line_status",
"set_bus",
"change_bus",
"redispatch",
"set_storage",
"curtail",
"raise_alarm",
}
attr_list_vect = [
"prod_p",
"prod_v",
"load_p",
"load_q",
"_redispatch",
"_set_line_status",
"_switch_line_status",
"_set_topo_vect",
"_change_bus_vect",
"_hazards",
"_maintenance",
"_storage_power",
"_curtail",
"_raise_alarm",
]
attr_nan_list_set = set()
attr_list_set = set(attr_list_vect)
shunt_added = False
_line_or_str = "line (origin)"
_line_ex_str = "line (extremity)"
ERR_ACTION_CUT = 'The action added to me will be cut, because i don\'t support modification of "{}"'
ERR_NO_STOR_SET_BUS = 'Impossible to modify the storage bus (with "set") with this action type.'
def __init__(self):
"""
INTERNAL USE ONLY
.. warning:: /!\\\\ Internal, do not use unless you know what you are doing /!\\\\
**It is NOT recommended** to create an action with this method, use the action space
of the environment :attr:`grid2op.Environment.Environment.action_space` instead.
This is used to create an BaseAction instance. Preferably, :class:`BaseAction` should be created with
:class:`ActionSpace`.
IMPORTANT: Use :func:`ActionSpace.__call__` or :func:`ActionSpace.sample` to generate a valid action.
"""
GridObjects.__init__(self)
# False(line is disconnected) / True(line is connected)
self._set_line_status = np.full(shape=self.n_line, fill_value=0, dtype=dt_int)
self._switch_line_status = np.full(
shape=self.n_line, fill_value=False, dtype=dt_bool
)
# injection change
self._dict_inj = {}
# topology changed
self._set_topo_vect = np.full(shape=self.dim_topo, fill_value=0, dtype=dt_int)
self._change_bus_vect = np.full(
shape=self.dim_topo, fill_value=False, dtype=dt_bool
)
# add the hazards and maintenance usefull for saving.
self._hazards = np.full(shape=self.n_line, fill_value=False, dtype=dt_bool)
self._maintenance = np.full(shape=self.n_line, fill_value=False, dtype=dt_bool)
# redispatching vector
self._redispatch = np.full(shape=self.n_gen, fill_value=0.0, dtype=dt_float)
# storage unit vector
self._storage_power = np.full(
shape=self.n_storage, fill_value=0.0, dtype=dt_float
)
# curtailment of renewable energy
self._curtail = np.full(shape=self.n_gen, fill_value=-1.0, dtype=dt_float)
self._vectorized = None
self._lines_impacted = None
self._subs_impacted = None
# shunts
if self.shunts_data_available:
self.shunt_p = np.full(
shape=self.n_shunt, fill_value=np.NaN, dtype=dt_float
)
self.shunt_q = np.full(
shape=self.n_shunt, fill_value=np.NaN, dtype=dt_float
)
self.shunt_bus = np.full(shape=self.n_shunt, fill_value=0, dtype=dt_int)
else:
self.shunt_p = None
self.shunt_q = None
self.shunt_bus = None
self._single_act = True
self._raise_alarm = np.full(
shape=self.dim_alarms, dtype=dt_bool, fill_value=False
) # TODO
# change the stuff
self._modif_inj = False
self._modif_set_bus = False
self._modif_change_bus = False
self._modif_set_status = False
self._modif_change_status = False
self._modif_redispatch = False
self._modif_storage = False
self._modif_curtailment = False
self._modif_alarm = False
@classmethod
def process_shunt_data(cls):
if not cls.shunts_data_available:
# this is really important, otherwise things from grid2op base types will be affected
cls.attr_list_vect = copy.deepcopy(cls.attr_list_vect)
cls.attr_list_set = copy.deepcopy(cls.attr_list_set)
# remove the shunts from the list to vector
for el in ["shunt_p", "shunt_q", "shunt_bus"]:
if el in cls.attr_list_vect:
try:
cls.attr_list_vect.remove(el)
except ValueError:
pass
cls.attr_list_set = set(cls.attr_list_vect)
return super().process_shunt_data()
def copy(self) -> "BaseAction":
# sometimes this method is used...
return self.__deepcopy__()
def _aux_copy(self, other):
attr_simple = [
"_modif_inj",
"_modif_set_bus",
"_modif_change_bus",
"_modif_set_status",
"_modif_change_status",
"_modif_redispatch",
"_modif_storage",
"_modif_curtailment",
"_modif_alarm",
"_single_act",
]
attr_vect = [
"_set_line_status",
"_switch_line_status",
"_set_topo_vect",
"_change_bus_vect",
"_hazards",
"_maintenance",
"_redispatch",
"_storage_power",
"_curtail",
"_raise_alarm",
]
if self.shunts_data_available:
attr_vect += ["shunt_p", "shunt_q", "shunt_bus"]
for attr_nm in attr_simple:
setattr(other, attr_nm, getattr(self, attr_nm))
for attr_nm in attr_vect:
getattr(other, attr_nm)[:] = getattr(self, attr_nm)
def __copy__(self) -> "BaseAction":
res = type(self)()
self._aux_copy(other=res)
# handle dict_inj
for k, el in self._dict_inj.items():
res._dict_inj[k] = copy.copy(el)
# just copy
res._vectorized = self._vectorized
res._lines_impacted = self._lines_impacted
res._subs_impacted = self._subs_impacted
return res
@classmethod
def process_shunt_data(cls):
return super().process_shunt_data()
def __deepcopy__(self, memodict={}) -> "BaseAction":
res = type(self)()
self._aux_copy(other=res)
# handle dict_inj
for k, el in self._dict_inj.items():
res._dict_inj[k] = copy.deepcopy(el, memodict)
# just copy
res._vectorized = copy.deepcopy(self._vectorized, memodict)
res._lines_impacted = copy.deepcopy(self._lines_impacted, memodict)
res._subs_impacted = copy.deepcopy(self._subs_impacted, memodict)
return res
def as_serializable_dict(self) -> dict:
"""
This method returns an action as a dictionnary, that can be serialized using the "json" module.
It can be used to store the action into a grid2op indepependant format (the default action serialization, for speed, writes actions to numpy array.
The size of these arrays can change depending on grid2op versions, especially if some different types of actions are implemented).
Once you have these dictionnary, you can use them to build back the action from the action space.
Examples
---------
It can be used like:
.. code-block:: python
import grid2op
env_name = "l2rpn_case14_sandbox" # or anything else
env = grid2op.make(env_name)
act = env.action_space(...)
dict_ = act.as_serializable_dict() # you can save this dict with the json library
act2 = env.action_space(dict_)
act == act2
"""
res = {}
# bool elements
if self._modif_alarm:
res["raise_alarm"] = [
int(id_) for id_, val in enumerate(self._raise_alarm) if val
]
if self._modif_change_bus:
res["change_bus"] = [
int(id_) for id_, val in enumerate(self._change_bus_vect) if val
]
if self._modif_change_status:
res["change_line_status"] = [
int(id_) for id_, val in enumerate(self._switch_line_status) if val
]
# int elements
if self._modif_set_bus:
res["set_bus"] = [
(int(id_), int(val))
for id_, val in enumerate(self._set_topo_vect)
if val != 0
]
if self._modif_set_status:
res["set_line_status"] = [
(int(id_), int(val))
for id_, val in enumerate(self._set_line_status)
if val != 0
]
# float elements
if self._modif_redispatch:
res["redispatch"] = [
(int(id_), float(val))
for id_, val in enumerate(self._redispatch)
if val != 0.0
]
if self._modif_storage:
res["set_storage"] = [
(int(id_), float(val))
for id_, val in enumerate(self._storage_power)
if val != 0.0
]
if self._modif_curtailment:
res["curtail"] = [
(int(id_), float(val))
for id_, val in enumerate(self._curtail)
if val != -1
]
# more advanced options
if self._modif_inj:
res["injection"] = {}
for ky in ["prod_p", "prod_v", "load_p", "load_q"]:
if ky in self._dict_inj:
res["injection"][ky] = [float(val) for val in self._dict_inj[ky]]
if not res["injection"]:
del res["injection"]
if type(self).shunts_data_available:
res["shunt"] = {}
if np.any(np.isfinite(self.shunt_p)):
res["shunt"]["shunt_p"] = [
(int(sh_id), float(val)) for sh_id, val in enumerate(self.shunt_p)
]
if np.any(np.isfinite(self.shunt_q)):
res["shunt"]["shunt_q"] = [
(int(sh_id), float(val)) for sh_id, val in enumerate(self.shunt_q)
]
if np.any(self.shunt_bus != 0):
res["shunt"]["shunt_bus"] = [
(int(sh_id), int(val))
for sh_id, val in enumerate(self.shunt_bus)
if val != 0
]
if not res["shunt"]:
del res["shunt"]
return res
@classmethod
def _add_shunt_data(cls):
if cls.shunt_added is False and cls.shunts_data_available:
cls.shunt_added = True
cls.attr_list_vect = copy.deepcopy(cls.attr_list_vect)
cls.attr_list_vect += ["shunt_p", "shunt_q", "shunt_bus"]
cls.authorized_keys = copy.deepcopy(cls.authorized_keys)
cls.authorized_keys.add("shunt")
cls.attr_nan_list_set.add("shunt_p")
cls.attr_nan_list_set.add("shunt_q")
cls._update_value_set()
def alarm_raised(self) -> np.ndarray:
"""
INTERNAL
This function is used to know if the given action aimed at raising an alarm or not.
Returns
-------
res: numpy array
The indexes of the areas where the agent has raised an alarm.
"""
return np.where(self._raise_alarm)[0]
@classmethod
def process_grid2op_compat(cls):
if cls.glop_version == cls.BEFORE_COMPAT_VERSION:
# oldest version: no storage and no curtailment available
# this is really important, otherwise things from grid2op base types will be affected
cls.authorized_keys = copy.deepcopy(cls.authorized_keys)
cls.attr_list_vect = copy.deepcopy(cls.attr_list_vect)
cls.attr_list_set = copy.deepcopy(cls.attr_list_set)
# deactivate storage
cls.set_no_storage()
if "set_storage" in cls.authorized_keys:
cls.authorized_keys.remove("set_storage")
if "_storage_power" in cls.attr_list_vect:
cls.attr_list_vect.remove("_storage_power")
cls.attr_list_set = set(cls.attr_list_vect)
# remove the curtailment
if "curtail" in cls.authorized_keys:
cls.authorized_keys.remove("curtail")
if "_curtail" in cls.attr_list_vect:
cls.attr_list_vect.remove("_curtail")
cls.attr_list_set = set(cls.attr_list_vect)
if cls.glop_version < "1.6.0":
# this feature did not exist before.
cls.dim_alarms = 0
def _reset_modified_flags(self):
self._modif_inj = False
self._modif_set_bus = False
self._modif_change_bus = False
self._modif_set_status = False
self._modif_change_status = False
self._modif_redispatch = False
self._modif_storage = False
self._modif_curtailment = False
self._modif_alarm = False
def can_affect_something(self) -> bool:
"""
This functions returns True if the current action has any chance to change the grid.
Notes
-----
This does not say however if the action will indeed modify something somewhere !
"""
return (
self._modif_inj
or self._modif_set_bus
or self._modif_change_bus
or self._modif_set_status
or self._modif_change_status
or self._modif_redispatch
or self._modif_storage
or self._modif_curtailment
or self._modif_alarm
)
def _get_array_from_attr_name(self, attr_name):
if hasattr(self, attr_name):
res = super()._get_array_from_attr_name(attr_name)
else:
if attr_name in self._dict_inj:
res = self._dict_inj[attr_name]
else:
if attr_name == "prod_p" or attr_name == "prod_v":
res = np.full(self.n_gen, fill_value=0.0, dtype=dt_float)
elif attr_name == "load_p" or attr_name == "load_q":
res = np.full(self.n_load, fill_value=0.0, dtype=dt_float)
else:
raise Grid2OpException(
'Impossible to find the attribute "{}" '
'into the BaseAction of type "{}"'.format(attr_name, type(self))
)
return res
def _post_process_from_vect(self):
self._modif_inj = self._dict_inj != {}
self._modif_set_bus = np.any(self._set_topo_vect != 0)
self._modif_change_bus = np.any(self._change_bus_vect)
self._modif_set_status = np.any(self._set_line_status != 0)
self._modif_change_status = np.any(self._switch_line_status)
self._modif_redispatch = np.any(
np.isfinite(self._redispatch) & (self._redispatch != 0.0)
)
self._modif_storage = np.any(self._storage_power != 0.0)
self._modif_curtailment = np.any(self._curtail != -1.0)
self._modif_alarm = np.any(self._raise_alarm)
def _assign_attr_from_name(self, attr_nm, vect):
if hasattr(self, attr_nm):
if attr_nm not in type(self).attr_list_set:
raise AmbiguousAction(
f"Impossible to modify attribute {attr_nm} with this action type."
)
super()._assign_attr_from_name(attr_nm, vect)
self._post_process_from_vect()
else:
if np.any(np.isfinite(vect)):
if np.any(vect != 0.0):
self._dict_inj[attr_nm] = vect
def check_space_legit(self):
"""
This method allows to check if this method is ambiguous **per se** (defined more formally as:
whatever the observation at time *t*, and the changes that can occur between *t* and *t+1*, this
action will be ambiguous).
For example, an action that try to assign something to busbar 3 will be ambiguous *per se*. An action
that tries to dispatch a non dispatchable generator will be also ambiguous *per se*.
However, an action that "switch" (change) the status (connected / disconnected) of a powerline can be
ambiguous and it will not be detected here. This is because the ambiguity depends on the current state
of the powerline:
- if the powerline is disconnected, changing its status means reconnecting it. And we cannot reconnect a
powerline without specifying on which bus.
- on the contrary if the powerline is connected, changing its status means disconnecting it, which is
always feasible.
In case of "switch" as we see here, the action can be ambiguous, but not ambiguous *per se*. This method
will **never** throw any error in this case.
Raises
-------
:class:`grid2op.Exceptions.AmbiguousAction`
Or any of its more precise subclasses, depending on which assumption is not met.
"""
self._check_for_ambiguity()
def get_set_line_status_vect(self) -> np.ndarray:
"""
Computes and returns a vector that can be used in the :func:`BaseAction.__call__` with the keyword
"set_status" if building an :class:`BaseAction`.
**NB** this vector is not the internal vector of this action but corresponds to "do nothing" action.
Returns
-------
res: :class:`numpy.array`, dtype:dt_int
A vector that doesn't affect the grid, but can be used in :func:`BaseAction.__call__` with the keyword
"set_status" if building an :class:`BaseAction`.
"""
return np.full(shape=self.n_line, fill_value=0, dtype=dt_int)
def get_change_line_status_vect(self) -> np.ndarray:
"""
Computes and returns a vector that can be used in the :func:`BaseAction.__call__` with the keyword
"set_status" if building an :class:`BaseAction`.
**NB** this vector is not the internal vector of this action but corresponds to "do nothing" action.
Returns
-------
res: :class:`numpy.array`, dtype:dt_bool
A vector that doesn't affect the grid, but can be used in :func:`BaseAction.__call__` with the keyword
"set_status" if building an :class:`BaseAction`.
"""
return np.full(shape=self.n_line, fill_value=False, dtype=dt_bool)
def __eq__(self, other) -> bool:
"""
Test the equality of two actions.
2 actions are said to be identical if they have the same impact on the powergrid. This is unrelated to their
respective class. For example, if an Action is of class :class:`Action` and doesn't act on the injection, it
can be equal to an Action of the derived class :class:`TopologyAction` (if the topological modifications are the
same of course).
This implies that the attributes :attr:`Action.authorized_keys` is not checked in this method.
Note that if 2 actions don't act on the same powergrid, or on the same backend (eg number of loads, or
generators are not the same in *self* and *other*, or they are not in the same order) then action will be
declared as different.
**Known issue** if two backends are different, but the description of the _grid are identical (ie all
n_gen, n_load, n_line, sub_info, dim_topo, all vectors \*_to_subid, and \*_pos_topo_vect are
identical) then this method will not detect the backend are different, and the action could be declared
as identical. For now, this is only a theoretical behavior: if everything is the same, then probably, up to
the naming convention, then the power grids are identical too.
Parameters
----------
other: :class:`BaseAction`
An instance of class Action to which "self" will be compared.
Returns
-------
res: ``bool``
Whether the actions are equal or not.
"""
if other is None:
return False
# check that the underlying grid is the same in both instances
same_grid = type(self).same_grid_class(type(other))
if not same_grid:
return False
# _grid is the same, now I test the the injections modifications are the same
same_action = self._modif_inj == other._modif_inj
same_action = same_action and self._dict_inj.keys() == other._dict_inj.keys()
if not same_action:
return False
# all injections are the same
for el in self._dict_inj.keys():
me_inj = self._dict_inj[el]
other_inj = other._dict_inj[el]
tmp_me = np.isfinite(me_inj)
tmp_other = np.isfinite(other_inj)
if not np.all(tmp_me == tmp_other) or not np.all(
me_inj[tmp_me] == other_inj[tmp_other]
):
return False
# same line status
if (self._modif_set_status != other._modif_set_status) or not np.all(
self._set_line_status == other._set_line_status
):
return False
if (self._modif_change_status != other._modif_change_status) or not np.all(
self._switch_line_status == other._switch_line_status
):
return False
# redispatching is same
if (self._modif_redispatch != other._modif_redispatch) or not np.all(
self._redispatch == other._redispatch
):
return False
# storage is same
me_inj = self._storage_power
other_inj = other._storage_power
tmp_me = np.isfinite(me_inj)
tmp_other = np.isfinite(other_inj)
if not np.all(tmp_me == tmp_other) or not np.all(
me_inj[tmp_me] == other_inj[tmp_other]
):
return False
# curtailment
if (self._modif_curtailment != other._modif_curtailment) or not np.array_equal(
self._curtail, other._curtail
):
return False
# alarm
if (self._modif_alarm != other._modif_alarm) or not np.array_equal(
self._raise_alarm, other._raise_alarm
):
return False
# same topology changes
if (self._modif_set_bus != other._modif_set_bus) or not np.all(
self._set_topo_vect == other._set_topo_vect
):
return False
if (self._modif_change_bus != other._modif_change_bus) or not np.all(
self._change_bus_vect == other._change_bus_vect
):
return False
# shunts are the same
if self.shunts_data_available:
if self.n_shunt != other.n_shunt:
return False
is_ok_me = np.isfinite(self.shunt_p)
is_ok_ot = np.isfinite(other.shunt_p)
if np.any(is_ok_me != is_ok_ot):
return False
if not np.all(self.shunt_p[is_ok_me] == other.shunt_p[is_ok_ot]):
return False
is_ok_me = np.isfinite(self.shunt_q)
is_ok_ot = np.isfinite(other.shunt_q)
if np.any(is_ok_me != is_ok_ot):
return False
if not np.all(self.shunt_q[is_ok_me] == other.shunt_q[is_ok_ot]):
return False
if not np.all(self.shunt_bus == other.shunt_bus):
return False
return True
def _dont_affect_topology(self) -> bool:
return (
(not self._modif_set_bus)
and (not self._modif_change_bus)
and (not self._modif_set_status)
and (not self._modif_change_status)
)
def get_topological_impact(self, powerline_status=None) -> Tuple[np.ndarray, np.ndarray]:
"""
Gives information about the element being impacted by this action.
**NB** The impacted elements can be used by :class:`grid2op.BaseRules` to determine whether or not an action
is legal or not.
**NB** The impacted are the elements that can potentially be impacted by the action. This does not mean they
will be impacted. For examples: