-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathSolverOpersTask.java
1429 lines (1281 loc) · 56.2 KB
/
SolverOpersTask.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
package com.variamos.dynsup.translation;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import com.variamos.common.core.exceptions.FunctionalException;
import com.variamos.common.core.utilities.StringUtils;
import com.variamos.dynsup.instance.InstElement;
import com.variamos.dynsup.model.InstanceModel;
import com.variamos.dynsup.model.ModelExpr;
import com.variamos.dynsup.model.OpersIOAttribute;
import com.variamos.dynsup.model.OpersSubOperation;
import com.variamos.dynsup.types.OpersComputationType;
import com.variamos.dynsup.types.OpersOpType;
import com.variamos.dynsup.types.OpersSubOpExecType;
import com.variamos.dynsup.types.OpersSubOpType;
import com.variamos.hlcl.core.HlclProgram;
import com.variamos.hlcl.core.HlclUtil;
import com.variamos.hlcl.model.expressions.HlclFactory;
import com.variamos.hlcl.model.expressions.Identifier;
import com.variamos.hlcl.model.expressions.IntBooleanExpression;
import com.variamos.io.core.importExport.ExportConfiguration;
import com.variamos.reasoning.defectAnalyzer.core.CauCosAnayzer;
import com.variamos.reasoning.defectAnalyzer.core.DefectsVerifier;
import com.variamos.reasoning.defectAnalyzer.core.IntCauCosAnalyzer;
import com.variamos.reasoning.defectAnalyzer.core.IntDefectsVerifier;
import com.variamos.reasoning.defectAnalyzer.model.defects.Defect;
import com.variamos.reasoning.defectAnalyzer.model.defects.DefectTypeEnum;
import com.variamos.reasoning.defectAnalyzer.model.diagnosis.CauCos;
import com.variamos.reasoning.defectAnalyzer.model.diagnosis.DefectAnalyzerModeEnum;
import com.variamos.reasoning.defectAnalyzer.model.diagnosis.Diagnosis;
import com.variamos.reasoning.fragop.Fragmental;
import com.variamos.reasoning.medic.model.diagnoseAlgorithm.MinimalSetsDFSIterationsHLCL;
import com.variamos.reasoning.medic.model.graph.NodeConstraintHLCL;
import com.variamos.reasoning.medic.model.graph.NodeVariableHLCL;
import com.variamos.reasoning.medic.model.graph.VertexHLCL;
import com.variamos.reasoning.util.LogParameters;
import com.variamos.solver.core.SWIPrologSolver;
import com.variamos.solver.model.SolverSolution;
import com.variamos.componentparser.main.MainParser;
/**
* A class to support SwingWorkers for solver execution tasks using the semantic
* operations. Originally copied from
* com.variamos.perspsupport.perspmodel.SolverTasks. Part of PhD work at
* University of Paris 1
*
* @author Juan C. Munoz Fernandez <[email protected]>
*
* @version 1.1
* @since 2015-12-22
* @see com.variamos.dynsup.translation.SolverTasks
*/
public class SolverOpersTask extends SwingWorker<Void, Void> {
private ModelExpr2HLCL refas2hlcl;
private HlclProgram configHlclProgram;
private boolean invalidConfigHlclProgram;
private List<String> outVariables = new ArrayList<String>();
private List<String> defectsFreeIdsName = null;
private boolean ignoreSorting = false;
private boolean test;
private long task = 0;
private InstElement element;
private List<String> operationsNames;
private boolean firstSimulExec;
private boolean reloadDashBoardConcepts = true;
private boolean showDashboard = false;
private String completedMessage;
private String executionTime = "";
// private List<String> defects;
private SolverSolution lastConfiguration;
private String errorTitle = "";
private String errorMessage = "";
private boolean update;
private Component parentComponent;
private InstanceModel refasModel;
private String file;
private ProgressMonitor progressMonitor;
private boolean next = true;
private boolean terminated = false;
private boolean correctExecution = true;
private int results[] = null;
public boolean isCorrectExecution() {
return correctExecution;
}
/**
* Method that builds what will be executed in the the worker
*
* @param progressMonitor
* @param refasModel
* @param refas2hlcl
* @param configHlclProgram
* @param firstSimulExec
* @param operations
* @param lastConfiguration
* @param filename
*/
public SolverOpersTask(ProgressMonitor progressMonitor, InstanceModel refasModel, ModelExpr2HLCL refas2hlcl,
HlclProgram configHlclProgram, boolean firstSimulExec, List<String> operations,
SolverSolution lastConfiguration, String filename) {
this.refasModel = refasModel;
this.progressMonitor = progressMonitor;
this.refas2hlcl = refas2hlcl;
this.configHlclProgram = configHlclProgram;
this.firstSimulExec = firstSimulExec;
this.reloadDashBoardConcepts = false;
this.showDashboard = false;
this.update = false;
this.operationsNames = operations;
this.lastConfiguration = lastConfiguration;
this.file = filename;
}
public SolverOpersTask(ProgressMonitor progressMonitor, String operationIdentifier, InstanceModel refasModel,
ModelExpr2HLCL refas2hlcl, String file) {
this.progressMonitor = progressMonitor;
this.refasModel = refasModel;
this.refas2hlcl = refas2hlcl;
// this.file = file;
}
public boolean isFirstSimulExec() {
return firstSimulExec;
}
public boolean isReloadDashBoardConcepts() {
return reloadDashBoardConcepts;
}
public void setReloadDashBoardConcepts(boolean reloadDashBoard) {
this.reloadDashBoardConcepts = reloadDashBoard;
}
public boolean isShowDashboard() {
return showDashboard;
}
public void setShowDashboard(boolean showDashBoard) {
this.showDashboard = showDashBoard;
}
public boolean isUpdate() {
return update;
}
public SolverSolution getLastConfiguration() {
return lastConfiguration;
}
@Override
public Void doInBackground() throws FunctionalException {
setProgress(0);
try {
Thread.sleep(1);
// Method that executes the operations
executeOperations();
} catch (java.lang.UnsatisfiedLinkError e) {
errorMessage = "Solver not correctly configured";
errorTitle = "System Configuration Error";
correctExecution = false;
// FIXME: Review how to handle here a functional exception
} catch (InterruptedException ignore) {
} catch (Exception e) {
errorMessage = "Solver Execution Problem, try again saving and loading the model.";
errorTitle = "Verification Error";
correctExecution = false;
// FIXME issue#230
e.printStackTrace();
throw new FunctionalException(e.getMessage() + " " + FunctionalException.exceptionStacktraceToString(e));
}
task = 100;
setProgress((int) task);
return null;
}
// for dynamic operations
public boolean saveConfiguration(String file, InstElement operation, InstElement suboper)
throws InterruptedException, FunctionalException {
setProgress(1);
progressMonitor.setNote("Solutions processed: 0");
Map<String, Map<String, Integer>> elements = refas2hlcl.execExport(progressMonitor, operation, suboper);
setProgress(95);
progressMonitor.setNote("Total Solutions processed: " + elements.size());
List<String> names = new ArrayList<String>();
if (elements.size() != 0)
for (String element : elements.get("1").keySet()) {
if (refasModel.getElement(element) != null)
names.add((String) refasModel.getElement(element).getInstAttribute("name").getValue());
}
ExportConfiguration export = new ExportConfiguration();
export.exportConfiguration(elements, names, file);
return true;
}
// for dynamic operations
public int countConfigurations(InstElement operation, InstElement suboper)
throws InterruptedException, FunctionalException {
setProgress(1);
progressMonitor.setNote("Solutions processed: 0");
int elements = refas2hlcl.execCount(progressMonitor, operation, suboper);
setProgress(95);
progressMonitor.setNote("Total Solutions processed: " + elements);
completedMessage = "Total solutions: " + elements;
return elements;
}
// TODO Modify for dynamic operations
@Deprecated
public void configModel() throws InterruptedException, FunctionalException {
// this.clearNotificationBar();
refas2hlcl.cleanGUIElements(ModelExpr2HLCL.CONF_EXEC);
Set<Identifier> freeIdentifiers = null;
Set<InstElement> elementSubSet = null;
task = 0;
long iniTime = 0;
long endTime = 0;
iniTime = System.currentTimeMillis();
if (invalidConfigHlclProgram && element == null) {
configHlclProgram = refas2hlcl.getHlclProgram("Simul", ModelExpr2HLCL.CONF_EXEC);
freeIdentifiers = refas2hlcl.getFreeIdentifiers();
} else {
freeIdentifiers = new HashSet<Identifier>();
elementSubSet = new HashSet<InstElement>();
refas2hlcl.configGraph(progressMonitor, element, elementSubSet, freeIdentifiers, false);
elementSubSet = new HashSet<InstElement>();
configHlclProgram = refas2hlcl.configGraph(progressMonitor, element, elementSubSet, freeIdentifiers, true);
task = 10;
setProgress((int) task);
}
invalidConfigHlclProgram = false;
TreeMap<String, Number> configuredIdentNames = refas2hlcl.getConfiguredIdentifier(elementSubSet);
SolverSolution config = new SolverSolution();
config.setSolverSolution(configuredIdentNames);
List<String> requiredConceptsNames = new ArrayList<String>();
List<String> deadConceptsNames = new ArrayList<String>();
IntDefectsVerifier defectVerifier = new DefectsVerifier(configHlclProgram, parentComponent,
"Configuring Selected Elements");
// System.out.println("FREE: " + freeIdentifiers);
// System.out.println("CONF: " + configuredIdentNames);
if (freeIdentifiers.size() > 0) {
List<Defect> requiredConcepts = null;
requiredConcepts = defectVerifier.getFalseOptionalElements(freeIdentifiers, null, config);
executionTime += "FalseOpt: " + defectVerifier.getTotalTime() + "["
+ defectVerifier.getSolverTime() / 1000000 + "]" + " -- ";
if (requiredConcepts.size() > 0) {
for (Defect conceptVariable : requiredConcepts) {
String[] conceptId = conceptVariable.getId().split("_");
requiredConceptsNames.add(conceptId[0]);
}
}
}
long falseOTime = defectVerifier.getSolverTime() / 1000000;
task = 80;
setProgress((int) task);
// System.out.println("newSEL: " + requiredConceptsNames);
refas2hlcl.updateRequiredConcepts(requiredConceptsNames, test);
if (freeIdentifiers.size() > 0) {
List<Defect> deadIndetifiersList = null;
defectVerifier.resetTime();
deadIndetifiersList = defectVerifier.getDeadElements(freeIdentifiers, null, config);
executionTime += "Dead: " + defectVerifier.getTotalTime() + "[" + defectVerifier.getSolverTime() / 1000000
+ "]" + " -- ";
if (deadIndetifiersList.size() > 0) {
for (Defect conceptVariable : deadIndetifiersList) {
String[] conceptId = conceptVariable.getId().split("_");
deadConceptsNames.add(conceptId[0]);
}
}
}
task = 100;
setProgress((int) task);
System.out.println("newNOTAV: " + deadConceptsNames);
refas2hlcl.updateDeadConfigConcepts(deadConceptsNames, test);
endTime = System.currentTimeMillis();
executionTime += "ConfigExec: " + (endTime - iniTime) + "["
+ (falseOTime + defectVerifier.getSolverTime() / 1000000) + "]" + " -- ";
}
// dynamic call implementation
public void executeOperations() throws FunctionalException {
update = false;
long iniTime = System.currentTimeMillis();
int result = 0;
setProgress(10);
lastConfiguration = null;
while (!terminated) { // use the same task for simulation iterations
if (!next) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// FIXME issue#230
throw new FunctionalException(FunctionalException.exceptionStacktraceToString(e));
}
continue;
}
next = false;
resetFreeIdentifiers();
// for each operation in the list of operation names, the list of operation
// names is a parameter
for (String operationName : operationsNames) {
// operationObj is the hlcl program regarding the operation name
// the call returns the object with the id
if (operationName.startsWith("I:"))
{
operationName = operationName.substring(2);
}
InstElement operationObj = refas2hlcl.getRefas()
.getSyntaxModel().getOperationalModel().getElement(operationName);
Set<InstElement> suboperationsObjs = new TreeSet<InstElement>();
Map<String, InstElement> instsuboperations = new HashMap<String, InstElement>();
// Auto sorting with treeset
String operType = (String) operationObj // operType is the type of the operation
.getInstAttributeValue("operType");
String computationalType = (String) operationObj // computationalType
.getInstAttributeValue("compType");
boolean computationalAnalysis = false;
if (operType.equals(StringUtils.formatEnumValue(OpersOpType.Computational_Analysis.toString()))) {
computationalAnalysis = true;
results = new int[2];
}
int subOperIndex = 0;
// to obtain the sub operations from operations (they may be more than one)
for (InstElement operpair : operationObj.getTargetRelations()) {
InstElement suboper = operpair.getTargetRelations().get(0);
instsuboperations.put(suboper.getIdentifier(), suboper);
suboperationsObjs.add(suboper);
}
result = 0;
InstElement lastSubOper = null;
// for each suboperation in an operation
for (InstElement suboper : suboperationsObjs) {
lastSubOper = suboper;
// stop when the result is -1 or the operation is of type Validation
if (result == -1 && operationObj.getInstAttributeValue("operType").equals("Validation"))
break;
try {
// Validation operations
// System.out.println(((String) suboper
// .getInstAttributeValue("type")));
// the type of the sub-operation
String type = (String) suboper.getInstAttributeValue("type");
// if the dashboard is visible or not
boolean showDashboard = (boolean) suboper.getInstAttributeValue("showDashboard");
// obtain the message of the operation when there is a string defined by the
// user
if (suboper.getInstAttributeValue("completedMessage") != null
&& !((String) suboper.getInstAttributeValue("completedMessage")).equals(""))
completedMessage = (String) suboper.getInstAttributeValue("completedMessage");
boolean simul = false;
if (showDashboard) {
this.showDashboard = showDashboard;
}
// determine the type of the operation and call the method implementing the
// operation
// if type Number_Solutions
if (type.equals(StringUtils.formatEnumValue(OpersSubOpType.Number_Solutions.toString()))) {
if (computationalAnalysis) {
results[subOperIndex++] = countConfigurations(operationObj, suboper);
result = 0;
} else
countConfigurations(operationObj, suboper); // Method that calls the solver and obtains
// the amount of solutions
}
// type is Export_Solutions
else if (type.equals(StringUtils.formatEnumValue(OpersSubOpType.Export_Solutions.toString()))) {
saveConfiguration(file, operationObj, suboper);
}
// type is First_Solution or Iterate
else if (type.equals(StringUtils.formatEnumValue(OpersSubOpType.First_Solution.toString()))
|| type.equals(
StringUtils.formatEnumValue(OpersSubOpType.Iterate_Solutions.toString()))) {
simul = true;
if (lastConfiguration == null || firstSimulExec) {
result = refas2hlcl.execute(progressMonitor,
ModelExpr2HLCL.ONE_SOLUTION,
operationObj, instsuboperations
.get(suboper.getIdentifier()),
this.ignoreSorting); // type
} else {
if (type.equals(
StringUtils.formatEnumValue(OpersSubOpType.Iterate_Solutions.toString()))) {
this.reloadDashBoardConcepts = false;
result = refas2hlcl.execute(
progressMonitor,
ModelExpr2HLCL.NEXT_SOLUTION,
operationObj, instsuboperations
.get(suboper
.getIdentifier()),
false); // type
} else
continue;
}
}
// Verification operations with CauCos
else if (type
.equals(StringUtils.formatEnumValue(OpersSubOpType.Multi_Verification.toString()))) {
String errorHint = (String) suboper.getInstAttributeValue("errorHint");
String modeStr = suboper.getInstAttributeValue("mode").toString();
boolean updateOutAttributes = (boolean) suboper
.getInstAttributeValue("updateOutAttributes");
String outAttribute = (String) suboper.getInstAttributeValue("outAttribute");
boolean natLanguage = (boolean) suboper.getInstAttributeValue("useNatLangExprDesc");
DefectAnalyzerModeEnum mode = null;
for (DefectAnalyzerModeEnum m : DefectAnalyzerModeEnum.values()) {
if (StringUtils.formatEnumValue(m.toString()).equals(modeStr)) {
mode = m;
break;
}
}
boolean indivRelExp = (boolean) suboper.getInstAttributeValue("indivRelExp");
boolean indivVerExp = (boolean) suboper.getInstAttributeValue("indivVerExp");
List<OpersIOAttribute> outAttributes = ((OpersSubOperation) suboper.getEdOperEle())
.getOutAttributes();
result = cauCos(0, operationObj, suboper, errorHint, outAttributes, updateOutAttributes,
outAttribute, operationsNames.size(), mode, indivVerExp, indivRelExp, natLanguage);
terminated = true;
}
// Verification operations with DefectsVerifier
else if (type.equals(StringUtils.formatEnumValue(OpersSubOpType.IdDef_Defects_Verif.toString()))
|| type.equals(StringUtils
.formatEnumValue(OpersSubOpType.UpdModel_Defects_Verif.toString()))) {
String method = (String) suboper.getInstAttributeValue("defectType");
String errorHint = (String) suboper.getInstAttributeValue("errorHint");
String outAttribute = (String) suboper.getInstAttributeValue("outAttribute");
boolean reuseFreeIds = (boolean) suboper.getInstAttributeValue("reuseFreeIds");
boolean updateFreeIds = (boolean) suboper.getInstAttributeValue("updateFreeIds");
String coreOperName = null;
InstElement coreOperation = null;
boolean updateOutAttributes = false;
List<IntBooleanExpression> constraitsToVerifyRedundacies = null;
if (type.equals(
StringUtils.formatEnumValue(OpersSubOpType.IdDef_Defects_Verif.toString()))) {
coreOperName = (String) suboper.getInstAttributeValue("defectsCoreOper");
if (coreOperName == null)
coreOperName = "Update Core Elements";
coreOperation = refas2hlcl.getRefas().getSyntaxModel().getOperationalModel()
.getVertexByName(coreOperName);
if (method.equals("getRedundancies") || method.equals("getFalsePLs")) {
constraitsToVerifyRedundacies = refas2hlcl.getHlclProgram(operationObj,
suboper.getIdentifier(), OpersSubOpExecType.TOVERIFY, null);
}
}
updateOutAttributes = (boolean) suboper.getInstAttributeValue("updateOutAttributes");
List<OpersIOAttribute> outAttributes = ((OpersSubOperation) suboper.getEdOperEle())
.getOutAttributes();
result = defectsVerifier(operationObj, suboper, method, errorHint, outAttributes,
operationsNames.size(), reuseFreeIds, updateFreeIds, outAttribute,
updateOutAttributes, coreOperation, constraitsToVerifyRedundacies);
terminated = true;
}
else if (type
.equals(StringUtils
.formatEnumValue(OpersSubOpType.ValidateDerivation
.toString())))
{
MainParser.message=""; // parser
if(MainParser.files_to_analize.isEmpty()) {
completedMessage="No files to validate, please derive a product first";
}else {
completedMessage=MainParser.executeParser(Fragmental.assembled_folder);
}
result = 0;
terminated = true;
}
else if (type
.equals(StringUtils
.formatEnumValue(OpersSubOpType.ExecuteDerivation
.toString())))
{
//start time
long startTime = System.nanoTime();
List<Map<String, String>> files = new ArrayList<>();
Boolean components_found=false;
ArrayList<String> components_to_assemble = new ArrayList<String>();
Fragmental.customize_files = new ArrayList<String>(); // used in customization
MainParser.files_to_analize = new ArrayList<String>(); // parser
MainParser.message=""; // parser
for (InstElement instE : refasModel.getElements()) {
String id="";
id= (String) instE.getSupSyntaxEleId();
if(id != null && id.startsWith("SyMPairwise2")) {
List<InstElement> listT = instE.getTargetRelations();
InstElement instT = listT.get(0);
Boolean selected= (Boolean) instT.getInstAttributeValue("SelectedToIntegrate");
if(selected) {
List<InstElement> listS = instE.getSourceRelations();
InstElement instS = listS.get(0);
String name= (String) instS.getInstAttributeValue("Name");
components_to_assemble.add(name);
}
}
}
for (InstElement instE : refasModel.getElements()) {
Map<String, String> file_map = new HashMap<String, String>();
boolean value=false;
String id="";
id= (String) instE.getSupSyntaxEleId();
if(id != null && id.startsWith("SyMPairwise1")) {
List<InstElement> listT = instE.getTargetRelations();
InstElement instT = listT.get(0);
String name = (String) instT.getInstAttributeValue("Name");
String folderc = "";
String filec = "";
if (components_to_assemble.contains(name)) {
components_found=true;
file_map.put("component_folder", name);
folderc = name;
List<InstElement> listS = instE.getSourceRelations();
InstElement instS = listS.get(0);
name= (String) instS.getInstAttributeValue("Name");
file_map.put("ID", name);
name= (String) instS.getInstAttributeValue("filename");
filec=name;
file_map.put("filename", name);
name= (String) instS.getInstAttributeValue("destination");
file_map.put("destination", name);
if(filec.equals("customization.json")) {
Fragmental.customize_files.add(folderc+"/"+filec); // used in customization
}else {
MainParser.files_to_analize.add(name); //to be parsed
files.add(file_map);
}
}
}
}
if(components_found) {
Fragmental.principal(files);
String found_errors=Fragmental.get_errors();
if(found_errors.equals("")) {
completedMessage=found_errors+"!!!Components successfully assembled!!!";
}else {
completedMessage=found_errors+"!!!Components assembled with multiple errors!!!";
}
}else {
completedMessage="There are not components selected to be assembled";
}
//end time
long elapsedTimeNs = System.nanoTime() - startTime;
System.out.println("Time: "+elapsedTimeNs);
result = 0;
terminated = true;
}
// TODO modifications by avillota for including MEDIC
else if (type.equals(StringUtils.formatEnumValue(OpersSubOpType.Medic.toString()))) {
String errorHint = (String) suboper.getInstAttributeValue("errorHint");
String outAttribute = (String) suboper.getInstAttributeValue("outAttribute");
// Sub orpetion id for diferenciate the one for graphs and the one for features
List<OpersIOAttribute> outAttributes = ((OpersSubOperation) suboper.getEdOperEle())
.getOutAttributes();
// PONER AQUi LAS INSTRUCCIONES PARA TOMAR LOS INPUTS
// Call to the method that calls medic
// result is -1 if something fails,
// if the model is consistent
// > 1 if it has inconsistencies
result = medicExecution(operationObj, suboper, errorHint, outAttributes, outAttribute);
// the operation should finish
terminated = true;
} else {
result = -1;
}
if (result == 0) {
update = true;
outVariables = refas2hlcl.getOutVariables(operationName, suboper.getIdentifier());
if (simul)
lastConfiguration = refas2hlcl.getConfiguration();
if (computationalAnalysis) {
if (!type.equals(
StringUtils.formatEnumValue(OpersSubOpType.Number_Solutions.toString())))
results[subOperIndex++] = refas2hlcl.getSingleOutValue(outVariables, suboper);
if (suboper.getInstAttributeValue("completedMessage") != null
&& !((String) suboper.getInstAttributeValue("completedMessage")).equals("")) {
completedMessage = (String) suboper.getInstAttributeValue("completedMessage");
if (completedMessage.contains("#numerator#"))
completedMessage = completedMessage.replace("#numerator#", results[0] + "");
if (completedMessage.contains("#denominator#"))
completedMessage = completedMessage.replace("#denominator#", results[1] + "");
if (completedMessage.contains("#result#")) {
if (results[1] == 0)
errorMessage = "Division by zero";
else {
if (computationalType.equals(StringUtils
.formatEnumValue(OpersComputationType.Simple_Quotient.toString())))
completedMessage = completedMessage.replace("#result#",
(results[0] * 1f) / results[1] + "");
else if (computationalType.equals(StringUtils.formatEnumValue(
OpersComputationType.One_Less_Quotient.toString())))
completedMessage = completedMessage.replace("#result#",
(1 - (results[0] * 1f) / results[1]) + "");
else if (computationalType.equals(StringUtils.formatEnumValue(
OpersComputationType.Quotient_denominator_exp_base_2
.toString())))
completedMessage = completedMessage.replace("#result#",
(results[0] * 1f) / Math.pow(2, results[1]) + "");
}
}
}
} else {
refas2hlcl.updateGUIElements(null, outVariables, suboper);
}
// messagesArea.setText(refas2hlcl.getText());
// bringUpTab(mxResources.get("elementSimPropTab"));
// editPropertiesRefas(editor.lastEditableElement);
// }
// correctExecution = true;
long endTime = System.currentTimeMillis();
executionTime = this.operationsNames.get(0) + (endTime - iniTime) + "["
+ (refas2hlcl.getLastExecutionTime() / 1000000) + "]" + " -- ";
System.out.println(executionTime);
} else {
if (result == -1)
if (firstSimulExec && lastConfiguration == null) {
errorMessage += (String) suboper.getInstAttributeValue("errorText");
errorTitle = (String) suboper.getInstAttributeValue("errorTitle");
correctExecution = false;
terminated = true;
} else {
errorMessage = "No more solutions found";
errorTitle = "Simulation Message";
correctExecution = false;
}
if (result >= 1)
if (computationalAnalysis) {
results[subOperIndex++] = result;
if (suboper.getInstAttributeValue("completedMessage") != null
&& !((String) suboper.getInstAttributeValue("completedMessage"))
.equals("")) {
completedMessage = (String) suboper.getInstAttributeValue("completedMessage");
if (completedMessage.contains("#numerator#"))
completedMessage = completedMessage.replace("#numerator#", results[0] + "");
if (completedMessage.contains("#denominator#"))
completedMessage = completedMessage.replace("#denominator#",
results[1] + "");
if (completedMessage.contains("#result#")) {
if (results[1] == 0)
errorMessage = "Division by zero";
else {
if (computationalType.equals(StringUtils.formatEnumValue(
OpersComputationType.Simple_Quotient.toString())))
completedMessage = completedMessage.replace("#result#",
(results[0] * 1f) / results[1] + "");
else if (computationalType.equals(StringUtils.formatEnumValue(
OpersComputationType.One_Less_Quotient.toString())))
completedMessage = completedMessage.replace("#result#",
(1 - (results[0] * 1f) / results[1]) + "");
else if (computationalType.equals(StringUtils.formatEnumValue(
OpersComputationType.Quotient_denominator_exp_base_2
.toString())))
completedMessage = completedMessage.replace("#result#",
(results[0] * 1f) / Math.pow(2, results[1]) + "");
}
}
}
} else if (firstSimulExec && lastConfiguration == null) {
outVariables
.addAll(refas2hlcl.getOutVariables(operationName, suboper.getIdentifier()));
errorMessage += (String) suboper.getInstAttributeValue("errorMsg");
if (errorMessage.contains("#number#"))
errorMessage = errorMessage.replace("#number#", result + "");
errorTitle = (String) suboper.getInstAttributeValue("errorTitle");
correctExecution = false;
// terminated = true;
} else {
errorMessage = "No more solutions found";
errorTitle = "Simulation Message";
correctExecution = false;
}
// terminated = true;
}
} catch (Exception e) {
// FIXME issue#230
throw new FunctionalException(FunctionalException.exceptionStacktraceToString(e));
}
// Only two suboperations allowed for computational analysis
if (subOperIndex == 2)
break;
}
if (!firstSimulExec && result == 1)
// Update GUI after first execution, editor is not notify
// because the task is at 100%
this.refas2hlcl.updateGUIElements(null, outVariables, lastSubOper);
}
task = 100;
setProgress((int) task);
this.setProgress(100);
}
}
private void resetFreeIdentifiers() {
defectsFreeIdsName = null;
}
/**
* Call to the method that calls medic result is -1 if something fails, 0 if the
* model is consistent > 1 if it has inconsistencies
*
* @param operation
* @param subOper
* @param verifHint
* @param outAttributes
* @param outAttribute
* @return
* @throws Exception
*/
public int medicExecution(InstElement operation, InstElement subOper, String verifHint,
List<OpersIOAttribute> outAttributes, // pend
String outAttribute) throws Exception {
String subOperationID = (String) subOper.getInstAttributeValue("userId");
int result = 0;
TranslationExpressionSet transExpSet = new TranslationExpressionSet(refasModel, operation, null, null);
Map<IntBooleanExpression, String> table = new HashMap<>();
HlclProgram program = refas2hlcl.getHlclProgram(operation, subOper.getIdentifier(), OpersSubOpExecType.NORMAL,
transExpSet, table);
// use for print table table
// for (IntBooleanExpression e : table.keySet()) {
//
// System.out.println(table.get(e)+" ,"+e);
//
// }
if (program != null) {
SWIPrologSolver swiSolver = new SWIPrologSolver();
swiSolver.setHLCLProgram(program); // passing the hlcl program to the solver
//System.out.println(program);
swiSolver.solve(); // This method prepares the solver
boolean satisfiable = swiSolver.hasSolution(); // Consulting if the solver has one solution
if (satisfiable) {
result = 0;
} else {
ArrayList<String> inconsistentPath = new ArrayList<String>();
ArrayList<String> inconsistentMsg = new ArrayList<String>();
System.out.println("======================================================================");
System.out.println("======================================================================");
// Log parameters allow the activation of the logManager,
// to start an execution using a log manager comment line 722 and uncomment line
// 723
// using a valid path and a name for the problem
LogParameters params = new LogParameters();
// LogParameters params= new LogParameters("/Users/Angela/Test/", "test");
MinimalSetsDFSIterationsHLCL medic = new MinimalSetsDFSIterationsHLCL(program, params);
// Setting the root variable regarding the type of model
String root = getRoot();
if (subOperationID.equals("Medic-features")) // Medic over feature models
{
if (root == null) // if the user did not pick a root, the algorithm starts in the root
root = "RootFeature1_Sel";
else // the algorithm starts with the attribute "Sel" of the selected feature
root += "_Sel";
}
else { // Medic over constraint graphs
if (root == null) // if the user did not pick a root, the algorithm starts in the first variable
root = "CGVariable1_value";
else // the algorithm starts with the first variable selected
root += "_value";
}
LinkedList<VertexHLCL> output = medic.sourceOfInconsistentConstraints(root, 10);
// LinkedList<VertexHLCL> output=
// medic.sourceOfInconsistentConstraints("CGVariable1_value",10);
for (VertexHLCL vertex : output) {
if (vertex instanceof NodeVariableHLCL) {
// Add the variable into the list of IDs to be updated
// Add the error message
String [] split =vertex.getId().split("_");
String varId= split[0];
if (!varId.equals("") && !inconsistentPath.contains(varId)) {
inconsistentPath.add(varId);
// System.out.println(vertex.getId() + " id:" + consId );
inconsistentMsg.add("variable in the inconsistent path");
}
//inconsistentPath.add(split[0]);
// añadir la variable a la lista y después una por una las retsricciones
// unarias asociadas.
for (NodeConstraintHLCL cons : ((NodeVariableHLCL) vertex).getUnary()) {
String [] object = getIdFromTable(cons.getConstraint(), table).split("_"); //this lines allow to obtain the id of the object
String consId =object[0];//the first part of the id is the name of the object
//String consId = getIdFromTable(cons.getConstraint(), table).replaceFirst("_value", "");
// System.out.println(cons.getId() + " id:" + consId );
if (!consId.equals("") && !inconsistentPath.contains(consId)) {
inconsistentPath.add(consId);
// System.out.println(vertex.getId() + " id:" + consId );
inconsistentMsg.add("Constraint in the inconsistent path");
}
}
} else {
//IntBooleanExpression con= ((NodeConstraintHLCL) vertex).getConstraint();
//String cad= getIdFromTable(((NodeConstraintHLCL) vertex).getConstraint(), table);
String [] split = getIdFromTable(((NodeConstraintHLCL) vertex).getConstraint(), table).split("_");
String consId = split[0]; //the first part of the id is the name of the object
//String consId = getIdFromTable(((NodeConstraintHLCL) vertex).getConstraint(), table).replaceFirst("_value", "");
if (!consId.equals("") && !inconsistentPath.contains(consId)) {
inconsistentPath.add(consId);
// System.out.println(vertex.getId() + " id:" + consId );
inconsistentMsg.add("Constraint in the inconsistent path");
}
}
}
// for (String s: inconsistentPath) {
// System.out.print(s+ ", ");
//
// }
refas2hlcl.updateErrorMark(inconsistentPath, verifHint, inconsistentMsg);
}
return result;
} else {
result = -1;
throw new FunctionalException("The translation is not working properly, the constraint program i empty");
}
}
/**
* Method to obtain the Id of a contstraint represented as a HLCL expression
*
* @param constraint
* hlcl expression
* @param table
* map with the constraints and the Ids
* @return
*/
private String getIdFromTable(IntBooleanExpression constraint, Map<IntBooleanExpression, String> table) {
return table.get(constraint);
}
private int defectsVerifier(InstElement operation, InstElement subOper, String method, String verifHint,
List<OpersIOAttribute> outAttributes, int numberOperations, boolean reuseIds, boolean updateIds,
String outAttribute, boolean updateOutAttributes, InstElement coreOperation,
List<IntBooleanExpression> constraitsToVerifyRedundacies) throws InterruptedException, FunctionalException {
int result = 0;
executionTime = "";
if (coreOperation == null && !method.equals("getRedundancies") && !method.equals("getFalsePLs"))
// Update core
result = defectExecution(operation, subOper, method, outAttributes, numberOperations, outAttribute,
updateOutAttributes);
else
result = defectExecution(operation, subOper, method, verifHint, outAttributes, numberOperations, reuseIds,
updateIds, outAttribute, updateOutAttributes, coreOperation, constraitsToVerifyRedundacies);
if (progressMonitor.isCanceled())
throw (new InterruptedException());
return result;
}
private int cauCos(int type, InstElement operation, InstElement subOper, String verifHint,
List<OpersIOAttribute> outAttributes, boolean updateOutAttributes, String outAttribute,
int numberOperations, DefectAnalyzerModeEnum mode, boolean indivVerExp, boolean indivRelExp,
boolean natLanguage) throws InterruptedException {
int outResult = 0;
executionTime = "";
// type: for future variations on the execution
String verifElement = operation.getIdentifier();
long iniTime = System.currentTimeMillis();
long iniSTime = 0;
long endSTime = 0;
try {
// que es un translation expression set?
TranslationExpressionSet transExpSet = new TranslationExpressionSet(refasModel, operation, null, null);
List<IntBooleanExpression> verifyList = refas2hlcl.getHlclProgram(operation, subOper.getIdentifier(),
OpersSubOpExecType.VERIFICATION, transExpSet);
HlclProgram relaxedList = refas2hlcl.getHlclProgram(operation, subOper.getIdentifier(),
OpersSubOpExecType.RELAXABLE, transExpSet);
List<ModelExpr> relaxedMEList = refas2hlcl.getInstanceExpressions(operation, subOper.getIdentifier(),
OpersSubOpExecType.RELAXABLE);
HlclProgram fixedList = refas2hlcl.getHlclProgram(operation, subOper.getIdentifier(),
OpersSubOpExecType.NORMAL, transExpSet);
Set<String> outIdentifiersSet = new TreeSet<String>();
ArrayList<String> outIdentifiersList = new ArrayList<String>();
String defects = "(";
HlclProgram modelToVerify = new HlclProgram();
modelToVerify.addAll(verifyList);
modelToVerify.addAll(relaxedList);
modelToVerify.addAll(fixedList);
IntDefectsVerifier verifier = new DefectsVerifier(modelToVerify);
// The model has two or more roots
Defect voidModel = verifier.isVoid();
Iterator<IntBooleanExpression> verifyIter = verifyList.iterator();
Iterator<IntBooleanExpression> relaxedIter = relaxedList.iterator();
ArrayList<String> naturalLanguageHints = new ArrayList<String>();
if (voidModel != null) {
List<IntBooleanExpression> verify = verifyList;
HlclProgram relaxed = relaxedList;
HlclProgram fixed = fixedList;
do {
if (indivVerExp) {
verify = new ArrayList<IntBooleanExpression>();
if (verifyIter.hasNext())
verify.add(verifyIter.next());
}
do {
if (indivRelExp) {
relaxed = new HlclProgram();
if (relaxedIter.hasNext()) {
relaxed.add(relaxedIter.next());
}
}
Defect defect = new Defect(verify);
defect.setDefectType(DefectTypeEnum.SEMANTIC_SPECIFIC_DEFECT);
iniSTime = System.currentTimeMillis();
if (progressMonitor.isCanceled())
throw (new InterruptedException());
IntCauCosAnalyzer cauCosAnalyzer = new CauCosAnayzer(parentComponent, verifElement);
HlclProgram fixedConstraint = new HlclProgram();
fixedConstraint.addAll(verify);
fixedConstraint.addAll(fixed);
Diagnosis result = cauCosAnalyzer.getCauCos(defect, relaxed, fixedConstraint, mode);
endSTime = System.currentTimeMillis();
for (CauCos correction : result.getCorrections()) {
if (progressMonitor.isCanceled())
throw (new InterruptedException());
List<IntBooleanExpression> corr = correction.getElements();
for (IntBooleanExpression expression : corr) {