-
Notifications
You must be signed in to change notification settings - Fork 19
/
WCAImpl.java
1155 lines (1059 loc) · 94 KB
/
WCAImpl.java
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) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
* Copyright (c) 2016-2018, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package eu.itesla_project.wca;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import com.powsybl.computation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.gdata.util.common.base.Pair;
import com.powsybl.commons.util.StringToIntMapper;
import com.powsybl.contingency.Contingency;
import com.powsybl.commons.datasource.DataSource;
import com.powsybl.commons.datasource.FileDataSource;
import eu.itesla_project.iidm.export.ampl.AmplExportConfig;
import eu.itesla_project.iidm.export.ampl.AmplNetworkWriter;
import eu.itesla_project.iidm.export.ampl.AmplSubset;
import eu.itesla_project.iidm.export.ampl.AmplUtil;
import com.powsybl.iidm.network.Network;
import com.powsybl.loadflow.LoadFlow;
import com.powsybl.loadflow.LoadFlowFactory;
import com.powsybl.loadflow.LoadFlowParameters;
import com.powsybl.loadflow.LoadFlowResult;
import eu.itesla_project.modules.constraints.ConstraintsModifier;
import eu.itesla_project.modules.constraints.ConstraintsModifierConfig;
import eu.itesla_project.modules.contingencies.Action;
import eu.itesla_project.modules.contingencies.ContingenciesAndActionsDatabaseClient;
import eu.itesla_project.modules.histo.HistoDbAttributeId;
import eu.itesla_project.modules.histo.HistoDbClient;
import eu.itesla_project.modules.histo.IIDM2DB;
import eu.itesla_project.modules.rules.RuleAttributeSet;
import eu.itesla_project.modules.rules.RuleId;
import eu.itesla_project.modules.rules.RulesDbClient;
import eu.itesla_project.modules.rules.SecurityRule;
import eu.itesla_project.modules.rules.SecurityRuleCheckReport;
import eu.itesla_project.modules.rules.SecurityRuleExpression;
import eu.itesla_project.modules.wca.Uncertainties;
import eu.itesla_project.modules.wca.UncertaintiesAnalyserFactory;
import eu.itesla_project.modules.wca.WCA;
import eu.itesla_project.modules.wca.WCAAsyncResult;
import eu.itesla_project.modules.wca.WCACluster;
import eu.itesla_project.modules.wca.WCAClusterNum;
import eu.itesla_project.modules.wca.WCAParameters;
import eu.itesla_project.modules.wca.WCAResult;
import eu.itesla_project.modules.wca.report.WCAActionApplication;
import eu.itesla_project.modules.wca.report.WCALoadflowResult;
import eu.itesla_project.modules.wca.report.WCAPostContingencyStatus;
import eu.itesla_project.modules.wca.report.WCAReport;
import eu.itesla_project.modules.wca.report.WCARuleViolationType;
import eu.itesla_project.modules.wca.report.WCASecurityRuleApplication;
import com.powsybl.security.LimitViolation;
import com.powsybl.security.LimitViolationFilter;
import com.powsybl.security.LimitViolationType;
import com.powsybl.security.Security;
import com.powsybl.simulation.securityindexes.SecurityIndexId;
import com.powsybl.simulation.securityindexes.SecurityIndexType;
import eu.itesla_project.wca.report.WCAReportImpl;
import eu.itesla_project.wca.uncertainties.UncertaintiesAmplWriter;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
public class WCAImpl implements WCA, WCAConstants {
private static final Logger LOGGER = LoggerFactory.getLogger(WCAImpl.class);
private static final String CLUSTERS_CMD_ID = "wca_clusters";
private static final String DOMAINS_CMD_ID = "wca_domains";
private static final String CLUSTERS_WORKING_DIR_PREFIX = "itesla_wca_clusters_";
private static final String DOMAINS_WORKING_DIR_PREFIX = "itesla_wca_domains_";
private static final String REQUIRED_FILE_NAME = "required";
private static final String[] COMMON_INPUT_FILE_NAMES = {
MEANS_FILE_SUFFIX + "." + TXT_EXT,
TRUST_INTERVAL_FILE_SUFFIX + "." + TXT_EXT,
REDUCTION_MATRIX_FILE_SUFFIX + "." + TXT_EXT,
HISTO_LOADS_FILE_SUFFIX + "." + TXT_EXT,
HISTO_GENERATORS_FILE_SUFFIX + "." + TXT_EXT
};
private static final String[] INPUT_FILE_NAMES = {
FAULTS_FILE_SUFFIX + "." + TXT_EXT,
ACTIONS_FILE_SUFFIX + "." + TXT_EXT,
SECURITY_RULES_FILE_SUFFIX + "." + TXT_EXT,
"_network_generators.txt",
"_network_ptc.txt",
"_network_substations.txt",
"_network_branches.txt",
"_network_limits.txt",
"_network_rtc.txt",
"_network_tct.txt",
"_network_buses.txt",
"_network_loads.txt",
"_network_shunts.txt",
};
private static final int THREADS = 1;
private static final float UNCERTAINTY_THRESHOLD = 50f;
private static final int DETAILS_LEVEL_NORMAL = 2;
private static final int DETAILS_LEVEL_DEBUG = 4;
private static final String WCA_FLOWS_FILE = "wca_flows.txt";
private static final String WCA_UNCERTAINTIES_FILE = "wca_uncertainties.txt";
private static final String WCA_UNDEFINED_PST_FILE = "wca_undefined_pst.txt";
private static final String WCA_SENSIBILITIES_FILE = "wca_sensibilities.txt";
private static final String WCA_INFLUENCE_PST_FILE = "wca_influence_pst.txt";
private final Network network;
private final ComputationManager computationManager;
private final HistoDbClient histoDbClient;
private final RulesDbClient rulesDbClient;
private final UncertaintiesAnalyserFactory uncertaintiesAnalyserFactory;
private final ContingenciesAndActionsDatabaseClient contingenciesActionsDbClient;
private final LoadFlowFactory loadFlowFactory;
private final WCAConfig config;
private final Map<String, String> env;
private final LimitViolationFilter violationsFilter;
private WCAReportImpl wcaReport;
public WCAImpl(Network network, ComputationManager computationManager, HistoDbClient histoDbClient,
RulesDbClient rulesDbClient, UncertaintiesAnalyserFactory uncertaintiesAnalyserFactory,
ContingenciesAndActionsDatabaseClient contingenciesActionsDbClient, LoadFlowFactory loadFlowFactory,
WCAConfig config) {
this.network = Objects.requireNonNull(network, "network is null");
this.computationManager = Objects.requireNonNull(computationManager, "computationManager is null");
this.histoDbClient = Objects.requireNonNull(histoDbClient, "histoDbClient is null");
this.rulesDbClient = Objects.requireNonNull(rulesDbClient, "rulesDbClient is null");
this.uncertaintiesAnalyserFactory = Objects.requireNonNull(uncertaintiesAnalyserFactory, "uncertaintiesAnalyserFactory is null");
this.contingenciesActionsDbClient = Objects.requireNonNull(contingenciesActionsDbClient, "contingenciesActionsDbClient is null");
this.loadFlowFactory = Objects.requireNonNull(loadFlowFactory, "loadFlowFactory is null");
this.config = Objects.requireNonNull(config, "config is null");
LOGGER.info(config.toString());
this.violationsFilter = new LimitViolationFilter().setViolationTypes(config.ignoreVoltageConstraints() ? EnumSet.of(LimitViolationType.CURRENT) : null)
.setMinBaseVoltage(config.getVoltageLevelConstraintFilter())
.setCountries(config.getCountryConstraintFilter().isEmpty() ? null : config.getCountryConstraintFilter());
this.wcaReport = new WCAReportImpl(network);
env = ImmutableMap.of("XPRESS", config.getXpressHome().resolve("bin").toString(),
"LD_LIBRARY_PATH", config.getXpressHome().resolve("lib").toString());
}
private static final AmplExportConfig DOMAINS_AMPL_EXPORT_CONFIG = new AmplExportConfig(AmplExportConfig.ExportScope.ONLY_MAIN_CC_AND_CONNECTABLE_GENERATORS_AND_SHUNTS_AND_ALL_LOADS,
false,
AmplExportConfig.ExportActionType.PREVENTIVE);
private static final AmplExportConfig CLUSTERS_AMPL_EXPORT_CONFIG = new AmplExportConfig(AmplExportConfig.ExportScope.ONLY_MAIN_CC_AND_CONNECTABLE_GENERATORS_AND_SHUNTS_AND_ALL_LOADS,
false,
AmplExportConfig.ExportActionType.CURATIVE);
private static final LoadFlowParameters LOAD_FLOW_PARAMETERS = new LoadFlowParameters()
.setVoltageInitMode(LoadFlowParameters.VoltageInitMode.UNIFORM_VALUES)
.setTransformerVoltageControlOn(false)
.setNoGeneratorReactiveLimits(false)
.setPhaseShifterRegulationOn(false);
private SecurityIndexType[] getSecurityIndexTypes(WCAParameters parameters) {
return parameters.getSecurityIndexTypes() != null
? parameters.getSecurityIndexTypes().toArray(new SecurityIndexType[parameters.getSecurityIndexTypes().size()])
: SecurityIndexType.values();
}
private List<InputFile> inputFiles(int dataSetNum) {
List<InputFile> inputFiles = new ArrayList<>(INPUT_FILE_NAMES.length + 1);
inputFiles.add(new InputFile(REQUIRED_FILE_NAME));
for (String inputFileName : COMMON_INPUT_FILE_NAMES) {
inputFiles.add(new InputFile(COMMONE_FILE_PREFIX + inputFileName));
}
for (String inputFileName : INPUT_FILE_NAMES) {
inputFiles.add(new InputFile(FILE_PREFIX + dataSetNum + inputFileName));
}
return inputFiles;
}
private static void copyRequired(Path workingDir) throws IOException {
Files.copy(WCAImpl.class.getResourceAsStream("/" + REQUIRED_FILE_NAME), workingDir.resolve(REQUIRED_FILE_NAME));
}
private CompletableFuture<WCAClustersResult> createClustersTask(Contingency contingency,
List<String> curativeActionIds,
String baseStateId,
String contingencyStateId,
List<String> curativeStateIds,
List<SecurityRuleExpression> securityRuleExpressions,
Uncertainties uncertainties,
WCAHistoLimits histoLimits,
StringToIntMapper<AmplSubset> mapper,
boolean activateFiltering) {
return computationManager.execute(new ExecutionEnvironment(env, CLUSTERS_WORKING_DIR_PREFIX, config.isDebug()),
new AbstractExecutionHandler<WCAClustersResult>() {
@Override
public List<CommandExecution> before(Path workingDir) throws IOException {
network.getStateManager().setWorkingState(baseStateId);
copyRequired(workingDir);
DataSource commonDataSource = new FileDataSource(workingDir, COMMONE_FILE_PREFIX);
// write uncertainies
new UncertaintiesAmplWriter(uncertainties, commonDataSource, mapper).write();
// write historical interval
histoLimits.write(commonDataSource, mapper);
int contingencyNum = mapper.newInt(AmplSubset.FAULT, contingency.getId());
int dataSetNum = contingencyNum - 1;
DataSource dataSource = new FileDataSource(workingDir, FILE_PREFIX + dataSetNum);
// write base state
AmplUtil.resetNetworkMapping(mapper);
AmplUtil.fillMapper(mapper, network);
new AmplNetworkWriter(network, dataSource, 0, 0, false, mapper, CLUSTERS_AMPL_EXPORT_CONFIG).write();
if (config.isExportStates()) {
WCAUtils.exportState(network, workingDir, 0, 0);
}
// write post contingency state
network.getStateManager().setWorkingState(contingencyStateId);
AmplUtil.resetNetworkMapping(mapper);
AmplUtil.fillMapper(mapper, network); // because action can create a new bus
new AmplNetworkWriter(network, dataSource, contingencyNum, 0, true, mapper, CLUSTERS_AMPL_EXPORT_CONFIG).write();
if (config.isExportStates()) {
WCAUtils.exportState(network, workingDir, contingencyNum, 0);
}
// write contingency description
WCAUtils.writeContingencies(Collections.singleton(contingency), dataSource, mapper);
// write security rules corresponding to the contingency
new WCASecurityRulesWriter(network, securityRuleExpressions, dataSource, mapper, false, activateFiltering).write();
// write post curative state
for (int i = 0; i < curativeActionIds.size(); i++) {
String curativeActionId = curativeActionIds.get(i);
int curativeActionNum = mapper.newInt(AmplSubset.CURATIVE_ACTION, curativeActionId);
String curativeStateId = curativeStateIds.get(i);
network.getStateManager().setWorkingState(curativeStateId);
AmplUtil.resetNetworkMapping(mapper);
AmplUtil.fillMapper(mapper, network); // because action can create a new bus
new AmplNetworkWriter(network, dataSource, contingencyNum, curativeActionNum, true, mapper, CLUSTERS_AMPL_EXPORT_CONFIG).write();
if (config.isExportStates()) {
WCAUtils.exportState(network, workingDir, contingencyNum, curativeActionNum);
}
}
// write curatives action description associated to the contingency
WCAUtils.writeActions(curativeActionIds, dataSource, mapper, "Curative actions", AmplSubset.CURATIVE_ACTION);
Command cmd = new SimpleCommandBuilder()
.id(CLUSTERS_CMD_ID)
.program("clusters")
.inputFiles(inputFiles(dataSetNum))
.args(COMMONE_FILE_PREFIX,
FILE_PREFIX + dataSetNum,
REQUIRED_FILE_NAME,
"" + dataSetNum,
Integer.toString(THREADS),
Float.toString(config.getReducedVariableRatio()),
Float.toString(UNCERTAINTY_THRESHOLD),
Integer.toString(config.isDebug() ? DETAILS_LEVEL_DEBUG : DETAILS_LEVEL_NORMAL),
Integer.toString(WCARestrictingThresholdLevel.getLevel(config.getRestrictingThresholdLevels())),
WCA_FLOWS_FILE,
WCA_UNCERTAINTIES_FILE,
WCA_UNDEFINED_PST_FILE,
WCA_SENSIBILITIES_FILE,
WCA_INFLUENCE_PST_FILE)
.build();
return Arrays.asList(new CommandExecution(cmd, 1));
}
@Override
public WCAClustersResult after(Path workingDir, ExecutionReport report) throws IOException {
report.log();
WCAClustersResult clustersResult = WCAUtils.readClustersResult(CLUSTERS_CMD_ID, workingDir, WCA_FLOWS_FILE, WCA_UNCERTAINTIES_FILE);
LOGGER.info("Network {}, contingency {}: 'clusters' result = {}", network.getId(), contingency.getId(), clustersResult.toString());
return clustersResult;
}
});
}
private CompletableFuture<WCADomainsResult> createDomainsTask(Contingency contingency,
String baseStateId,
List<SecurityRuleExpression> securityRuleExpressions,
Uncertainties uncertainties,
WCAHistoLimits histoLimits,
StringToIntMapper<AmplSubset> mapper,
List<String> preventiveStateIds,
List<String> preventiveActionIds,
boolean activateFiltering) {
return computationManager.execute(new ExecutionEnvironment(env, DOMAINS_WORKING_DIR_PREFIX, config.isDebug()),
new AbstractExecutionHandler<WCADomainsResult>() {
@Override
public List<CommandExecution> before(Path workingDir) throws IOException {
network.getStateManager().setWorkingState(baseStateId);
copyRequired(workingDir);
DataSource commonDataSource = new FileDataSource(workingDir, COMMONE_FILE_PREFIX);
// write uncertainies
new UncertaintiesAmplWriter(uncertainties, commonDataSource, mapper).write();
// write historical interval
histoLimits.write(commonDataSource, mapper);
int contingencyNum = contingency == null ? 1 : mapper.newInt(AmplSubset.FAULT, contingency.getId());
int dataSetNum = contingencyNum - 1;
DataSource dataSource = new FileDataSource(workingDir, FILE_PREFIX + dataSetNum);
// write base state
AmplUtil.resetNetworkMapping(mapper);
AmplUtil.fillMapper(mapper, network);
new AmplNetworkWriter(network, dataSource, 0, 0, false, mapper, DOMAINS_AMPL_EXPORT_CONFIG).write();
if (config.isExportStates()) {
WCAUtils.exportState(network, workingDir, 0, 0);
}
// write contingency description
WCAUtils.writeContingencies(contingency == null ? Collections.emptyList() : Collections.singleton(contingency), dataSource, mapper);
// write post preventive state
for (int i = 0; i < preventiveActionIds.size(); i++) {
String preventiveActionId = preventiveActionIds.get(i);
int preventiveActionNum = mapper.newInt(AmplSubset.PREVENTIVE_ACTION, preventiveActionId);
String preventiveStateId = preventiveStateIds.get(i);
network.getStateManager().setWorkingState(preventiveStateId);
AmplUtil.resetNetworkMapping(mapper);
AmplUtil.fillMapper(mapper, network); // because action can create a new bus
new AmplNetworkWriter(network, dataSource, 0, preventiveActionNum, true, mapper, DOMAINS_AMPL_EXPORT_CONFIG).write();
if (config.isExportStates()) {
WCAUtils.exportState(network, workingDir, 0, preventiveActionNum);
}
}
// write preventive action description
WCAUtils.writeActions(preventiveActionIds, dataSource, mapper, "Preventive actions", AmplSubset.PREVENTIVE_ACTION);
// write security rules corresponding to the contingency
new WCASecurityRulesWriter(network, securityRuleExpressions, dataSource, mapper, false, activateFiltering).write();
Command cmd = new SimpleCommandBuilder()
.id(DOMAINS_CMD_ID)
.program("domains")
.inputFiles(inputFiles(dataSetNum))
.args(COMMONE_FILE_PREFIX,
FILE_PREFIX + dataSetNum,
REQUIRED_FILE_NAME,
"" + dataSetNum,
Integer.toString(THREADS),
Float.toString(config.getReducedVariableRatio()),
Float.toString(UNCERTAINTY_THRESHOLD),
Integer.toString(SecurityIndexType.TSO_OVERLOAD.ordinal()),
Integer.toString(config.isDebug() ? DETAILS_LEVEL_DEBUG : DETAILS_LEVEL_NORMAL),
Integer.toString(WCARestrictingThresholdLevel.getLevel(config.getRestrictingThresholdLevels())),
WCA_FLOWS_FILE,
WCA_UNCERTAINTIES_FILE,
WCA_UNDEFINED_PST_FILE,
WCA_SENSIBILITIES_FILE,
WCA_INFLUENCE_PST_FILE)
.build();
return Arrays.asList(new CommandExecution(cmd, 1));
}
@Override
public WCADomainsResult after(Path workingDir, ExecutionReport report) throws IOException {
report.log();
WCADomainsResult domainsResult = WCAUtils.readDomainsResult(DOMAINS_CMD_ID, workingDir, WCA_UNCERTAINTIES_FILE);
LOGGER.info("Network {}, {}: 'domains' result = {}", network.getId(), contingency == null ? "pre-contingency" : "contingency " + contingency.getId(), domainsResult.toString());
return domainsResult;
}
});
}
private CompletableFuture<WCAClustersResult> createClustersTaskWithDeps(Contingency contingency,
List<String> curativeActionIds,
String baseStateId,
String contingencyStateId,
List<String> curativeStateIds,
List<SecurityRuleExpression> securityRuleExpressions,
Supplier<CompletableFuture<Uncertainties>> memoizedUncertaintiesFuture,
Supplier<CompletableFuture<WCAHistoLimits>> histoLimitsFuture,
StringToIntMapper<AmplSubset> mapper,
boolean activateFiltering) {
return memoizedUncertaintiesFuture.get()
.thenCombine(histoLimitsFuture.get(), (uncertainties, histoLimits) -> Pair.of(uncertainties, histoLimits))
.thenCompose(p -> createClustersTask(contingency, curativeActionIds, baseStateId, contingencyStateId, curativeStateIds,
securityRuleExpressions, p.getFirst(), p.getSecond(), mapper, activateFiltering));
}
private CompletableFuture<WCADomainsResult> createDomainsTaskWithDeps(Contingency contingency,
String baseStateId,
List<SecurityRuleExpression> securityRuleExpressions,
Supplier<CompletableFuture<Uncertainties>> memoizedUncertaintiesFuture,
Supplier<CompletableFuture<WCAHistoLimits>> histoLimitsFuture,
StringToIntMapper<AmplSubset> mapper,
List<String> preventiveStateIds,
List<String> preventiveActionIds,
boolean activateFiltering) {
return memoizedUncertaintiesFuture.get()
.thenCombine(histoLimitsFuture.get(), (uncertainties, histoLimits) -> Pair.of(uncertainties, histoLimits))
.thenCompose(p -> createDomainsTask(contingency, baseStateId, securityRuleExpressions, p.getFirst(), p.getSecond(), mapper,
preventiveStateIds, preventiveActionIds, activateFiltering));
}
private CompletableFuture<WCAClusterNum> createClustersWorkflowTask(Contingency contingency, String baseStateId,
ContingencyDbFacade contingencyDbFacade,
List<SecurityRuleExpression> securityRuleExpressions,
Supplier<CompletableFuture<Uncertainties>> memoizedUncertaintiesFuture,
Supplier<CompletableFuture<WCAHistoLimits>> histoLimitsFuture,
StringToIntMapper<AmplSubset> mapper,
LoadFlow loadFlow,
boolean activateFiltering,
boolean filterCurativeActions,
WCAFilteredClusters filteredClusters) {
String[] contingencyStateId = new String[1];
List<String> curativeStateIds = Collections.synchronizedList(new ArrayList<>());
List<String> curativeActionIds = Collections.synchronizedList(new ArrayList<>());
return CompletableFuture
.runAsync(() -> {
LOGGER.info("Network {}, contingency {}: computing post contingency state", network.getId(), contingency.getId());
contingencyStateId[0] = baseStateId + "_" + contingency.getId();
network.getStateManager().cloneState(baseStateId, contingencyStateId[0]);
network.getStateManager().setWorkingState(contingencyStateId[0]);
contingency.toTask().modify(network, computationManager);
}, computationManager.getExecutor())
.thenCompose(aVoid -> loadFlow.runAsync(contingencyStateId[0], LOAD_FLOW_PARAMETERS))
.thenCompose(loadFlowResult -> {
if (!loadFlowResult.isOk()) {
LOGGER.warn("Network {}, contingency {}: load flow on post contingency state diverged, metrics = {}",
network.getId(), contingency.getId(), loadFlowResult.getMetrics());
filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO, WCAClusterNum.THREE),
WCAClusterOrigin.LF_POST_CONTINGENCY_DIVERGENCE);
wcaReport.addPostContingencyStatus(new WCAPostContingencyStatus(
contingency.getId(),
new WCALoadflowResult(false, "load flow on post contingency state diverged: metrics = " + loadFlowResult.getMetrics())
));
return CompletableFuture.completedFuture(WCAClusterNum.FOUR);
} else {
network.getStateManager().setWorkingState(contingencyStateId[0]);
WCAPostContingencyStatus postContingencyStatus = new WCAPostContingencyStatus(contingency.getId(), new WCALoadflowResult(true, null));
List<LimitViolation> contingencyStateLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
if (contingencyStateLimitViolations.size() > 0) {
LOGGER.warn("Network {}, contingency {}: constraint violantions found in post contingency state:\n{}",
network.getId(), contingency.getId(), Security.printLimitsViolations(contingencyStateLimitViolations, network, violationsFilter));
postContingencyStatus.setPostContingencyViolationsWithoutUncertainties(contingencyStateLimitViolations);
filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE),
WCAClusterOrigin.LF_POST_CONTINGENCY_VIOLATION);
}
if (WCACurativeActionsOptimizer.CLUSTERS.equals(config.getCurativeActionsOptimizer())
|| WCACurativeActionsOptimizer.LF_HEURISTIC.equals(config.getCurativeActionsOptimizer())) {
LOGGER.info("Network {}, contingency {}: getting curative actions", network.getId(), contingency.getId());
List<List<Action>> curativeActions = contingencyDbFacade.getCurativeActions(contingency, null); // pass post contingency violations?
LOGGER.info("Network {}, contingency {}: found {} curative actions", network.getId(), contingency.getId(), curativeActions.size());
if (curativeActions.isEmpty()) {
LOGGER.warn("Network {}, contingency {}: found no curative actions", network.getId(), contingency.getId());
filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE),
WCAClusterOrigin.LF_POST_SPECIFIC_CURATIVE_ACTION_VIOLATION);
postContingencyStatus.setCurativeActionsAvailable(false);
wcaReport.addPostContingencyStatus(postContingencyStatus);
if (WCACurativeActionsOptimizer.CLUSTERS.equals(config.getCurativeActionsOptimizer())) {
return createClustersTaskWithDeps(contingency, Collections.emptyList(), baseStateId, contingencyStateId[0],
Collections.emptyList(), securityRuleExpressions, memoizedUncertaintiesFuture,
histoLimitsFuture, mapper, activateFiltering)
.thenCompose(clusterResults -> {
return CompletableFuture.completedFuture(clusterResults.getClusterNum());
});
} else {
return CompletableFuture.completedFuture(WCAClusterNum.UNDEFINED);
}
} else {
List<String> curativeStateIdsForClusters = Collections.synchronizedList(new ArrayList<>());
List<String> curativeActionIdsForClusters = Collections.synchronizedList(new ArrayList<>());
List<WCAActionApplication> curativeActionsApplication = Collections.synchronizedList(new ArrayList<>());
curativeActions.sort((o1, o2) -> o1.stream().map(Action::getId).collect(Collectors.joining("+")).compareTo(o2.stream().map(Action::getId).collect(Collectors.joining("+"))));
String previousState = contingencyStateId[0];
for (int i = 0; i < curativeActions.size(); i++) {
List<Action> curativeAction = curativeActions.get(i);
String curativeActionId = curativeAction.stream().map(Action::getId).collect(Collectors.joining("+"));
curativeActionIds.add(curativeActionId);
String curativeStateId = previousState + "_" + curativeActionId;
curativeStateIds.add(curativeStateId);
LOGGER.info("Network {}, contingency {}, curative action {}: starting analysis",
network.getId(), contingency.getId(), curativeActionId);
network.getStateManager().cloneState(previousState, curativeStateId);
network.getStateManager().setWorkingState(curativeStateId);
LOGGER.info("Network {}, contingency {}, curative action {}: computing post curative action state",
network.getId(), contingency.getId(), curativeActionId);
for (Action subAction : curativeAction) {
subAction.toTask().modify(network, computationManager);
}
LoadFlowResult loadFlowResult1;
try {
loadFlowResult1 = loadFlow.run(LOAD_FLOW_PARAMETERS);
if (loadFlowResult1.isOk()) {
boolean violationsRemoved = false;
boolean actionApplied = false;
String comment = null;
List<LimitViolation> curativeStateLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
if (curativeStateLimitViolations.isEmpty()) {
LOGGER.info("Network {}, contingency {}, curative action {} solves violations: adding curative action to list for 'clusters' task",
network.getId(), contingency.getId(), curativeActionId);
curativeStateIdsForClusters.add(curativeStateId);
curativeActionIdsForClusters.add(curativeActionId);
violationsRemoved = true;
actionApplied = true;
previousState = curativeStateId;
} else {
LOGGER.warn("Network {}, contingency {}, curative action {}: violantions found in post curative action state:\n{}",
network.getId(), contingency.getId(), curativeActionId, Security.printLimitsViolations(curativeStateLimitViolations, network, violationsFilter));
comment = "violantions found in post curative action state";
if (!filterCurativeActions) {
LOGGER.info("Network {}, contingency {}, curative action {}: adding anyway curative action to list for 'clusters' task (config filterCurativeActions = false)",
network.getId(), contingency.getId(), curativeActionId);
curativeStateIdsForClusters.add(curativeStateId);
curativeActionIdsForClusters.add(curativeActionId);
actionApplied = true;
previousState = curativeStateId;
}
}
curativeActionsApplication.add(new WCAActionApplication(curativeActionId,
null,
new WCALoadflowResult(true, null),
violationsRemoved,
actionApplied,
comment));
} else {
LOGGER.warn("Network {}, contingency {}, curative action {}: load flow on post curative action state diverged, metrics = {}",
network.getId(), contingency.getId(), curativeActionId, loadFlowResult1.getMetrics());
curativeActionsApplication.add(new WCAActionApplication(curativeActionId,
null,
new WCALoadflowResult(false, "load flow on post curative action state diverged: metrics = " + loadFlowResult1.getMetrics()),
false,
false,
null));
}
} catch (Exception e) {
LOGGER.warn("Network {}, contingency {}, curative action {}: load flow on post curative action state failed: {}",
network.getId(), contingency.getId(), curativeActionId, e.getMessage(), e);
curativeActionsApplication.add(new WCAActionApplication(curativeActionId,
null,
new WCALoadflowResult(false, "load flow on post curative action state failed: " + e.getMessage()),
false,
false,
null));
}
}
postContingencyStatus.setCurativeActionsApplication(curativeActionsApplication);
if (curativeActionIdsForClusters.isEmpty()) {
LOGGER.warn("Network {}, contingency {}: no available curative actions", network.getId(), contingency.getId());
filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE),
WCAClusterOrigin.LF_POST_SPECIFIC_CURATIVE_ACTION_VIOLATION);
}
return CompletableFuture.completedFuture(new WCAClustersResult())
.thenCompose(clusterResults -> {
if (WCACurativeActionsOptimizer.CLUSTERS.equals(config.getCurativeActionsOptimizer())) {
LOGGER.info("Network {}, contingency {}: running 'clusters' curative action optimizer", network.getId(), contingency.getId());
return createClustersTaskWithDeps(contingency, curativeActionIdsForClusters, baseStateId, contingencyStateId[0],
curativeStateIdsForClusters, securityRuleExpressions, memoizedUncertaintiesFuture,
histoLimitsFuture, mapper, activateFiltering);
} else {
return CompletableFuture.completedFuture(clusterResults);
}
})
.thenCompose(clusterResults2 -> {
if (clusterResults2.foundViolations()) {
LOGGER.info("Network {}, contingency {}: 'clusters' found violations", network.getId(), contingency.getId());
String clustersUncertaintiesState = contingencyStateId[0] + "_clustersUncertaintiesState";
LOGGER.info("Network {}, contingency {}: creating post contingency state with 'clusters' uncertainties",
network.getId(), contingency.getId());
network.getStateManager().cloneState(contingencyStateId[0], clustersUncertaintiesState);
network.getStateManager().setWorkingState(clustersUncertaintiesState);
WCAUtils.applyInjections(network, clustersUncertaintiesState, clusterResults2.getInjections());
LOGGER.info("Network {}, contingency {}: running loadflow on post contingency state with 'clusters' uncertainties",
network.getId(), contingency.getId());
loadFlow.runAsync(clustersUncertaintiesState, LOAD_FLOW_PARAMETERS)
.thenAccept(loadFlowResult2 -> {
if (!loadFlowResult2.isOk()) {
LOGGER.info("Network {}, contingency {}: loadflow on state with 'clusters' uncertainties diverged: metrics = {}",
network.getId(), contingency.getId(), loadFlowResult.getMetrics());
postContingencyStatus.setPostContingencyWithUncertaintiesLoadflowResult(
new WCALoadflowResult(false,
"load flow on post contingency state with 'clusters' uncertainties diverged: metrics = " + loadFlowResult.getMetrics())
);
} else {
postContingencyStatus.setPostContingencyWithUncertaintiesLoadflowResult(new WCALoadflowResult(true, null));
List<LimitViolation> clustersLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
if (clustersLimitViolations.size() > 0) {
LOGGER.warn("Network {}, contingency {}: constraint violantions found in state with 'clusters' uncertainties:\n{}",
network.getId(), contingency.getId(), Security.printLimitsViolations(clustersLimitViolations, network, violationsFilter));
postContingencyStatus.setPostContingencyViolationsWithUncertainties(clustersLimitViolations);
} else {
LOGGER.warn("Network {}, contingency {}: no violations found in state with 'clusters' uncertainties",
network.getId(), contingency.getId());
}
}
}).join();
}
wcaReport.addPostContingencyStatus(postContingencyStatus);
return CompletableFuture.completedFuture(clusterResults2.getClusterNum());
});
}
} else {
return CompletableFuture.completedFuture(WCAClusterNum.UNDEFINED);
}
}
})
.handle((clusterNumber, throwable) -> {
if (throwable != null) {
LOGGER.error(throwable.toString(), throwable);
}
// cleanup working states
network.getStateManager().removeState(contingencyStateId[0]);
for (String curativeStateId : curativeStateIds) {
network.getStateManager().removeState(curativeStateId);
}
return clusterNumber;
});
}
private CompletableFuture<List<CompletableFuture<WCACluster>>> createWcaTask(String baseStateId, WCAParameters parameters) throws Exception {
if (!network.getStateManager().isStateMultiThreadAccessAllowed()) {
throw new IllegalArgumentException("State multi thread access has to be activated");
}
LoadFlow loadFlow = loadFlowFactory.create(network, computationManager, 0);
return loadFlow
.runAsync(baseStateId, LOAD_FLOW_PARAMETERS)
.thenApply(loadFlowInBaseStateResult -> {
network.getStateManager().setWorkingState(baseStateId);
ContingencyDbFacade contingencyDbFacade = new SimpleContingencyDbFacade(contingenciesActionsDbClient, network);
StringToIntMapper<AmplSubset> mapper = AmplUtil.createMapper(network);
Collection<Contingency> contingencies = contingencyDbFacade.getContingencies();
LOGGER.info("Network {}: working on {} contingencies", network.getId(), contingencies.size());
List<CompletableFuture<WCACluster>> clusters = new ArrayList<>(contingencies.size());
WCAFilteredClusters filteredClusters = new WCAFilteredClusters(network.getId(), contingencies.stream().map(Contingency::getId).collect(Collectors.toList()));
if (!loadFlowInBaseStateResult.isOk()) {
LOGGER.error("Network {}: load flow on base state diverged, metrics = {}", network.getId(), loadFlowInBaseStateResult.getMetrics());
wcaReport.setBaseStateLoadflowResult(new WCALoadflowResult(false, "load flow on base state diverged: metrics = " + loadFlowInBaseStateResult.getMetrics()));
contingencies.forEach(contingency -> {
filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO, WCAClusterNum.THREE),
WCAClusterOrigin.LF_DIVERGENCE);
clusters.add(CompletableFuture.completedFuture(new WCAClusterImpl(contingency,
WCAClusterNum.FOUR,
EnumSet.of(WCAClusterOrigin.LF_DIVERGENCE),
Collections.emptyList())));
});
} else {
wcaReport.setBaseStateLoadflowResult(new WCALoadflowResult(true, null));
List<LimitViolation> baseStateLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
if (baseStateLimitViolations.size() > 0) {
LOGGER.warn("Network {}: constraint violantions found in base state:\n{}",
network.getId(), Security.printLimitsViolations(baseStateLimitViolations, network, violationsFilter));
wcaReport.setPreContingencyViolationsWithoutUncertainties(baseStateLimitViolations);
contingencies.forEach(contingency -> filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO),
WCAClusterOrigin.LF_BASIC_VIOLATION));
}
Supplier<CompletableFuture<Uncertainties>> uncertainties = Suppliers.memoize(() -> {
network.getStateManager().setWorkingState(baseStateId);
try {
if (!(config.getPreventiveActionsFilter() == WCAPreventiveActionsFilter.DOMAINS)
&& !(config.getPreventiveActionsOptimizer() == WCAPreventiveActionsOptimizer.DOMAINS)
&& !(parameters.getOfflineWorkflowId() != null)
&& !(config.getCurativeActionsOptimizer() == WCACurativeActionsOptimizer.CLUSTERS)) {
return CompletableFuture.completedFuture(new Uncertainties(Collections.emptyList(), 0));
}
LOGGER.info("Network {}: computing uncertainities", network.getId());
return uncertaintiesAnalyserFactory.create(network, histoDbClient, computationManager).analyse(parameters.getHistoInterval());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Supplier<CompletableFuture<WCAHistoLimits>> histoLimits
= Suppliers.memoize(() -> CompletableFuture.supplyAsync(() -> {
network.getStateManager().setWorkingState(baseStateId);
try {
WCAHistoLimits limits = new WCAHistoLimits(parameters.getHistoInterval());
if (config.getPreventiveActionsFilter() == WCAPreventiveActionsFilter.DOMAINS
|| config.getPreventiveActionsOptimizer() == WCAPreventiveActionsOptimizer.DOMAINS
|| parameters.getOfflineWorkflowId() != null
|| config.getCurativeActionsOptimizer() == WCACurativeActionsOptimizer.CLUSTERS) {
LOGGER.info("Network {}: computing historical limits", network.getId());
limits.load(network, histoDbClient);
}
return limits;
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}, computationManager.getExecutor()));
List<LimitViolation> violationsToBePrevented = baseStateLimitViolations;
if (WCAPreventiveActionsFilter.DOMAINS.equals(config.getPreventiveActionsFilter())) {
LOGGER.info("Network {}: running 'domains' preventive actions filter", network.getId());
violationsToBePrevented = createDomainsTaskWithDeps(null, baseStateId, Collections.emptyList(), uncertainties,
histoLimits, mapper, Collections.emptyList(), Collections.emptyList(),
config.activateFiltering())
.thenCompose(domainsResult -> {
if (domainsResult.foundBasicViolations()) {
LOGGER.info("Network {}: 'domains' found basic violations", network.getId());
String domainsUncertaintiesState = "domainsUncertaintiesState";
LOGGER.info("Network {}: creating state with 'domains' uncertainties", network.getId());
network.getStateManager().cloneState(baseStateId, domainsUncertaintiesState);
network.getStateManager().setWorkingState(domainsUncertaintiesState);
WCAUtils.applyInjections(network, domainsUncertaintiesState, domainsResult.getInjections());
LOGGER.info("Network {}: running loadflow on state with 'domains' uncertainties", network.getId());
return loadFlow.runAsync(domainsUncertaintiesState, LOAD_FLOW_PARAMETERS)
.thenApply(loadFlowResult -> {
if (!loadFlowResult.isOk()) {
LOGGER.info("Network {}: loadflow on state with 'domains' uncertainties diverged, metrics = {}", network.getId(), loadFlowResult.getMetrics());
wcaReport.setBaseStateWithUncertaintiesLoadflowResult(new WCALoadflowResult(false, "load flow on state with 'domains' uncertainties diverged: metrics = " + loadFlowResult.getMetrics()));
return CompletableFuture.completedFuture(baseStateLimitViolations);
} else {
List<LimitViolation> domainsLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
if (domainsLimitViolations.size() > 0) {
LOGGER.warn("Network {}: constraint violantions found in state with 'domains' uncertainties:\n{}",
network.getId(), Security.printLimitsViolations(domainsLimitViolations, network, violationsFilter));
wcaReport.setPreContingencyViolationsWithUncertainties(domainsLimitViolations);
contingencies.forEach(contingency -> filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO),
WCAClusterOrigin.DOMAINS_BASIC_VIOLATION));
return CompletableFuture.completedFuture(domainsLimitViolations);
} else {
LOGGER.warn("Network {}: no violations found in state with 'domains' uncertainties", network.getId());
}
return CompletableFuture.completedFuture(baseStateLimitViolations);
}
}).join();
}
return CompletableFuture.completedFuture(baseStateLimitViolations);
})
.join();
network.getStateManager().setWorkingState(baseStateId);
}
LOGGER.info("Network {}: {} violations to be prevented:\n{}",
network.getId(), violationsToBePrevented.size(), Security.printLimitsViolations(violationsToBePrevented, network, violationsFilter));
List<String> preventiveStateIdsForDomains = Collections.synchronizedList(new ArrayList<>());
List<String> preventiveActionIdsForDomains = Collections.synchronizedList(new ArrayList<>());
Map<String, List<Action>> possibleActionsToApply = Collections.synchronizedMap(new HashMap<String, List<Action>>());
wcaReport.setBaseStateRemainingViolations(violationsToBePrevented); // should I use these violations (they could come from 'domains' worst uncertainties state) or the original basecase violations?
if (violationsToBePrevented.size() > 0) {
if (config.getPreventiveActionsOptimizer().equals(WCAPreventiveActionsOptimizer.NONE)) {
contingencies.forEach(contingency -> filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO, WCAClusterNum.THREE),
null));
} else {
LOGGER.info("Network {}: getting preventive actions", network.getId());
violationsToBePrevented.sort((o1, o2) -> (int) Math.ceil(((o2.getValue() - o2.getLimit()) / o2.getValue()) - ((o1.getValue() - o1.getLimit()) / o1.getValue())));
String previousState = baseStateId;
List<LimitViolation> solvedViolations = new ArrayList<>();
List<LimitViolation> originalViolations = violationsToBePrevented;
violationsLoop: for (LimitViolation violationToBePrevented : violationsToBePrevented) {
List<List<Action>> preventiveActions = contingencyDbFacade.getPreventiveActions(violationToBePrevented);
if (preventiveActions.isEmpty()) {
continue;
}
for (int i = 0; i < preventiveActions.size(); i++) {
List<Action> preventiveAction = preventiveActions.get(i);
String preventiveActionId = preventiveAction.stream().map(Action::getId).collect(Collectors.joining("+"));
if (preventiveStateIdsForDomains.contains(preventiveActionId)) {
continue;
}
String preventiveStateId = previousState + "_" + preventiveActionId;
LOGGER.info("Network {}, preventive action {}: starting analysis for {} violation on equipment {}",
network.getId(), preventiveActionId, violationToBePrevented.getLimitType(), violationToBePrevented.getSubjectId());
possibleActionsToApply.put(preventiveActionId, preventiveAction);
network.getStateManager().cloneState(previousState, preventiveStateId);
network.getStateManager().setWorkingState(preventiveStateId);
for (Action subAction : preventiveAction) {
subAction.toTask().modify(network, computationManager);
}
LoadFlowResult loadFlowResult1;
try {
loadFlowResult1 = loadFlow.run(LOAD_FLOW_PARAMETERS);
if (loadFlowResult1.isOk()) {
List<LimitViolation> preventiveStateLimitViolations = violationsFilter.apply(Security.checkLimits(network), network);
Optional<LimitViolation> notSolvedLimitViolation = preventiveStateLimitViolations
.stream()
.filter(preventiveStateLimitViolation -> preventiveStateLimitViolation.getSubjectId().equals(violationToBePrevented.getSubjectId()))
.findAny();
Optional<LimitViolation> previouslySolvedLimitViolation = preventiveStateLimitViolations
.stream()
.filter(preventiveStateLimitViolation -> WCAUtils.containsViolation(solvedViolations, preventiveStateLimitViolation))
.findAny();
Optional<LimitViolation> newLimitViolation = preventiveStateLimitViolations
.stream()
.filter(preventiveStateLimitViolation -> !WCAUtils.containsViolation(originalViolations, preventiveStateLimitViolation))
.findAny();
if (notSolvedLimitViolation.isPresent() || previouslySolvedLimitViolation.isPresent() || newLimitViolation.isPresent()) {
String message = null;
if (notSolvedLimitViolation.isPresent()) {
message = "post preventive action state still contains " + violationToBePrevented.getLimitType()
+ " violation on equiment " + violationToBePrevented.getSubjectId();
} else if (previouslySolvedLimitViolation.isPresent()) {
message = "post preventive action state contains previously solved violations";
} else if (newLimitViolation.isPresent()) {
message = "post preventive action state contains new violations";
}
LOGGER.warn("Network {}, preventive action {}: {}:\n{}",
network.getId(), preventiveActionId, message, Security.printLimitsViolations(preventiveStateLimitViolations, network, violationsFilter));
if (!config.filterPreventiveActions()) {
LOGGER.info("Network {}, preventive action {}: adding anyway preventive action to list (config filterPreventiveActions = false)",
network.getId(), preventiveActionId);
preventiveStateIdsForDomains.add(preventiveStateId);
preventiveActionIdsForDomains.add(preventiveActionId);
previousState = preventiveStateId;
solvedViolations.add(violationToBePrevented);
}
WCAActionApplication actionApplication = new WCAActionApplication(preventiveActionId,
violationToBePrevented,
new WCALoadflowResult(true, null),
false,
false,
message);
actionApplication.setPostActionViolations(preventiveStateLimitViolations);
wcaReport.addPreventiveActionApplication(actionApplication);
} else {
LOGGER.info("Network {}, preventive action {} solves {} violation on equiment {}: adding preventive action to list",
network.getId(), preventiveActionId, violationToBePrevented.getLimitType(), violationToBePrevented.getSubjectId());
preventiveStateIdsForDomains.add(preventiveStateId);
preventiveActionIdsForDomains.add(preventiveActionId);
previousState = preventiveStateId;
solvedViolations.add(violationToBePrevented);
WCAActionApplication actionApplication = new WCAActionApplication(preventiveActionId,
violationToBePrevented,
new WCALoadflowResult(true, null),
true,
false,
null);
actionApplication.setPostActionViolations(preventiveStateLimitViolations);
wcaReport.addPreventiveActionApplication(actionApplication);
if (preventiveStateLimitViolations.isEmpty()) {
LOGGER.info("Network {}, preventive action {} solved all the remaining violations: stopping preventive actions analysis",
network.getId(), preventiveActionId);
break violationsLoop;
}
break;
}
} else {
LOGGER.warn("Network {}, preventive action {}: loadflow on post preventive action state diverged, metrics = {}",
network.getId(), preventiveActionId, loadFlowResult1.getMetrics());
wcaReport.addPreventiveActionApplication(new WCAActionApplication(preventiveActionId,
violationToBePrevented,
new WCALoadflowResult(false, "loadflow on post preventive action state diverged: metrics = " + loadFlowResult1.getMetrics()),
false,
false,
null));
}
} catch (Exception e) {
LOGGER.error("Network {}, preventive action {}: loadflow on post preventive action state failed: {}",
network.getId(), preventiveActionId, e.getMessage(), e);
wcaReport.addPreventiveActionApplication(new WCAActionApplication(preventiveActionId,
violationToBePrevented,
new WCALoadflowResult(false, "loadflow on post preventive action state failed: " + e.getMessage()),
false,
false,
null));
}
}
}
LOGGER.info("Network {}: found {} preventive actions", network.getId(), preventiveActionIdsForDomains.size());
Collection<String> preventiveActionsToApply = CompletableFuture.completedFuture(new ArrayList<String>())
.thenCompose(ignored -> {
if (config.getPreventiveActionsOptimizer().equals(WCAPreventiveActionsOptimizer.DOMAINS)
&& !preventiveActionIdsForDomains.isEmpty()) {
LOGGER.info("Network {}: running 'domains' preventive actions optimizer", network.getId());
return createDomainsTaskWithDeps(null, baseStateId, Collections.emptyList(), uncertainties, histoLimits, mapper,
preventiveStateIdsForDomains, preventiveActionIdsForDomains, config.activateFiltering())
.thenCompose(domainsResult -> {
if (domainsResult.getPreventiveActionIndex() > 0) {
LOGGER.info("Network {}: 'domains' found {} preventive actions solved the violations",
network.getId(), preventiveActionIdsForDomains.subList(0, domainsResult.getPreventiveActionIndex()));
contingencies.forEach(contingency -> filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO),
WCAClusterOrigin.DOMAINS_SPECIFIC_PREVENTIVE_ACTION_FOUND));
} else {
LOGGER.info("Network {}: 'domains' found no preventive actions solving the violations", network.getId());
contingencies.forEach(contingency -> filteredClusters.removeClusters(contingency.getId(),
EnumSet.of(WCAClusterNum.ONE, WCAClusterNum.TWO, WCAClusterNum.THREE),
WCAClusterOrigin.DOMAINS_NO_PREVENTIVE_ACTION_FOUND));
}
return CompletableFuture.completedFuture(new ArrayList<String>(preventiveActionIdsForDomains.subList(0, domainsResult.getPreventiveActionIndex())));
});
}
return CompletableFuture.completedFuture(new ArrayList<String>());
})
.join();
if (preventiveActionsToApply.size() > 0 && config.applyPreventiveActions()) {
LOGGER.info("Network {}: applying preventive actions", network.getId());
network.getStateManager().setWorkingState(baseStateId);
CompletableFuture.runAsync(() -> {
preventiveActionsToApply.forEach(actionId -> {
if (possibleActionsToApply.containsKey(actionId)) {
possibleActionsToApply.get(actionId).forEach(action -> {
LOGGER.info("Network {}: applying preventive action {}, elementary action {}", network.getId(), actionId, action.getId());
action.toTask().modify(network, computationManager);
});
wcaReport.setPreventiveActionAsApplied(actionId);
} else {
LOGGER.warn("Network {}: action {} not found in preventive actions", network.getId(), actionId);
}
});
}, computationManager.getExecutor())
.thenCompose(ignored -> loadFlow.runAsync(baseStateId, LOAD_FLOW_PARAMETERS))
.thenAccept(ignored -> {
// check that the violations have disappeared? this check has already been done previously
// update basecase remaining violations
wcaReport.setBaseStateRemainingViolations(violationsFilter.apply(Security.checkLimits(network), network));
})
.exceptionally(throwable -> {
if (throwable != null) {
LOGGER.error(throwable.toString(), throwable);
}
return null;
})
.join();
}
if (contingencies.stream().allMatch(
contingency -> filteredClusters.getClusters(contingency.getId()).size() == 1
&& WCAClusterNum.FOUR.equals(filteredClusters.getCluster(contingency.getId()))
) || config.loosenConstraints()) {
wcaReport.setPostPreventiveActionsViolationsWithUncertainties(wcaReport.getBaseStateRemainingViolations());
if (!wcaReport.getBaseStateRemainingViolations().isEmpty()) {
LOGGER.warn("Network {}: loosening the basecase constraints for remaining violations:\n{}",
network.getId(), Security.printLimitsViolations(new ArrayList<>(wcaReport.getBaseStateRemainingViolations()), network, violationsFilter));
ConstraintsModifierConfig constraintsModifierConfig = new ConstraintsModifierConfig(
config.getCountryConstraintFilter(),
config.ignoreVoltageConstraints() ? EnumSet.of(LimitViolationType.CURRENT) : EnumSet.allOf(LimitViolationType.class)
);
ConstraintsModifier constraintsModifier = new ConstraintsModifier(network, constraintsModifierConfig);
constraintsModifier.looseConstraints(baseStateId,
new ArrayList<>(wcaReport.getBaseStateRemainingViolations()),
config.getMargin());
}
}