-
Notifications
You must be signed in to change notification settings - Fork 19
/
DdbDtaImpExp.java
2594 lines (2342 loc) · 121 KB
/
DdbDtaImpExp.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) 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.iidm.ddb.eurostag_imp_exp;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.powsybl.iidm.network.*;
import com.powsybl.iidm.network.util.ConnectedComponents;
import com.powsybl.iidm.network.util.Identifiables;
import eu.itesla_project.iidm.ddb.eurostag_imp_exp.utils.Utils;
import eu.itesla_project.iidm.ddb.model.*;
import eu.itesla_project.iidm.ddb.service.DDBManager;
import eu.itesla_project.iidm.ejbclient.EjbClientCtx;
import itesla.converter.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
/**
*
* @author Quinary <itesla@quinary.com>
*/
public class DdbDtaImpExp implements DynamicDatabaseClient {
private static final String PAR_MACROBLOCK_NAME = "macroblock.name";
private static final String MTC_PREFIX_NAME = "MTC_";
//DDBManager jndi name
private static final String DDBMANAGERJNDINAME = "ejb:iidm-ddb-ear/iidm-ddb-ejb/DDBManagerBean!eu.itesla_project.iidm.ddb.service.DDBManager";
private static final String DICT_GENS_CSV = "dict_gens.csv";
private static final String SKIPPED_GENS_CSV = "skipped_gens.csv";
static Logger log = LoggerFactory.getLogger(DdbDtaImpExp.class);
String[][] estg = new String[][] {
{"M1U", "Unsaturated generator defined by its internal parameters - full model"},
{"M1DU", "Unsaturated generator defined by its internal parameters - full model - type Fortescue"},
{"M2U", "Unsaturated generator defined by its external parameters - full model"},
{"M2DU", "Unsaturated generator defined by its external parameters - full model - type Fortescue"},
{"M1S", "Saturated generator defined by its internal parameters - full model"},
{"M1DS", "Saturated generator defined by its internal parameters - full model - type Fortescue"},
{"M2S", "Saturated generator defined by its external parameters - full model"},
{"M2DS", "Saturated generator defined by its external parameters - full model - type Fortescue"},
// {"M5 U", "Unsaturated generator defined by its internal parameters - simplified model"},
// {"M5DU", "Unsaturated generator defined by its internal parameters - simplified model - type Fortescue"},
// {"M6 U", "Unsaturated generator defined by its external parameters - simplified model"},
// {"M6DU", "Unsaturated generator defined by its external parameters - simplified model - type Fortescue"},
// {"M5 S", "Saturated generator defined by its internal parameters - simplified model"},
// {"M5DS", "Saturated generator defined by its internal parameters - simplified model - type Fortescue"},
// {"M6 S", "Saturated generator defined by its external parameters - simplified model"},
// {"M6DS", "Saturated generator defined by its external parameters - simplified model - type Fortescue"},
// {"M10", "Induction motor - full model"},
// {"M10D", "Induction motor - full model - type Fortescue"},
// {"M11", "Induction motor - simplified model"},
// {"M11D", "Induction motor - simplified model - type Fortescue"},
// {"M13", "Induction motor - full model with torque by macrolanguage"},
// {"M13D", "Induction motor - full model with torque by macrolanguage - type Fortescue"},
// {"M14", "Induction motor - simplified model with torque by macrolanguage"},
// {"M14D", "Induction motor - simplified model with torque by macrolanguage - type Fortescue"},
// {"M15", "Double Fed Induction machines"},
// {"M15D", "Double Fed Induction machines - type Fortescue"},
// {"M20", "PLOAD-QLOAD injector"},
// {"M20D", "PLOAD-QLOAD injector - type Fortescue"},
{"M21", "B-G injector"},
// {"M21D", "B-G injector - type Fortescue"},
// {"M22", "I-PHI injector"},
// {"M22D", "I-PHI injector - type Fortescue"},
// {"M23", "IR-II injector"},
// {"M23D", "IR-II injector - type Fortescue"},
{"M50", "Converter"},
// {"M50D", "Converter - type Fortescue"},
{"MA", "Macro-Automaton"},
//// {"R", "Macroblock"}
};
public String eurostagVersion = "5.1.1";
private final DdbConfig config;
private final DdExportConfig configExport;
private String jndiName;
private Network network;
private Map<String, Character> parallelIndexes;
private boolean updateFlag = false;
Hashtable<String, Set<String>> macroblocksPinNames = new Hashtable<>();
Hashtable<String, List<String>> EquipmentsInternalsMap = new Hashtable<>();
Hashtable<String, String> equipmentsTypeMap = new Hashtable<>();
//structure tracking regs names
Set<String> uniqueRegNamesSet = new TreeSet<>();
//structure tracking RST zones
HashMap<String, ArrayList<String>> geneRst = new HashMap<String, ArrayList<String>>();
HashMap<String, String> pilotPointRst = new HashMap<String, String>();
HashMap<String, String> pilotGeneratorsRst = new HashMap<String, String>();
//structure tracking ACMC equipments
HashMap<String, ArrayList<String>> acmcs = new HashMap<String, ArrayList<String>>();
public DdbConfig getConfig() {
return config;
}
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public void setUpdateFlag(boolean updateFlag) {
this.updateFlag = updateFlag;
}
@Override
public String getName() {
return "DDB";
}
@Override
public String getVersion() {
return null;
}
public EjbClientCtx newEjbClientEcx() throws NamingException {
return new EjbClientCtx(config.getJbossHost(), Integer.parseInt(config.getJbossPort()), config.getJbossUser(), config.getJbossPassword());
}
public DdbDtaImpExp(DdbConfig config, String jndiName) {
this.config = config;
this.jndiName = jndiName;
this.configExport = DdExportConfig.load();
}
public DdbDtaImpExp(DdbConfig config) {
this(config, DDBMANAGERJNDINAME);
}
public DdbDtaImpExp() {
this(new DdbConfig(), DDBMANAGERJNDINAME);
}
/* ********************************
* Import Functions
********************************* */
public void loadEurostagData(Path dtaFile, Path mappingFile, String eurostagVersion, Path regsFolder) {
try {
log.info("Reading mapping cimid-eurostagid file: " + mappingFile.toAbsolutePath());
Map<String, String> mapping = readWithCsvMapReader(mappingFile);
log.info("Loading data from: " + dtaFile.toAbsolutePath() + ", Eurostag version: " + eurostagVersion + ", regulators directory: " + regsFolder.toAbsolutePath());
loadEurostagData(dtaFile, mapping, eurostagVersion, regsFolder);
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
}
public void loadEurostagData(Path dtaFile, Map<String, String> dicoMap, String eurostagVersion, Path regsFolder) {
try (EjbClientCtx cx = newEjbClientEcx()) {
DDBManager ddbmanager = cx.connectEjb(DDBMANAGERJNDINAME);
SimulatorInst eurostagSim = getOrCreateEurostagSimulatorInst(ddbmanager, eurostagVersion);
//make sure eurostag models catalog is loaded
loadEurostagTemplatesCatalog(ddbmanager);
final Map<String, Path> regsMapping = buildRegsFilesMapping(regsFolder);
if (!Files.exists(dtaFile)) {
log.error(dtaFile + " does not exist");
} else {
if (!Files.isDirectory(dtaFile)) {
// process single file
try {
feedDDBWithEurostagData(dtaFile, dicoMap, eurostagSim, ddbmanager, regsMapping);
} catch (Throwable t) {
log.error(t.getMessage() + "; file " + dtaFile, t);
}
} else {
// process a directory, recursively
final Map<String, String> dicoMapF = dicoMap;
final SimulatorInst eurostagSimF = eurostagSim;
final DDBManager ddbmanagerF = ddbmanager;
Files.walkFileTree(dtaFile,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
if (attr.isRegularFile()) {
String aFileName = file.toString();
if ((aFileName.endsWith(".dd")) || (aFileName.endsWith(".dta"))) {
try {
feedDDBWithEurostagData(file, dicoMapF, eurostagSimF, ddbmanagerF, regsMapping);
} catch (Throwable t) {
log.error("errors processing file {} ; ", file, t.getMessage(), t);
}
} else {
log.warn("file " + file + " not recognized (not .dd, nor .dta): skipped!");
}
} else {
log.warn("file %s not a regular file: skipped!", file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
};
// If this method is not overridden and an error occurs, an IOException is thrown.
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
log.error(exc.getMessage(), exc);
return FileVisitResult.CONTINUE;
}
});
}
}
processConnections(ddbmanager);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
//load ddb with eurostag templates
public void loadEurostagTemplatesCatalog(DDBManager ddbmanager) {
try {
SimulatorInst eurostagSim = getOrCreateEurostagSimulatorInst(ddbmanager, eurostagVersion);
feedDDBWithEurostagModelTemplates(estg, eurostagSim, ddbmanager);
} catch (Throwable e) {
log.error(e.getMessage());
} finally {
}
}
private void feedDDBWithEurostagModelTemplates(
String[][] keyNamesAndDescriptions,
SimulatorInst eurostagSimulator, DDBManager ddbmanager) {
ModelTemplateContainer mtc = null;
ModelTemplate mt = null;
String eurostagKey = "";
String eurostagComment = "";
String ddbId = "";
for (int i = 0; i < keyNamesAndDescriptions.length; i++) {
eurostagKey = keyNamesAndDescriptions[i][0];
eurostagComment = keyNamesAndDescriptions[i][1];
ddbId = MTC_PREFIX_NAME + eurostagKey;
mtc = ddbmanager.findModelTemplateContainer(ddbId);
if (mtc == null) {
log.debug("-- creating Model Template Container" + ddbId);
mtc = new ModelTemplateContainer(ddbId, "");
mt = new ModelTemplate(eurostagSimulator, eurostagKey,
eurostagComment);
// must be decided what to put in data attribute; here we put
// again the typename, as in the original example circulated
mt.setData("data", Utils.stringAsByteArrayUTF8(eurostagKey));
mtc.getModelTemplates().add(mt);
mtc = ddbmanager.save(mtc);
} else {
log.debug("-- Modeltemplate container " + ddbId
+ " already defined, id: " + mtc.getId());
}
}
}
public void feedDDBWithEurostagData(Path inputFile,
Map<String, String> dicoMap, SimulatorInst eurostagSim,
DDBManager ddbmanager, Map<String, Path> regsMapping) throws Exception {
log.info("Processing file: " + inputFile.toAbsolutePath());
// first parse the .dta file
ArrayList<EurostagRecord> retZones = DtaParser.parseZones(inputFile);
// second, populate DDB with parsed data
for (EurostagRecord zone : retZones) {
log.info(" processing: {} ", zone);
String dbId = "";
switch (zone.getKeyName()) {
case "M1U":
case "M1DU":
case "M1S":
case "M1DS":
case "M2U":
case "M2DU":
case "M2S":
case "M2DS":
dbId = populateDDB_M1M2(zone, dicoMap, ddbmanager, eurostagSim);
break;
case "M21":
dbId = populateDDB_M21(zone, dicoMap, ddbmanager, eurostagSim);
break;
case "M50":
dbId = populateDDB_M50(zone, dicoMap, ddbmanager, eurostagSim);
break;
case "R":
dbId = populateDDB_R(zone, dicoMap, ddbmanager, eurostagSim, regsMapping);
break;
default:
dbId = populateDDB_Default(zone, dicoMap, ddbmanager, eurostagSim);
break;
}
log.trace(dbId);
}
}
public String populateDDB_M1M2(EurostagRecord zone, Map<String, String> amap,
DDBManager ddbmanager, SimulatorInst eurostagSim) {
// here we assume that the simulator with the required version already
// exists
if (eurostagSim == null) {
throw new RuntimeException("Eurostag simulator could not be null");
}
if (!(("M1".equals(zone.getTypeName())) || ("M2".equals(zone.getTypeName())))) {
throw new RuntimeException("not expected type (not M1 nor M2): " + zone);
}
log.debug("-Creating DDB component {} ", zone.getTypeName());
String mName = (String) zone.getData().get("machine.name");
String cimId = amap.get(mName);
if ((cimId == null) || ("".equals(cimId))) {
throw new RuntimeException(mName + ": cimId not found in mapping.");
}
if (!equipmentsTypeMap.contains(cimId)) {
equipmentsTypeMap.put(cimId, zone.getTypeName());
}
Equipment eq1 = ddbmanager.findEquipment(cimId);
if ((eq1 != null) && updateFlag) {
Set<String> connectedInternals = getConnectedInternals(cimId, ddbmanager);
//remove this equipment graph
log.info("- removing existing equipment {}", cimId);
removeEquipment(cimId, ddbmanager);
eq1 = null;
for (String internalId: connectedInternals) {
log.info("- removing existing connected internal {}", internalId);
removeInternal(internalId, ddbmanager);
}
}
String mtcDdbId = MTC_PREFIX_NAME + zone.getKeyName();
ModelTemplateContainer mtc1 = ddbmanager
.findModelTemplateContainer(mtcDdbId);
if (mtc1 == null) {
throw new RuntimeException(" template container " + mtcDdbId
+ " not defined! ");
}
ParametersContainer pc1 = ddbmanager.findParametersContainer(mName);
if (pc1 == null) {
log.debug("-- creating Parameters Container " + mName + " plus parameters.");
pc1 = new ParametersContainer(mName);
Parameters pars = new Parameters(eurostagSim);
for (String varName : zone.getData().keySet()) {
String varFType = DtaParser.getVarFType(zone.typeName, varName);
Object varValue = zone.getData().get(varName);
if (log.isDebugEnabled()) {
log.trace("----" + varName + " = " + varValue + ", " + varFType);
}
if (varFType.startsWith("F")) {
if (varValue != null) {
pars.addParameter(new ParameterFloat(varName,
new Float((Double) varValue)));
} else {
pars.addParameter(new ParameterFloat(varName, null));
}
} else if (varFType.startsWith("A")) {
pars.addParameter(new ParameterString(varName,
(String) varValue));
} else {
log.error(varFType + " not handled");
}
}
pc1.getParameters().add(pars);
pc1 = ddbmanager.save(pc1);
} else {
log.debug("-- Parameters Container container " + mName
+ " already defined, id: " + pc1.getId());
// ddbmanager.delete(pc1);
}
if (eq1 == null) {
log.info("-- creating Equipment " + cimId + "; eurostag name is: "
+ mName);
eq1 = new Equipment(cimId);
eq1.setModelContainer(mtc1);
eq1.setParametersContainer(pc1);
eq1 = ddbmanager.save(eq1);
} else {
log.warn("-- Equipment " + cimId + " already defined, id: "
+ eq1.getId());
}
return cimId;
}
public String populateDDB_M21(EurostagRecord zone, Map<String, String> amap,
DDBManager ddbmanager, SimulatorInst eurostagSim) {
// here we assume that the simulator with the required version already
// exists
if (eurostagSim == null) {
throw new RuntimeException("Eurostag simulator could not be null");
}
if (!"M21".equals(zone.getTypeName())) {
throw new RuntimeException("not expected type M21: " + zone);
}
log.debug("-Creating DDB component {} ", zone.getTypeName());
String mName = (String) zone.getData().get("machine.name");
String cimId = amap.get(mName);
if ((cimId == null) || ("".equals(cimId))) {
throw new RuntimeException(mName + ": cimId not found in mapping.");
}
if (!equipmentsTypeMap.contains(cimId)) {
equipmentsTypeMap.put(cimId, zone.getTypeName());
}
Equipment eq1 = ddbmanager.findEquipment(cimId);
if ((eq1 != null) && updateFlag) {
Set<String> connectedInternals = getConnectedInternals(cimId, ddbmanager);
//remove this equipment graph
log.info("- removing existing equipment {}", cimId);
removeEquipment(cimId, ddbmanager);
eq1 = null;
for (String internalId: connectedInternals) {
log.info("- removing existing connected internal {}", internalId);
removeInternal(internalId, ddbmanager);
}
}
String mtcDdbId = MTC_PREFIX_NAME + zone.getKeyName();
ModelTemplateContainer mtc1 = ddbmanager
.findModelTemplateContainer(mtcDdbId);
if (mtc1 == null) {
throw new RuntimeException(" template container " + mtcDdbId
+ " not defined! ");
}
ParametersContainer pc1 = ddbmanager.findParametersContainer(mName);
if (pc1 == null) {
log.debug("-- creating Parameters Container " + mName + " plus parameters.");
pc1 = new ParametersContainer(mName);
Parameters pars = new Parameters(eurostagSim);
for (String varName : zone.getData().keySet()) {
String varFType = DtaParser.getVarFType(zone.typeName, varName);
Object varValue = zone.getData().get(varName);
if (log.isDebugEnabled()) {
log.trace("----" + varName + " = " + varValue + ", " + varFType);
}
if (varFType.startsWith("F")) {
if (varValue != null) {
pars.addParameter(new ParameterFloat(varName,
new Float((Double) varValue)));
} else {
pars.addParameter(new ParameterFloat(varName, null));
}
} else if (varFType.startsWith("A")) {
pars.addParameter(new ParameterString(varName,
(String) varValue));
} else {
log.error(varFType + " not handled");
}
}
pc1.getParameters().add(pars);
pc1 = ddbmanager.save(pc1);
} else {
log.debug("-- Parameters Container container " + mName
+ " already defined, id: " + pc1.getId());
// ddbmanager.delete(pc1);
}
if (eq1 == null) {
log.info("-- creating Equipment " + cimId + "; eurostag name is: "
+ mName);
eq1 = new Equipment(cimId);
eq1.setModelContainer(mtc1);
eq1.setParametersContainer(pc1);
eq1 = ddbmanager.save(eq1);
} else {
log.warn("-- Equipment " + cimId + " already defined, id: "
+ eq1.getId());
}
return cimId;
}
public String populateDDB_M50(EurostagRecord zone, Map<String, String> amap,
DDBManager ddbmanager, SimulatorInst eurostagSim) {
// here we assume that the simulator with the required version already
// exists
if (eurostagSim == null) {
throw new RuntimeException("Eurostag simulator could not be null");
}
if (!"M50".equals(zone.getTypeName())) {
throw new RuntimeException("not expected type M50: " + zone);
}
log.debug("-Creating DDB component {} ", zone.getTypeName());
String mName = (String) zone.getData().get("machine.name");
String cimId = amap.get(mName);
if ((cimId == null) || ("".equals(cimId))) {
throw new RuntimeException(mName + ": cimId not found in mapping.");
}
if (!equipmentsTypeMap.contains(cimId)) {
equipmentsTypeMap.put(cimId, zone.getTypeName());
}
Equipment eq1 = ddbmanager.findEquipment(cimId);
if ((eq1 != null) && updateFlag) {
Set<String> connectedInternals = getConnectedInternals(cimId, ddbmanager);
//remove this equipment graph
log.info("- removing existing equipment {}", cimId);
removeEquipment(cimId, ddbmanager);
eq1 = null;
for (String internalId : connectedInternals) {
log.info("- removing existing connected internal {}", internalId);
removeInternal(internalId, ddbmanager);
}
}
String mtcDdbid = MTC_PREFIX_NAME + zone.getKeyName();
ModelTemplateContainer mtc1 = ddbmanager
.findModelTemplateContainer(mtcDdbid);
if (mtc1 == null) {
throw new RuntimeException(" template container " + mtcDdbid
+ " not defined! ");
}
ParametersContainer pc1 = ddbmanager.findParametersContainer(mName);
if (pc1 == null) {
log.debug("-- creating Parameters Container " + mName + " plus parameters.");
pc1 = new ParametersContainer(mName);
Parameters pars = new Parameters(eurostagSim);
for (String varName : zone.getData().keySet()) {
String varFType = DtaParser.getVarFType(zone.typeName, varName);
Object varValue = zone.getData().get(varName);
if (log.isDebugEnabled()) {
log.trace("----" + varName + " = " + varValue + ", " + varFType);
}
if (varFType.startsWith("F")) {
if (varValue != null) {
pars.addParameter(new ParameterFloat(varName,
new Float((Double) varValue)));
} else {
pars.addParameter(new ParameterFloat(varName, null));
}
} else if (varFType.startsWith("A")) {
pars.addParameter(new ParameterString(varName,
(String) varValue));
} else {
log.error(varFType + " not handled");
}
}
pc1.getParameters().add(pars);
pc1 = ddbmanager.save(pc1);
} else {
log.debug("-- Parameters Container container " + mName
+ " already defined, id: " + pc1.getId());
// ddbmanager.delete(pc1);
}
if (eq1 == null) {
log.info("-- creating Equipment " + cimId + "; eurostag name is: "
+ mName);
eq1 = new Equipment(cimId);
eq1.setModelContainer(mtc1);
eq1.setParametersContainer(pc1);
eq1 = ddbmanager.save(eq1);
} else {
log.warn("-- Equipment " + cimId + " already defined, id: "
+ eq1.getId());
}
return cimId;
}
private String populateDDB_R(EurostagRecord zone, Map<String, String> amap,
DDBManager ddbmanager, SimulatorInst eurostagSim, Map<String, Path> regsMapping) {
log.debug("-Creating DDB component (R) " + zone);
String machineName = (String) zone.getData().get("machine.name");
//macroblock's coupling parameters - map machine IDs to iidm IDs
zone.getData().keySet().stream()
.filter(parName -> parName.startsWith("coupling.par") && (zone.getData().get(parName) != null) && (!"".equals(zone.getData().get(parName))))
.forEach(parName -> {
String parValue = zone.getData().get(parName).toString();
String couplingtype = parValue.substring(0, 2);
//log.info("machine: {} - coupling macroblock parameter: {} = {}", machineName, parName, parValue);
switch (couplingtype) {
case "M ":
case "N#":
String couplingMachineName = parValue.substring(3).trim();
String iidmCouplingMachineName = amap.get(couplingMachineName);
if (iidmCouplingMachineName != null) {
String newparValue = couplingtype + " " + iidmCouplingMachineName;
zone.getData().put(parName, newparValue);
log.info("macroblock {} - coupling parameter {} = '{}' - mapped to '{}'", machineName, parName, parValue, newparValue);
} else {
String errMsg = "macroblock " + machineName + " - coupling parameter " + parName + " = " + parValue + " not mapped";
log.error(errMsg);
throw new RuntimeException(errMsg);
}
break;
case "N ":
log.warn("macroblock {} - coupling parameter: {} = {} - coupling type {} not stored in DDB", machineName, parName, parValue, couplingtype);
break;
default:
log.warn("macroblock {} - coupling parameter: {} = {} coupling type {} not supported !", machineName, parName, parValue, couplingtype);
}
});
String macroblockName = (String) zone.getData().get(
PAR_MACROBLOCK_NAME);
int paramSetNum = (int) zone.getData().get("psetnum");
String nativeId = amap.get(machineName);
if ((nativeId == null) || ("".equals(nativeId))) {
throw new RuntimeException(
"native id cannot be null; machine name is " + machineName);
}
addToEquipmentsInternalMap(nativeId, macroblockName);
addPinNames(nativeId, macroblockName, retrieveActualRegPath(macroblockName + "." + "frm", regsMapping));
//MTC and MT handling
String mtcDdbId = MTC_PREFIX_NAME + macroblockName;
ModelTemplateContainer mtc1 = ddbmanager.findModelTemplateContainer(mtcDdbId);
if (mtc1 != null) {
log.info("-- Using existing Model Template Container: " + mtc1.getDdbId());
} else {
log.info("-- Creating Model Template Container: " + mtcDdbId);
mtc1 = new ModelTemplateContainer(mtcDdbId, "");
}
//find a mt for this mtc and simulator
ModelTemplate mt1 = null;
for (ModelTemplate mt : mtc1.getModelTemplates()) {
if ((mt.getSimulator().equals(eurostagSim)) && ("R".equals(mt.getTypeName())) && (mt.getComment().equals(macroblockName))) {
mt1 = mt;
break;
}
}
//if it does exist, and the update flag is set, delete it
if (mt1 != null) {
if (updateFlag) {
log.info("--- removing existing Model Template: {}, {}, {}", mt1.getSimulator(), mt1.getTypeName(), mt1.getComment());
mtc1.getModelTemplates().remove(mt1);
mtc1 = ddbmanager.save(mtc1);
mtc1 = ddbmanager.findModelTemplateContainer(mtcDdbId);
mt1 = null;
removePinNames(nativeId, macroblockName);
} else {
log.info("--- using existing Model Template: {}, {}, {}", mt1.getSimulator(), mt1.getTypeName(), mt1.getComment());
}
}
if (mt1 == null) {
mt1 = new ModelTemplate(eurostagSim, "R", macroblockName);
log.info("--- creating model template: {}, {}, {}", mt1.getSimulator(), mt1.getTypeName(), mt1.getComment());
// populate DDB with regs files
// assumption: regulators files' names are always in lower case
// if a regulator file does not exist, it does not throw any exception but logs a warning
// ... some regulators, e.g. pcp or rcp, could not be available at this time
// to be resolved externally before a computation ....
for (String extension : Arrays.asList("fri", "frm", "par", "pcp", "rcp")) {
Path friPath = retrieveActualRegPath(macroblockName + "." + extension, regsMapping);
if ((friPath == null) || (Files.notExists(friPath))) {
log.error("--- Regulator file " + macroblockName + "." + extension
+ " does not exist");
} else {
log.debug("--- Loading regulator file " + macroblockName + "." + extension + " in the database.");
try {
mt1.setData(extension, Files.readAllBytes(friPath));
} catch (IOException e) {
log.error("Could not read regulator file " + friPath + ", " + e.getMessage(), e);
}
}
}
mtc1.getModelTemplates().add(mt1);
mtc1 = ddbmanager.save(mtc1);
addPinNames(nativeId, macroblockName, retrieveActualRegPath(macroblockName + "." + "frm", regsMapping));
}
String pcontainerID = "PC_" + nativeId + "_" + macroblockName;
ParametersContainer pc1 = ddbmanager
.findParametersContainer(pcontainerID);
if (pc1 == null) {
log.debug("-- Creating Parameters Container " + pcontainerID);
log.debug("--- Parameter set number: " + paramSetNum);
pc1 = new ParametersContainer(pcontainerID);
Parameters pars = new Parameters(eurostagSim);
pars.setDefParamSetNum(paramSetNum);
for (String varName : zone.getData().keySet()) {
String varFType = DtaParser.getVarFType(zone.typeName, varName);
if (varFType == null) {
//this is not a variable belonging to R; it's a modificated parameter
//by default insert it into the db as an int (ref. eurostag doc. 09_Dynamyc_Data_File.pdf, Macroblocks section)
log.debug("---- varName " + varName + " is not in the list associated component " + zone.typeName + "; handle it as an additional modification parameter, with a float type");
varFType = "F8";
}
Object varValue = zone.getData().get(varName);
if (log.isDebugEnabled()) {
log.trace("----" + varName + " = " + varValue + ", " + varFType);
}
if (varFType.startsWith("F")) {
if (varValue != null) {
pars.addParameter(new ParameterFloat(varName,
new Float((Double) varValue)));
} else {
pars.addParameter(new ParameterFloat(varName, null));
}
} else if (varFType.startsWith("A")) {
pars.addParameter(new ParameterString(varName,
(String) varValue));
} else if (varFType.startsWith("I")) {
pars.addParameter(new ParameterInteger(varName,
(Integer) varValue));
} else {
log.error(varFType + " not handled");
}
}
pc1.getParameters().add(pars);
pc1 = ddbmanager.save(pc1);
} else {
log.debug("-- ParametersContainer container " + pcontainerID
+ " already defined, id: " + pc1.getId());
}
String internalID = nativeId + "_" + macroblockName;
Internal int1 = ddbmanager.findInternal(internalID);
if (int1 == null) {
log.info("-- Creating Internal " + internalID);
int1 = new Internal(internalID);
int1.setModelContainer(mtc1);
int1.setParametersContainer(pc1);
int1 = ddbmanager.save(int1);
} else {
log.warn("-- Internal " + internalID + " already defined, id: "
+ int1.getId());
// ddbmanager.delete(int1);
}
return int1.getNativeId();
}
private String populateDDB_Default(EurostagRecord zone, Map<String, String> amap,
DDBManager ddbmanager, SimulatorInst eurostagSim) {
log.warn("- Not supported, skipping: {}", zone);
return null;
}
private void processConnections(DDBManager ddbmanager) {
log.debug("processing connections");
//nativeId being the equipment's cimId
for (String nativeId : EquipmentsInternalsMap.keySet()) {
//create a connection schema, if needed
log.info("processing connections for Equipment: " + nativeId);
ConnectionSchema cs = ddbmanager.findConnectionSchema(nativeId, null);
if (cs == null) {
log.info("- creating conn. schema with cimId " + nativeId);
cs = new ConnectionSchema(nativeId, null);
cs = ddbmanager.save(cs);
} else {
log.warn("- conn. schema with cimId " + nativeId + ", already exists! currently defined connections: " + cs.getConnections());
}
//machineInterfaceVariables is the set of this machine type variables names
Set<String> machineInterfaceVariables = DtaParser.getInterfaceVariablesNamesByComponentTypeName(equipmentsTypeMap.get(nativeId));
log.debug("-- equipment " + nativeId + ", variable names: " + machineInterfaceVariables);
//create a connection machine-macroblock, for each macroblock
log.debug("-- equipment " + nativeId + ", connected regulators: " + EquipmentsInternalsMap.get(nativeId));
log.debug("--- processing machine-regulators connections, for equipment " + nativeId);
//for each regulator/macroblock; mName is the eurostag name of the regulator
for (String mName : EquipmentsInternalsMap.get(nativeId)) {
String internalID = nativeId + "_" + mName; // internaID name of the regulator
List<Connection> definedConnections = cs.getConnections();
//create a direct machine-macroblock connection iff machine and macroblock share -at least- one variable
Set<String> machineRegulatorIntSet = Sets.intersection(machineInterfaceVariables, Sets.newHashSet(macroblocksPinNames.get(mName)));
log.debug("---- regulator: " + mName + " (internalId: " + internalID + "); reg. variable names: " + macroblocksPinNames.get(mName) + ", equip. regul. common vars: " + machineRegulatorIntSet);
if (!machineRegulatorIntSet.isEmpty()) {
for (String pinName : machineRegulatorIntSet) {
Connection newC = new Connection(nativeId, Connection.EQUIPMENT_TYPE, internalID, Connection.INTERNAL_TYPE, pinName,
pinName, Connection.INSIDE_CONNECTION);
if (!definedConnections.contains(newC)) {
log.debug("----- creating connection " + newC);
cs.getConnections().add(newC);
} else {
log.debug("----- connection already exist: " + newC);
}
}
} else {
log.debug("----- no common variable names, so no connections are created.");
}
}
//create connections macroblock-macroblock
log.debug("--- processing regulator-regulator connections, for equipment " + nativeId);
for (int i = 0; i < EquipmentsInternalsMap.get(nativeId).size(); i++) {
for (int j = i + 1; j < EquipmentsInternalsMap.get(nativeId).size(); j++) {
String id1 = EquipmentsInternalsMap.get(nativeId).get(i);
String id2 = EquipmentsInternalsMap.get(nativeId).get(j);
Set<String> intSet = Sets.intersection(Sets.newHashSet(macroblocksPinNames.get(id1)), Sets.newHashSet(macroblocksPinNames.get(id2)));
log.debug("--- reg: " + id1 + ", reg: " + id2 + ", common variable names:" + intSet);
boolean toBeProcessed = intSet.size() > 0;
if (toBeProcessed) {
for (String pinName : intSet) {
String longId1 = nativeId + "_" + id1;
String longId2 = nativeId + "_" + id2;
Connection newC = new Connection(longId1, Connection.INTERNAL_TYPE, longId2, Connection.INTERNAL_TYPE, pinName, pinName, Connection.INSIDE_CONNECTION);
List<Connection> definedConnections = cs.getConnections();
if (!definedConnections.contains(newC)) {
log.debug("---- creating connection: " + newC);
cs.getConnections().add(newC);
} else {
log.debug("---- connection already exists: " + newC);
}
}
} else {
log.debug("---- no common variable names, so no connections are created.");
}
}
}
log.info("- connection schema for cimId " + nativeId + ": " + cs.getConnections());
cs = ddbmanager.save(cs);
}
}
/*
// regs file names are inferred implicitly from .dta data
// the problem is that names are always uppercase whilst actual filenames are not
// Apparently eurostag is case unsensitive, so regs file names are to be matched case-insensitively
// Here we assume that no (f1,f2) , where f1 != f2 and f1.equalsIgnoreCase(f2) actually exist
*
*/
public Map<String, Path> buildRegsFilesMapping(Path regsFolderPath) {
Map<String, Path> regsMap = new HashMap<>();
regsMap = new HashMap<>();
try (DirectoryStream<Path> flow = Files.newDirectoryStream(
regsFolderPath, "*")) {
for (Path item : flow) {
//System.out.println("Reg file: " + item.toString());
String fileName = item.getFileName().toString();
regsMap.put(fileName.toLowerCase(), regsFolderPath.resolve(fileName));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return regsMap;
}
public Path retrieveActualRegPath(String tentativeFileName, Map<String, Path> regsMap) {
if (!regsMap.containsKey(tentativeFileName.toLowerCase())) {
return null;
} else {
return regsMap.get(tentativeFileName.toLowerCase());
}
}
private void addToEquipmentsInternalMap(String nativeId, String macroblockName) {
List<String> macroblocks = null;
if (!EquipmentsInternalsMap.containsKey(nativeId)) {
macroblocks = new ArrayList<String>();
} else {
macroblocks = EquipmentsInternalsMap.get(nativeId);
}
if (!macroblocks.contains(macroblockName)) {
macroblocks.add(macroblockName);
}
EquipmentsInternalsMap.put(nativeId, macroblocks);
}
private void addPinNames(String nativeId, String macroblockName, Path friPath) {
log.debug("addPinNames: NativeId " + nativeId + ", Macroblock " + macroblockName + ", file " + friPath);
if (!macroblocksPinNames.containsKey(macroblockName)) {
List<String> pinNames = Collections.emptyList();
if ((friPath == null) || Files.notExists(friPath)) {
log.error("could not parse pin names for macroblock {}: regulator files not found", macroblockName);
} else {
log.debug(" ---------- Reading pin names from file {}", macroblockName, friPath);
Converter converter = new Converter(friPath.toAbsolutePath().toString(), "/tmp", false);
pinNames = converter.getConnections();
for (String pinName : pinNames) {
log.debug(" -------------- {}", pinName);
}
}
macroblocksPinNames.put(macroblockName, new HashSet<String>(pinNames));
}
}
private void removePinNames(String nativeId, String macroblockName) {
log.debug("removePinNames: NativeId " + nativeId + ", Macroblock " + macroblockName);
if (!macroblocksPinNames.containsKey(macroblockName)) {
log.debug(" ---------- macroblock does not exist in the macroblock map", macroblockName);
} else {
macroblocksPinNames.remove(macroblockName);
}
}
public Map<String, String> readWithCsvMapReader(Path dicoFile) throws Exception {
return DtaParser.readWithCsvMapReader(dicoFile);
}
/* ********************************
* Export Functions
********************************* */
/**
* in the workingDir, write eurostag dynamic data (fileName) for a given list of cimIDs, and regulator files (.fri, .frm, .par, .pcp, rcp)
* *
* @param workingDir
* @param fileName
* @param network
* @param parallelIndexes
* @param eurostagVersion
* @param iidm2eurostagId
*/
@Override
public void dumpDtaFile(Path workingDir, String fileName,
Network network, Map<String, Character> parallelIndexes, String eurostagVersion,
Map<String, String> iidm2eurostagId) {
try (EjbClientCtx cx = newEjbClientEcx()) {
DDBManager ddbmanager = cx.connectEjb(DDBMANAGERJNDINAME);
dumpDtaFile(workingDir, fileName, network, parallelIndexes, eurostagVersion, iidm2eurostagId, ddbmanager);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
private boolean filteredGenerator(Generator g) {
if (configExport.getGensPQfilter()) {
if (!Float.isNaN(g.getTerminal().getP()) && ((-g.getTerminal().getP() > g.getMaxP()) || (-g.getTerminal().getP() < g.getMinP()))) {
return true;
}
}
return false;
}
public Bus getBus(Terminal t, boolean noswitch) {
if (noswitch) {
return t.getBusView().getBus();
} else {
return t.getBusBreakerView().getBus();
}
}
public boolean isInMainCc(Injection injection, boolean noswitch) {
return ConnectedComponents.getCcNum(getBus(injection.getTerminal(), noswitch)) == Component.MAIN_NUM;
}
/**
* in the workingDir, write eurostag dynamic data (fileName) for a given list of cimIDs, and regulator files (.fri, .frm, .par, .pcp, rcp)
* *
* @param workingDir
* @param fileName