-
Notifications
You must be signed in to change notification settings - Fork 113
/
test_alert_trust_score.py
1885 lines (1651 loc) · 93.7 KB
/
test_alert_trust_score.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-2023, 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 unittest
import os
import tempfile
from grid2op.Observation import BaseObservation
from grid2op.tests.helper_path_test import *
from grid2op import make
from grid2op.Reward import _AlertTrustScore
from grid2op.Parameters import Parameters
from grid2op.Exceptions import Grid2OpException
from grid2op.Runner import Runner
from grid2op.Action import BaseAction, PlayableAction
from grid2op.Agent import BaseAgent
from grid2op.Episode import EpisodeData
from _aux_opponent_for_test_alerts import (_get_steps_attack,
TestOpponent,
TestOpponentMultiLines,
_get_blackout)
ATTACKED_LINE = "48_50_136"
DEFAULT_PARAMS_TRUSTSCORE = dict(reward_min_no_blackout=-1.0,
reward_min_blackout=-50.0,
reward_max_no_blackout=0.0,
reward_max_blackout=0.0,
reward_end_episode_bonus=0.0,
min_score=-3.0)
#a near copy of _normalisation_fun function from alertTrusScore. Use when, for to a given trustscore parametrization,
# it is not easy to guess the score before hand, for a given scenario.
# especially when reward_end_episode_bonus is non null for some non blackout cases
def manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,max_score):
manual_standardized_score= np.round((cm_reward - cm_reward_min_ep) / (cm_reward_max_ep - cm_reward_min_ep + 1e-5), 4)
manual_score = DEFAULT_PARAMS_TRUSTSCORE["min_score"] + (
max_score - DEFAULT_PARAMS_TRUSTSCORE[
"min_score"]) * manual_standardized_score
return manual_score
# Test alertTrustScore when no blackout and when blackout
class TestAlertTrustScoreNoBlackout(unittest.TestCase):
"""test the basic behavior of the assistant alert feature when no blackout occur """
def setUp(self) -> None:
""" WARNING: Parameter ALERT_TIME_WINDOW should be set to 2 in these test for the environment used
Max Iter should be set to 10
"""
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
#this is the test case no blakcout where it reaches max score
def test_assistant_trust_score_no_blackout_no_attack_no_alert(self) -> None :
""" When no blackout and no attack occur, and no alert is raised we expect a maximum score
at the end of the episode and cumulated reward equal to the end of episode bonus
Raises:
Grid2OpException: raise an exception if an attack occur
"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
obs, score, done, info = env.step(env.action_space())
if info["opponent_attack_line"] is None :
if i == env.max_episode_duration()-1:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks= env._reward_helper.template_reward.nb_last_attacks
assert total_nb_attacks==0
assert nb_last_attacks==0
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == 0.
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]
assert score == env._reward_helper.template_reward.max_score
else :
assert score == 0
else :
raise Grid2OpException('No attack expected')
assert done
# this is the test case no blakcout where it reaches min score
def test_assistant_trust_score_no_blackout_attack_alert(self) -> None :
"""When we raise an alert for an attack (at step 1)
and no blackout occur, we expect a minimum score
at the end of the episode if end of episode bonus is null (or above otherwise), a cumulated reward equal to reward_min_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnba"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if i == 1 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1
cm_reward=env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]+ DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]+DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
assert score == DEFAULT_PARAMS_TRUSTSCORE["min_score"] # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > DEFAULT_PARAMS_TRUSTSCORE["min_score"]
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else :
assert score == 0
# this is the test case no blakcout where it reaches mean score ( a score in the middle)
def test_assistant_trust_score_no_blackout_2_attack_same_time_1_alert(self) -> None:
""" When we raise only 1 alert for 2 attacks at the same time (step 2) (considered as a single attack event)
but no blackout occur, we expect a mean score
at the end of the episode if no end of episode bonus,
a cumulated reward equal to (reward_max_no_blackout + reward_min_no_blackout)/2 end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE] + ['48_53_141'],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tatsnb2ast1a"
) as env:
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 1:
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1 # 1 because two simultaneaous attacks is considered as a signgle attack event
cm_reward = env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward == (
DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]) / 2 + \
DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE[
"reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
max_score = env._reward_helper.template_reward.max_score
mean_score = (max_score + DEFAULT_PARAMS_TRUSTSCORE["min_score"]) / 2
assert score == mean_score # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > mean_score
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else:
assert score == 0
def test_assistant_trust_score_no_blackout_no_attack_alert(self) -> None:
""" When an alert is raised while no attack / nor blackout occur, we expect a maximum score
at the end of the episode and cumulated reward equal to the end of episode bonus
Raises:
Grid2OpException: raise an exception if an attack occur
"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE)
) as env:
env.seed(0)
env.reset()
done = False
attackable_line_id = 0
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1:
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if info["opponent_attack_line"] is None:
if step == env.max_episode_duration():
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert total_nb_attacks == 0
assert nb_last_attacks == 0
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
"reward_end_episode_bonus"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)
assert cm_reward_min_ep == 0.
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]
assert score == env._reward_helper.template_reward.max_score
else:
assert score == 0
else:
raise Grid2OpException('No attack expected')
assert done
# If attack
def test_assistant_trust_score_no_blackout_attack_no_alert(self) -> None:
""" When we don't raise an alert for an attack (at step 1)
and no blackout occur, we expect a maximum score
at the end of the episode, a cumulated reward equal to reward_max_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[1])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnbana"
) as env:
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert np.round(score, 3) == env._reward_helper.template_reward.max_score
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
"reward_end_episode_bonus"] + DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
else:
assert score == 0
def test_assistant_trust_score_no_blackout_attack_alert_too_late(self) -> None :
""" When we raise an alert too late for an attack (at step 2) but no blackout occur,
we expect a maximum score at the end of the episode,
a cumulated reward equal to reward_max_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tatsnbaatl"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 2 :
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert score == env._reward_helper.template_reward.max_score
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] +\
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"]+DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
else :
assert score == 0
def test_assistant_trust_score_no_blackout_attack_alert_too_early(self)-> None :
""" When we raise an alert too early for an attack (at step 2)
we expect a maximum score at the end of the episode,
a cumulated reward equal to reward_max_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tatsnbaate"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = env.action_space()
if step == 0 :
# An alert is raised at step 0
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert score == env._reward_helper.template_reward.max_score
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] +\
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
else :
assert score == 0
# 2 ligne attaquées
def test_assistant_trust_score_no_blackout_2_attack_same_time_no_alert(self) -> None :
""" When we don't raise an alert for 2 attacks at the same time (step 1) (considered as a single attack event)
but no blackout occur, we expect a maximum score
at the end of the episode, a cumulated reward equal to reward_max_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[1])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnb2astna"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1 #1 because to simultaneaous attacks is considered as a signgle attack event
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] +\
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]*total_nb_attacks
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]*total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]*total_nb_attacks
assert score == env._reward_helper.template_reward.max_score
else :
assert score == 0
def test_assistant_trust_score_no_blackout_2_attack_same_time_2_alert(self) -> None :
""" When we raise 2 alerts for 2 attacks at the same time (step 2) (considered as a single attack event)
but no blackout occur, we expect a minimum score
at the end of the episode if no end of episode bonus,
a cumulated reward equal to reward_min_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=3,
steps_attack=[2])
with make(self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
_add_to_name="_tatsnb2ast2a"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_ids = [0, 1]
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": attackable_line_ids})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 1 #1 because to simultaneaous attacks is considered as a signgle attack event
cm_reward=env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
assert score == DEFAULT_PARAMS_TRUSTSCORE["min_score"] # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > DEFAULT_PARAMS_TRUSTSCORE["min_score"]
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else :
assert score == 0
def test_assistant_trust_score_no_blackout_2_attack_diff_time_no_alert(self) -> None :
""" When we raise 2 alerts for 2 attacks at the same time (step 2)
but no blackout occur, we expect a maximum score at the end of the episode,
a cumulated reward equal to 2*reward_max_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1, 1],
steps_attack=[1, 2])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnb2dtna"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True) :
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert score == env._reward_helper.template_reward.max_score
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 2
assert env._reward_helper.template_reward.cumulated_reward==DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] +\
total_nb_attacks*DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
else :
assert score == 0
def test_assistant_trust_score_no_blackout_2_attack_diff_time_2_alert(self) -> None :
""" When we raise 2 alerts for 2 attacks at the same time (step 2)
but no blackout occur, we expect a minimum score at the end of the episode if no bonus,
a cumulated reward equal to 2*reward_min_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnb2dt2a"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [0]})
elif step == 2 :
act = env.action_space({"raise_alert": [1]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 2
cm_reward=env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
"reward_end_episode_bonus"] + \
total_nb_attacks * DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
assert score == DEFAULT_PARAMS_TRUSTSCORE["min_score"] # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > DEFAULT_PARAMS_TRUSTSCORE["min_score"]
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else :
assert score == 0
def test_assistant_trust_score_no_blackout_2_attack_diff_time_alert_first_attack(self) -> None :
""" When we raise 2 alerts for 2 attacks at the same time (step 2)
but no blackout occur, we expect a mean score at the end of the episode if no bonus,
a cumulated reward equal to reward_max_no_blackout + reward_min_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnb2dtafa"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if step == 1 :
act = env.action_space({"raise_alert": [0]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 2
cm_reward=env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
"reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"]+DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
max_score=env._reward_helper.template_reward.max_score
mean_score=(max_score + DEFAULT_PARAMS_TRUSTSCORE["min_score"]) / 2
assert score == mean_score # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > mean_score
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else :
assert score == 0
def test_assistant_trust_score_no_blackout_2_attack_diff_time_alert_second_attack(self) -> None :
""" When we raise 1 alert on the second attack while we have 2 attacks at two times (steps 2 and 3)
but no blackout occur, we expect a mean score at the end of the episode if no bonus,
a cumulated reward equal to reward_max_no_blackout + reward_min_no_blackout + end of episode bonus.
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE]+['48_53_141'],
duration=[1,1],
steps_attack=[2, 3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponentMultiLines,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsnb2dtasa"
) as env :
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
act = env.action_space()
if i == 2 :
act = env.action_space({"raise_alert": [1]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent, multi=True):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 2
cm_reward=env._reward_helper.template_reward.cumulated_reward
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
"reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] + DEFAULT_PARAMS_TRUSTSCORE[
"reward_max_no_blackout"]
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks,nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_min_no_blackout"] * total_nb_attacks
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE["reward_end_episode_bonus"] + \
DEFAULT_PARAMS_TRUSTSCORE["reward_max_no_blackout"] * total_nb_attacks
max_score=env._reward_helper.template_reward.max_score
mean_score=(max_score + DEFAULT_PARAMS_TRUSTSCORE["min_score"]) / 2
assert score == mean_score # because reward_end_episode_bonus == 0
# Can Be used if reward_end_episode_bonus!=0
# assert score > mean_score
# assert score == manual_score (cm_reward,cm_reward_min_ep,cm_reward_max_ep,env._reward_helper.template_reward.max_score)
else :
assert score == 0, f"error for step {step}: {score} vs 0"
class TestAlertTrustScoreBlackout_NoAttackCause(unittest.TestCase):
def setUp(self) -> None:
""" WARNING: Parameter ALERT_TIME_WINDOW should be set to 2 in these test for the environment used
Max Iter should be set to 10"""
self.env_nm = os.path.join(
PATH_DATA_TEST, "l2rpn_idf_2023_with_alert"
)
def get_dn(self, env):
return env.action_space({})
def get_blackout(self, env):
return _get_blackout(env.action_space)
# this is the test case a blackout occur but not because of an attack and you get a maximum score
def test_assistant_trust_score_blackout_attack_nocause_blackout_no_alert(self) -> None:
"""When 1 line is attacked at step 3 and you don't raise an alert
and a blackout occur at step 7 (not considered as because of the attack because outside of the alert time window)
we expect a minimum score,
a cumulated reward equal to reward_max_no_blackout
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsbarga"
) as env:
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 7:
act = self.get_blackout(env)
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert score == env._reward_helper.template_reward.max_score
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0 # because no attack caused the blackout
assert total_nb_attacks == 1
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
'reward_max_no_blackout']
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE['reward_min_no_blackout']
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE['reward_max_no_blackout']
break
else:
assert score == 0
# this is the test case a blackout occur but not because of an attack and you get a minimum score
def test_assistant_trust_score_blackout_attack_nocause_blackout_raise_alert(self) -> None:
"""When 1 line is attacked at step 3 and we raise an alert
and a blackout occur at step 7 (not considered as because of the attack because outside of the alert time window)
we expect a minimum score,
a cumulated reward equal to reward_min_no_blackout
score is otherwise 0 at other time steps
"""
kwargs_opponent = dict(lines_attacked=[ATTACKED_LINE],
duration=3,
steps_attack=[3])
with make(self.env_nm,
test=True,
difficulty="1",
opponent_attack_cooldown=0,
opponent_attack_duration=99999,
opponent_budget_per_ts=1000,
opponent_init_budget=10000.,
opponent_action_class=PlayableAction,
opponent_class=TestOpponent,
kwargs_opponent=kwargs_opponent,
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE),
_add_to_name="_tatsbarga"
) as env:
new_param = Parameters()
new_param.MAX_LINE_STATUS_CHANGED = 10
env.change_parameters(new_param)
env.seed(0)
env.reset()
step = 0
for i in range(env.max_episode_duration()):
attackable_line_id = 0
act = self.get_dn(env)
if i == 7:
act = self.get_blackout(env)
elif i == 2:
# I raise the alert (on the right line) just before the opponent attack
# opp attack at step = 3, so i = 2
act = env.action_space({"raise_alert": [attackable_line_id]})
obs, score, done, info = env.step(act)
step += 1
if step in _get_steps_attack(kwargs_opponent):
assert info["opponent_attack_line"] is not None, f"no attack is detected at step {step}"
else:
assert info["opponent_attack_line"] is None, f"an attack is detected at step {step}"
if done:
assert score == DEFAULT_PARAMS_TRUSTSCORE["min_score"]
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0 # because no attack caused the blackout
assert total_nb_attacks == 1
assert env._reward_helper.template_reward.cumulated_reward == DEFAULT_PARAMS_TRUSTSCORE[
'reward_min_no_blackout']
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)
assert cm_reward_min_ep == DEFAULT_PARAMS_TRUSTSCORE['reward_min_no_blackout']
assert cm_reward_max_ep == DEFAULT_PARAMS_TRUSTSCORE['reward_max_no_blackout']
break
else:
assert score == 0
# this is the test case a blackout occur but not because of an attack and you get a score of 0 (in the middle)
def test_assistant_trust_score_blackout_no_attack_alert(self) -> None:
"""Even if there is a blackout, an we raise an alert
we expect a score of 0 because there is no attack and we don't finish the scenario"""
with make(
self.env_nm,
test=True,
difficulty="1",
reward_class=_AlertTrustScore(**DEFAULT_PARAMS_TRUSTSCORE)
) as env:
env.seed(0)
env.reset()
done = False
for i in range(env.max_episode_duration()):
act = self.get_dn(env)
if i == 3:
act = self.get_blackout(env)
elif i == 1:
act = env.action_space({"raise_alert": [0]})
obs, score, done, info = env.step(act)
if info["opponent_attack_line"] is None:
if done: # info["opponent_attack_line"] is None :
assert score == 0.
total_nb_attacks = env._reward_helper.template_reward.total_nb_attacks
nb_last_attacks = env._reward_helper.template_reward.nb_last_attacks
assert nb_last_attacks == 0
assert total_nb_attacks == 0
assert env._reward_helper.template_reward.total_nb_attacks == 0.
assert env._reward_helper.template_reward.cumulated_reward == 0.
cm_reward_min_ep, cm_reward_max_ep = env._reward_helper.template_reward._compute_min_max_reward(
total_nb_attacks, nb_last_attacks)