This repository was archived by the owner on May 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathUncertainties.mo
More file actions
3918 lines (3596 loc) · 134 KB
/
Uncertainties.mo
File metadata and controls
3918 lines (3596 loc) · 134 KB
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
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package Uncertainties
public import Absyn;
public import BackendDAE;
public import BackendVarTransform;
public import DAE;
public import FCore;
public import GlobalScript;
public import HashTable;
public import Values;
protected
import AdjacencyMatrix;
import Algorithm;
import BackendDAECreate;
import BackendDAEEXT;
import BackendDAEUtil;
import BackendEquation;
import BackendVariable;
import BaseHashSet;
import BaseHashTable;
import ClassInf;
import ClockIndexes;
import ComponentReference;
import DAEUtil;
import Error;
import Expression;
import ExpressionSimplify;
import ExpressionSolve;
import Flags;
import HashSet;
import HashTable2;
import InnerOuter;
import Inst;
import List;
import Matching;
import MathematicaDump;
import Print;
import SCode;
import SCodeUtil;
import Sorting;
import SymbolTable;
import System;
import Util;
protected type ExtIncidenceMatrixRow = tuple<Integer,list<Integer>>;
protected type ExtIncidenceMatrix = list<ExtIncidenceMatrixRow>;
protected type mapBlocks =list<tuple<list<Integer>,Boolean,Boolean>>; // {blocks,blocks.visited,blocks.square}
public constant String UNDERLINE = "==========================================================================";
protected uniontype AliasSet
record ALIASSET
HashSet.HashSet symbols;
HashTable2.HashTable expl;
HashTable.HashTable signs;
Option<DAE.ElementSource> source;
end ALIASSET;
end AliasSet;
public function modelEquationsUC
input FCore.Cache inCache;
input FCore.Graph inEnv;
input Absyn.Path className "path for the model";
input String outputFileIn;
input Boolean dumpSteps;
output FCore.Cache outCache;
output Values.Value outValue;
algorithm
(outCache,outValue):=
matchcontinue (inCache,inEnv,className,outputFileIn,dumpSteps)
local
String outputFile,resstr;
DAE.DAElist dae;
FCore.Cache cache;
FCore.Graph graph;
Absyn.Program p;
BackendDAE.BackendDAE dlow,dlow_1;
BackendDAE.IncidenceMatrix m,mt;
list<Integer> approximatedEquations,approximatedEquations_one;
list<BackendDAE.Equation> setC_eq,setS_eq;
list<BackendDAE.EqSystem> eqsyslist;
BackendDAE.Variables allVars,knownVariables,unknownVariables,globalKnownVars;
BackendDAE.EquationArray allEqs;
list<Integer> variables,knowns,unknowns,directlyLinked,indirectlyLinked,outputvars;
BackendDAE.Shared shared;
BackendDAE.EqSystem currentSystem;
ExtIncidenceMatrix mExt;
list<Integer> setS,setC,unknownsVarsMatch,remainingEquations,removed_equations_squared;
array<list<Integer>> mapEqnIncRow;
array<Integer> mapIncRowEqn;
String outStringA,outStringB,outString,description;
list<Option<DAE.Distribution>> distributions;
Boolean forceOrdering = Flags.getConfigBool(Flags.DEFAULT_OPT_MODULES_ORDERING);
case (cache,graph,_,outputFile,_)
equation
//print("Initiating\n");
Print.clearBuf();
p = SymbolTable.getAbsyn();
(dae,cache,graph) = flattenModel(className,p,cache);
description = DAEUtil.daeDescription(dae);
//print("- Flatten ok\n");
dlow = BackendDAECreate.lower(dae,cache,graph,BackendDAE.EXTRA_INFO(description,outputFile));
//(dlow_1,funcs1) = BackendDAEUtil.getSolvedSystem(dlow, funcs,SOME({"removeSimpleEquations","removeFinalParameters", "removeEqualFunctionCalls", "expandDerOperator"}), NONE(), NONE(),NONE());
Flags.setConfigBool(Flags.DEFAULT_OPT_MODULES_ORDERING, false);
(dlow_1) = BackendDAEUtil.getSolvedSystem(dlow, "", SOME({"removeSimpleEquations","removeUnusedVariables","removeEqualFunctionCalls","expandDerOperator"}), NONE(), NONE(), SOME({}));
Flags.setConfigBool(Flags.DEFAULT_OPT_MODULES_ORDERING, forceOrdering);
//print("* Lowered Ok \n");
dlow_1 = removeSimpleEquationsUC(dlow_1);
BackendDAE.DAE(currentSystem::eqsyslist,shared) = dlow_1;
BackendDAE.EQSYSTEM(orderedVars=allVars,orderedEqs=allEqs) = currentSystem;
BackendDAE.SHARED(globalKnownVars=globalKnownVars) = shared;
(m,_,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.incidenceMatrixScalar(currentSystem,BackendDAE.NORMAL(),NONE());
//(dlow_1 as BackendDAE.DAE(BackendDAE.EQSYSTEM(orderedVars=allVars,orderedEqs=allEqs,m=SOME(m),mT=SOME(mt))::eqsyslist,_)) = BackendDAEUtil.mapEqSystem(dlow_1,BackendDAEUtil.getIncidenceMatrixScalarfromOptionForMapEqSystem);
true = listEmpty(eqsyslist);
mExt=getExtIncidenceMatrix(m);
//dumpExtIncidenceMatrix(mExt);
variables = List.intRange(BackendVariable.varsSize(allVars));
(knowns,_) = getUncertainRefineVariableIndexes(allVars,variables);
directlyLinked = getRelatedVariables(mExt,knowns);
indirectlyLinked = List.setDifference(getRelatedVariables(mExt,directlyLinked),knowns);
unknowns = listAppend(directlyLinked,indirectlyLinked);
outputvars = List.setDifference(List.intRange(BackendVariable.varsSize(allVars)),listAppend(unknowns,knowns));
// First try to eliminate all the unknown variables
dlow_1 = eliminateVariablesDAE(unknowns,dlow_1);
printSep(getMathematicaText("== Initial system =="));
// printSep(getMathematicaText("Equations (Function calls represent more than one equation"));
// printSep(equationsToMathematicaGrid(List.intRange(BackendEquation.equationArraySize(allEqs)),allEqs,allVars,globalKnownVars,mapIncRowEqn));
// printSep(getMathematicaText("All variables"));
// printSep(variablesToMathematicaGrid(List.intRange(BackendVariable.varsSize(allVars)),allVars));
//print("Checkpoint 1\n");
BackendDAE.DAE(currentSystem::_,shared) = dlow_1;
BackendDAE.EQSYSTEM(orderedVars=allVars,orderedEqs=allEqs) = currentSystem;
BackendDAE.SHARED(globalKnownVars=globalKnownVars) = shared;
(m,_,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.incidenceMatrixScalar(currentSystem,BackendDAE.NORMAL(),NONE());
printSep(getMathematicaText("After Symbolic Elimination"));
printSep(getMathematicaText("Equations (Function calls represent more than one equation)"));
printSep(equationsToMathematicaGrid(List.intRange(BackendEquation.equationArraySize(allEqs)),allEqs,allVars,globalKnownVars,mapIncRowEqn));
printSep(getMathematicaText("Variables"));
printSep(variablesToMathematicaGrid(List.intRange(BackendVariable.varsSize(allVars)),allVars));
mExt=getExtIncidenceMatrix(m);
approximatedEquations_one = getEquationsWithApproximatedAnnotation(dlow_1);
approximatedEquations = List.flatten(List.map1r(approximatedEquations_one,listGet,arrayList(mapEqnIncRow)));
mExt=removeEquations(mExt,approximatedEquations);
printSep(getMathematicaText("Approximated equations to be removed"));
printSep(equationsToMathematicaGrid(approximatedEquations,allEqs,allVars,globalKnownVars,mapIncRowEqn));
printSep(getMathematicaText("After eliminating approximated equations"));
printSep(equationsToMathematicaGrid(getEquationsNumber(mExt),allEqs,allVars,globalKnownVars,mapIncRowEqn));
// get the variable indices after the elimination
variables = List.intRange(BackendVariable.varsSize(allVars));
(knowns,distributions) = getUncertainRefineVariableIndexes(allVars,variables);
directlyLinked = getRelatedVariables(mExt,knowns);
indirectlyLinked = List.setDifference(getRelatedVariables(mExt,directlyLinked),knowns);
unknowns = listAppend(directlyLinked,indirectlyLinked);
outputvars = List.setDifference(List.intRange(BackendVariable.varsSize(allVars)),listAppend(unknowns,knowns));
printSep(getMathematicaText("Known variables"));
printSep(variablesToMathematicaGrid(knowns,allVars));
printSep(getMathematicaText("Directly linked variables"));
printSep(variablesToMathematicaGrid(directlyLinked,allVars));
printSep(getMathematicaText("Indirectly linked variables"));
printSep(variablesToMathematicaGrid(indirectlyLinked,allVars));
printSep(getMathematicaText("Output variables"));
printSep(variablesToMathematicaGrid(outputvars,allVars));
mExt=eliminateOutputVariables(mExt,outputvars);
printSep(getMathematicaText("After eliminating output variables"));
printSep(equationsToMathematicaGrid(getEquationsNumber(mExt),allEqs,allVars,globalKnownVars,mapIncRowEqn));
(setS,unknownsVarsMatch)=getEquationsForUnknownsSystem(mExt,knowns,unknowns);
printSep(getMathematicaText("Matching performed after step 5 (Set S)"));
printSep(unknowsMatchingToMathematicaGrid(unknownsVarsMatch,setS,allEqs,allVars,globalKnownVars,mapIncRowEqn));
remainingEquations=List.setDifference(getEquationsNumber(mExt),setS);
printSep(getMathematicaText("Remaining equations"));
printSep(equationsToMathematicaGrid(remainingEquations,allEqs,allVars,globalKnownVars,mapIncRowEqn));
(setC,removed_equations_squared)=getEquationsForKnownsSystem(mExt,knowns,unknowns,setS,allEqs,allVars,globalKnownVars,mapIncRowEqn);
if not listEmpty(removed_equations_squared) then
print("Warning: the system is ill-posed. One or more equations have been removed from squared system of knowns.\n");
end if;
printSep(getMathematicaText("Equations removed from squared blocks (with more than one equation)"));
printSep(equationsToMathematicaGrid(removed_equations_squared,allEqs,allVars,globalKnownVars,mapIncRowEqn));
printSep(getMathematicaText("Final Equations"));
printSep(equationsToMathematicaGrid(setC,allEqs,allVars,globalKnownVars,mapIncRowEqn));
setC = List.map1r(setC, listGet, arrayList(mapIncRowEqn));
setC = List.unique(setC);
setS = List.map1r(setS, listGet, arrayList(mapIncRowEqn));
setS = List.unique(setS);
setC_eq = List.map1r(setC, BackendEquation.get, allEqs);
setS_eq = List.map1r(setS, BackendEquation.get, allEqs);
//eqnLst = BackendEquation.equationList(eqns);
knownVariables = BackendVariable.listVar(List.map1r(knowns,BackendVariable.getVarAt,allVars));
unknownVariables = BackendVariable.listVar(List.map1r(unknowns,BackendVariable.getVarAt,allVars));
//print("* Uncertainty equations extracted: \n");
//BackendDump.dumpEquationList(setC_eq,"setC");
//print("* Auxiliary set of equations: \n");
//BackendDump.dumpEquationList(setS_eq,"setS");
outStringB = "{{"+getMathematicaVarStr(knownVariables)+","+getMathematicaEqStr(setC_eq,allVars,globalKnownVars)+"},{"
+getMathematicaVarStr(unknownVariables)+","+getMathematicaEqStr(setS_eq,allVars,globalKnownVars)+"},"
+dumpVarsDistributionInfo(distributions)+"}";
Print.printBuf("{"+getMathematicaText("Extraction finished")+"}");
outStringA = "Grid[{"+Print.getString()+"}]";
outString=if dumpSteps then outStringA else outStringB;
resstr=writeFileIfNonEmpty(outputFile,outString);
//resstr="Done...";
then
(cache,Values.STRING(resstr));
case (_,_,_,outputFile,_)
equation
Print.printBuf("{"+getMathematicaText("Extraction failed")+"}");
outStringA = "Grid[{"+Print.getString()+"}]";
_=writeFileIfNonEmpty(outputFile,outStringA);
true = Flags.isSet(Flags.FAILTRACE);
resstr = Absyn.pathStringNoQual(className);
resstr = stringAppendList({"modelEquationsUC: The model equations in model",resstr," could not be extracted"});
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
then
fail();
end matchcontinue;
end modelEquationsUC;
public function dataReconciliation
input BackendDAE.BackendDAE inDae;
output BackendDAE.BackendDAE outDae;
algorithm
outDae:=match(inDae)
local
BackendDAE.BackendDAE dae;
BackendDAE.BackendDAE dlow,dlow_1;
BackendDAE.IncidenceMatrix m,mt;
list<Integer> approximatedEquations,approximatedEquations_one;
list<BackendDAE.Equation> setC_eq,setS_eq;
list<BackendDAE.EqSystem> eqsyslist;
BackendDAE.Variables allVars,knownVariables,unknownVariables,globalKnownVars,finalvars;
BackendDAE.EquationArray allEqs,newEqs;
list<Integer> variables,knowns,unknowns,directlyLinked,indirectlyLinked,inputvar,outputvars,fullvars,finalvarlist;
BackendDAE.Shared shared;
BackendDAE.EqSystem currentSystem;
ExtIncidenceMatrix mExt;
list<Integer> setS,setC,tempsetS,tempsetC,removedequationsquared;
array<list<Integer>> mapEqnIncRow;
array<Integer> mapIncRowEqn, match1,match2;
list<list<Integer>> bltblocks,blockstofind;
list<tuple<list<Integer>,Integer>> blockranks;
list<list<String>> blockstatus;
list<tuple<Integer,Integer>> var;
list<BackendDAE.Var> tempvar;
list<tuple<list<Integer>,list<tuple<list<Integer>,Integer>>,list<tuple<list<String>,Integer>>>> blocktargetinfo;
list<Boolean> blocksqstatus;
list<Integer> removedequationssolvedvar,outputblocks,removedequationvars,approximated_eq_solvar;
mapBlocks initblocks;
list<tuple<list<Integer>,list<String>,Boolean,Integer,Boolean>> blockdata;
String modelname;
BackendDAE.ExtraInfo einfo;
case(dae)
equation
BackendDAE.DAE(currentSystem::eqsyslist,shared) = dae;
BackendDAE.EQSYSTEM(orderedVars=allVars,orderedEqs=allEqs) = currentSystem;
BackendDAE.SHARED(globalKnownVars=globalKnownVars,info=einfo) = shared;
BackendDAE.EXTRA_INFO(fileNamePrefix=modelname)= einfo;
(m,_,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.incidenceMatrixScalar(currentSystem,BackendDAE.NORMAL(),NONE());
print("\nModelInfo: " + modelname + "\n" + UNDERLINE + "\n\n");
BackendDump.dumpEquationArray(allEqs,"orderedEquation");
BackendDump.dumpVariables(allVars,"orderedVariables");
(match1,match2) = Matching.PerfectMatching(m);
var=dumpMatching(match1);
BackendDump.dumpMatching(match1);
bltblocks=Sorting.Tarjan(m,match1);
// dump BLT BLOCKS
dumpListList(bltblocks,"BLT_BLOCKS");
true = listEmpty(eqsyslist);
mExt=getExtIncidenceMatrix(m);
//dumpExtIncidenceMatrix(mExt);
// Extract List of variables
variables = List.intRange(BackendVariable.varsSize(allVars));
(knowns,_) = getUncertainRefineVariableIndexes(allVars,variables);
directlyLinked = getRelatedVariables(mExt,knowns);
indirectlyLinked = List.setDifference(getRelatedVariables(mExt,directlyLinked),knowns);
unknowns = listAppend(directlyLinked,indirectlyLinked);
outputvars = List.setDifference(List.intRange(BackendVariable.varsSize(allVars)),listAppend(unknowns,knowns));
unknowns = listAppend(unknowns,outputvars);
fullvars =listAppend(unknowns,knowns);
initblocks=setInitialBlocks(bltblocks);
// Extract approximated equation
approximatedEquations_one = getEquationsWithApproximatedAnnotation(dae);
approximatedEquations = List.flatten(List.map1r(approximatedEquations_one,listGet,arrayList(mapEqnIncRow)));
approximated_eq_solvar = getRemovedEquationSolvedVariables(approximatedEquations,var);
// Extraction Algorithm steps
(blockstofind,blockstatus)=originalBlocks(bltblocks,knowns,unknowns,outputvars,var);
blockranks=List.toListWithPositions(blockstofind);
blockstatus=checkBlockStatus(blockstofind,blockstatus);
blocktargetinfo=findBlockTargets(blockstofind,blockstatus,var,mExt,initblocks,blockranks);
//step-3 of algorithm
(blocksqstatus,blockdata)=findSquareAndNonSquareBlocks(blocktargetinfo,var,mExt,initblocks);
//Step-4 of algorithm
(tempsetC,tempsetS,removedequationsquared)=ExtractEquationsfromBlocks(blockdata,approximatedEquations);
tempsetC=List.setDifferenceOnTrue(tempsetC,approximatedEquations,intEq);
tempsetS=List.setDifferenceOnTrue(tempsetS,approximatedEquations,intEq);
tempsetC = List.setDifferenceOnTrue(tempsetC,tempsetS,intEq);
print("\nFINAL SET OF EQUATIONS After Reconciliation \n" + UNDERLINE + "\n" +"SET_C: "+dumplistInteger(tempsetC)+"\n" +"SET_S: "+ dumplistInteger(tempsetS)+ "\n\n" );
//BackendDump.dumpList(setC,"setC_Eqs :");
//BackendDump.dumpList(setS,"setS_Eqs :");
removedequationsquared=List.setDifferenceOnTrue(removedequationsquared,tempsetS,intEq);
removedequationsquared=List.unique(listAppend(removedequationsquared,approximatedEquations));
removedequationssolvedvar=getRemovedEquationSolvedVariables(removedequationsquared,var);
//removedequationvars=getRemovedEquationSolvedVariables(outputblocks,var);
//removedequationvars={};
setC = List.map1r(tempsetC, listGet, arrayList(mapIncRowEqn));
setC = List.unique(setC);
setS = List.map1r(tempsetS, listGet, arrayList(mapIncRowEqn));
setS = List.unique(setS);
setC_eq = List.map1r(setC, BackendEquation.get, allEqs);
setS_eq = List.map1r(setS, BackendEquation.get, allEqs);
finalvarlist=List.setDifferenceOnTrue(fullvars,removedequationssolvedvar,intEq);
finalvars=BackendVariable.listVar(List.map1r(finalvarlist,BackendVariable.getVarAt,allVars));
tempvar= List.map1r(removedequationssolvedvar,BackendVariable.getVarAt,allVars);
globalKnownVars=BackendVariable.listVar(List.map1(tempvar,BackendVariable.setVarDirection,DAE.INPUT()));
newEqs=BackendEquation.listEquation(listAppend(setC_eq,setS_eq));
currentSystem=BackendDAEUtil.setEqSystVars(currentSystem,finalvars);
currentSystem=BackendDAEUtil.setEqSystEqs(currentSystem,newEqs);
shared = BackendDAEUtil.setSharedGlobalKnownVars(shared, globalKnownVars);
//BackendDump.dumpEquationArray(currentSystem.orderedEqs,"After_data_RECONCIALTION_EQUATIONS");
//BackendDump.dumpVariables(currentSystem.orderedVars,"After_data_RECONCIALTION_VARIABLES");
BackendDump.dumpEquationList(setC_eq,"SET_C");
BackendDump.dumpEquationList(setS_eq,"SET_S");
VerifyDataReconciliation(tempsetC,tempsetS,knowns,unknowns,mExt,var);
outDae=BackendDAE.DAE({currentSystem}, shared);
print("\n\n ################ END OF EXTRACTION ####################\n\n");
then
outDae;
case(_) then inDae;
end match;
end dataReconciliation;
public function VerifyDataReconciliation
input list<Integer> setc;
input list<Integer> sets;
input list<Integer> knowns;
input list<Integer> unknowns;
input ExtIncidenceMatrix mExt;
input list<tuple<Integer,Integer>> solvedvar;
protected
list<Integer> matchedeq,matchedknownssetc,matchedunknownssetc,matchedknownssets,matchedunknownssets;
list<Integer> tmpunknowns,tmpknowns,tmplist1,tmplist2,tmplist3,tmplist1sets,setstmp;
list<Integer> tmplistvar1,tmplistvar2,tmplistvar3,sets_eqs={};
Integer eqnumber;
String str,resstr;
algorithm
print("\n\nAutomatic Verification Steps of DataReconciliation Algorithm"+ "\n" + UNDERLINE + "\n\n" + "-Known Variables:" + dumplistInteger(knowns) +"\n" + "-SET_C:"+ dumplistInteger(setc)+ "\n" + "-SET_S:" + dumplistInteger(sets) +"\n\n");
//Condition-1
matchedeq:=List.intersectionOnTrue(setc,sets,intEq);
print("Condition-1 " + "\"SET_C and SET_S must not have no equations in common\"" + "\n" + UNDERLINE + "\n");
if(listEmpty(matchedeq)) then
//print("-Passed"+"\n"+"-SET_C:"+ dumplistInteger(setc)+ "\n" + "-SET_S:"+ dumplistInteger(sets) +"\n\n");
print("-Passed\n\n");
else
resstr:=": Condition 1- Failed" + "\n" + "-The following equations are present in both SET_C and SET_S:" + dumplistInteger(matchedeq) + "\n\n";
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
return;
end if;
(matchedknownssetc,matchedunknownssetc):=getVariableOccurence(setc,mExt,knowns);
(matchedknownssets,matchedunknownssets):=getVariableOccurence(sets,mExt,knowns);
// Condition -2
print("Condition-2 " + "\"All variables of interest must be involved in SET_C or SET_S\"" + "\n" +UNDERLINE +"\n");
(tmplist1,tmplist2,tmplist3):=List.intersection1OnTrue(matchedknownssetc,knowns,intEq);
if(listEmpty(tmplist3)) then
print("-Passed"+"\n" + "-SET_C equations contains all variables of interest:" + dumplistInteger(tmplist1)+"\n\n");
elseif(not listEmpty(tmplist3)) then // check in sets
(tmplist1sets,tmplist2,_):=List.intersection1OnTrue(tmplist3,matchedknownssets,intEq);
if(not listEmpty(tmplist2)) then
str:=dumplistInteger(tmplist2);
resstr:=": Condition 2-Failed"+ "\n" + "-the following known variables are not present in both SET_C and SET_S equations:" + str + "\n\n";
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
return;
end if;
print("-Passed" + "\n" + "-SET_C equations contains known variables:" + dumplistInteger(tmplist1) + "\n" +"-SET_S equations contains known variables:" + dumplistInteger(tmplist1sets)+"\n\n");
end if;
//Condition-3
print("Condition-3 " +"\"SET_C equations must be strictly less than Variable of Interest\"" + "\n" + UNDERLINE +"\n");
if(listLength(setc) < listLength(knowns)) then
print("-Passed"+ "\n" + "-SET_C contains:" + intString(listLength(setc)) + " equations < " + intString(listLength(knowns))+" known variables \n\n");
else
resstr:=": Condition 3-Failed"+ "\n" + "-SET_C contains:" + intString(listLength(setc)) + " equations > " + intString(listLength(knowns)) +" known variables \n\n";
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
return;
end if;
//Condition-4
print("Condition-4 " +"\"SET_S should contain all intermediate variables involved in SET_C\"" + "\n" + UNDERLINE +"\n");
(tmplistvar1,tmplistvar2,tmplistvar3):=List.intersection1OnTrue(matchedunknownssetc,matchedunknownssets,intEq);
if(listEmpty(matchedunknownssetc))then
print("-Passed"+"\n"+"-SET_C contains No Intermediate Variables \n\n");
return;
else
print("-SET_C contains "+ "\""+intString(listLength(matchedunknownssetc))+ "\"" +" intermediate variables :"+ dumplistInteger(matchedunknownssetc)+"\n");
if(listEmpty(tmplistvar2)) then
print("-SET_S contains the intermediate variables :"+ dumplistInteger(tmplistvar1)+ " which are involved in SET_C\n"+"-Passed"+ "\n\n");
else
resstr:=": Condition 4-Failed\n" + "SET_S does not contains the intermediate variables :"+ dumplistInteger(tmplistvar2)+ " which are involved in SET_C\n" +"\n\n";
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
return;
end if;
end if;
//Condition-5
print("Condition-5 " +"\"SET_S must compute intermediate variables involved in SET_C\"" + "\n" + UNDERLINE +"\n");
if(listEmpty(sets)) then
print("-Passed"+"\n"+"-SET_S contains 0 intermediate variables and 0 equations \n\n");
return;
end if;
if(not listEmpty(matchedunknownssetc)) then
for i in matchedunknownssetc loop
(eqnumber,_):= getSolvedEquationNumber(i,solvedvar);
sets_eqs:=eqnumber::sets_eqs;
end for;
(tmplist1,tmplist2,tmplist3):=List.intersection1OnTrue(sets_eqs,sets,intEq);
if(listEmpty(tmplist2)) then
print("-Passed\n" +"SET_C contains "+intString(listLength(matchedunknownssetc)) + " intermediate variable:" +
dumplistInteger(matchedunknownssetc) +"\n" +"SET_S contains "+ intString(listLength(tmplist1))+ " equations:" + dumplistInteger(tmplist1) + " which can compute intermediate variables:" + dumplistInteger(tmplistvar1));
else
resstr:=": Condition 5-Failed\n" +"SET_C contains "+intString(listLength(matchedunknownssetc)) + " intermediate variable \n" +"SET_S contains only "+ intString(listLength(tmplist1))+ " equations: " +dumplistInteger(tmplist1) +" which computes intermediate variables: " + dumplistInteger(tmplistvar1) +"\n"+ "SET_S cannot compute intermediate variable :"+
dumplistInteger(tmplistvar2)+"\n\n";
Error.addMessage(Error.INTERNAL_ERROR, {resstr});
end if;
end if;
end VerifyDataReconciliation;
public function dumpListList
input list<list<Integer>> lstLst;
input String heading;
algorithm
print("\n" + heading + ":\n" + UNDERLINE + "\n" +"{"+stringDelimitList(List.map(lstLst,dumplistInteger),",") + "}" +"\n\n");
end dumpListList;
public function dumplistInteger
input list<Integer> inlist;
output String outstring;
protected
list<String> s;
algorithm
s := List.map(inlist, intString);
outstring := stringDelimitList(s, ", ");
outstring := stringAppendList({"{",outstring,"}"});
end dumplistInteger;
public function getVariableOccurence
input list<Integer> setc;
input ExtIncidenceMatrix mext;
input list<Integer> knowns;
output list<Integer> knownvariables={};
output list<Integer> unknownvariables={};
protected
list<Integer> vars;
Integer eq;
algorithm
for i in setc loop
for j in mext loop
(eq,vars):=j;
if(intEq(i,eq)) then
// print("\n Equations matched=>");
// print(anyString(eq));
// print("=>");
// print(anyString(vars));
for var in vars loop
if(listMember(var,knowns)) then
knownvariables:=var::knownvariables;
else
unknownvariables:=var::unknownvariables;
end if;
end for;
end if;
end for;
end for;
knownvariables:=List.unique(knownvariables);
unknownvariables:=List.unique(unknownvariables);
end getVariableOccurence;
public function setInitialBlocks
/* Dictionary to set the Square status of BLT BLocks
At start set all BLT Blocks Square status = true
order of datastructure
1 - BLT BLOCKS
2 - Visited status // may be not needed
3 - square status
*/
input list<list<Integer>> inlist1;
output mapBlocks outlist={};
algorithm
for i in inlist1 loop
outlist:=(i,false,true)::outlist;
end for;
outlist:=listReverse(outlist);
end setInitialBlocks;
public function updateBlocks
/* Function to update the Square Status of BLT Blocks */
input list<Integer> blocktoupdate;
input mapBlocks inlist;
input Boolean visited;
input Boolean square;
output mapBlocks outlist={};
protected
list<Integer> i1;
Boolean b1,b2,b3;
algorithm
for i in inlist loop
(i1,b1,b2):=i;
b3:=List.setEqualOnTrue(i1,blocktoupdate,intEq);
if(b3==true) then
b1:=visited;
b2:=square;
end if;
outlist:=(i1,b1,b2)::outlist;
end for;
outlist:=listReverse(outlist);
end updateBlocks;
public function sortBlocks
input list<Integer> sortedranklist;
input list<tuple<list<Integer>,Integer>> inlist2;
output list<tuple<list<Integer>,Integer>> outlist={};
protected
Integer e1,e2;
list<Integer> blocks;
algorithm
for i in sortedranklist loop
for j in inlist2 loop
(blocks,e1):=j;
if(valueEq(i,e1)) then
outlist:=(blocks,e1)::outlist;
end if;
end for;
end for;
outlist:=listReverse(outlist);
end sortBlocks;
public function findBlocksRanks
input list<tuple<list<Integer>,Integer>> inlist1;
input list<list<Integer>> inlist2;
output list<tuple<list<Integer>,Integer>> outlist={};
output list<Integer> ranklist={};
protected
list<Integer> blocks;
Integer rank;
algorithm
for i in inlist2 loop
for j in inlist1 loop
(blocks,rank):=j;
if(valueEq(i,blocks)) then
outlist:=(i,rank)::outlist;
ranklist:=rank::ranklist;
end if;
end for;
end for;
outlist:=listReverse(outlist);
ranklist:=List.sort(ranklist,intGt);
end findBlocksRanks;
public function findBlockTargets
/* Function which finds the Target blocks for each BLT blocks */
input list<list<Integer>> inlist1;
input list<list<String>> inlist2;
input list<tuple<Integer,Integer>> solvedvariables;
input ExtIncidenceMatrix mxt;
input mapBlocks map;
input list<tuple<list<Integer>,Integer>> blockranks;
output list<tuple<list<Integer>,list<tuple<list<Integer>,Integer>>,list<tuple<list<String>,Integer>>>> outlist={};
protected
list<list<Integer>> targetblocks;
list<tuple<list<String>,Integer>> targetvarlist;
list<String> blockvarlst;
list<Integer> ranklist,blocks1;
Integer rank;
list<tuple<list<Integer>,Integer>> updatedblocks;
algorithm
for i in inlist1 loop
targetblocks:=findBlockTargetsHelper({i},inlist2,solvedvariables,mxt,map,inlist1);
targetblocks:=listAppend({i},targetblocks);
(updatedblocks,ranklist):=findBlocksRanks(blockranks,targetblocks);
updatedblocks:=sortBlocks(ranklist,updatedblocks);
// print("\n TARGET BLOCKS ===>");
// print(anyString(i));
// print("=>");
// print(anyString(updatedblocks));
targetvarlist:={};
for blocks in updatedblocks loop
(blocks1,rank):=blocks;
blockvarlst:=getBlockVarList(blocks1,inlist1,inlist2);
targetvarlist:=(blockvarlst,rank)::targetvarlist;
end for;
//print("=>");
//print(anyString(listReverse(targetvarlist)));
outlist:=(i,updatedblocks,listReverse(targetvarlist))::outlist;
end for;
outlist:=listReverse(outlist);
end findBlockTargets;
public function findBlockTargetsHelper
/* Recursive Function which finds the Target blocks for each BLT blocks */
input list<list<Integer>> inlist1;
input list<list<String>> inlist2;
input list<tuple<Integer,Integer>> solvedvariables;
input ExtIncidenceMatrix mxt;
input mapBlocks map;
input list<list<Integer>> actualblocks;
output list<list<Integer>> outlist={};
algorithm
outlist:=match(inlist1,inlist2,solvedvariables,mxt,map,actualblocks)
local
list<Integer> first,dependencyequation,targetblockslist;
list<list<Integer>> rest, targetblocks,targetblocks1,originalblocks;
list<list<String>> restitem;
list<String> firstitem;
list<tuple<Integer,Integer>> solvar;
ExtIncidenceMatrix mxt1;
mapBlocks map1;
case(first::rest,firstitem::restitem,solvar,mxt1,map1,originalblocks)
equation
dependencyequation=findBlockTargetsHelper1((first::rest),solvar,mxt1);
targetblocks=getActualBlocks(dependencyequation,originalblocks,first);
targetblocks1=findBlockTargetsHelper(targetblocks,firstitem::restitem,solvar,mxt1,map1,originalblocks);
then
(List.unique(listAppend(targetblocks,targetblocks1)));
case(_,_,_,_,_,_) then {};
end match;
end findBlockTargetsHelper;
public function findBlockTargetsHelper1
input list<list<Integer>> inlist;
input list<tuple<Integer,Integer>> solvedvariables;
input ExtIncidenceMatrix mxt;
output list<Integer> outlist={};
protected
list<Integer> dependencyequations;
algorithm
for i in inlist loop
dependencyequations:=getDependencyequation(i,{},solvedvariables,mxt);
for v in listReverse(dependencyequations) loop
outlist:=v::outlist;
end for;
end for;
end findBlockTargetsHelper1;
public function findSquareAndNonSquareBlocks
/*
Step-3 of DataReconciliation Algorithm
This function provides the square status of the BLT Blocks
*/
input list<tuple<list<Integer>,list<tuple<list<Integer>,Integer>>,list<tuple<list<String>,Integer>>>> blockinfo;
input list<tuple<Integer,Integer>> solvedvariables;
input ExtIncidenceMatrix mxt;
input mapBlocks map;
output list<Boolean> outlist={};
output list<tuple<list<Integer>,list<String>,Boolean,Integer,Boolean>> outlist2={};
protected
list<Integer> dependencyequation;
list<tuple<list<Integer>,Integer>> blockstoupdate,targetblocks;
list<tuple<list<String>,Integer>> targetblocksvar;
list<Integer> blockitem,blockitems1,blockitems2;
list<String> blockvarlst,blockvarlst1,blockvarlst2;
Integer foundblock,count=1,foundblockrank;
mapBlocks map1=map;
Boolean visited,square,status,checkknowns,finalsquarestauts,exist,exist1;
list<tuple<list<Integer>,list<String>,Boolean,Integer>> outlist1={};
algorithm
for blocks in blockinfo loop
(blockitems1,targetblocks,targetblocksvar):= blocks;
(blockstoupdate,exist,foundblock):=findSquareAndNonSquareBlocksHelper(targetblocks,targetblocksvar);
(blockvarlst1,_):=List.first(targetblocksvar);
outlist1:=(blockitems1,blockvarlst1,exist,foundblock)::outlist1;
for j in blockstoupdate loop
(blockitem,_):=j;
visited:=false;
map1:=updateBlocks(blockitem,map1,visited,false);
end for;
end for;
//print("\n AFTER NEW SQUARE TRAVERSAL =====>");
for k in map1 loop
(_,_,finalsquarestauts):=k;
(blockitems1,blockvarlst2,exist1,foundblockrank):=listGet(listReverse(outlist1),count);
outlist:=finalsquarestauts::outlist;
outlist2:=(blockitems1,blockvarlst2,exist1,foundblockrank,finalsquarestauts)::outlist2;
count:=count+1;
end for;
outlist:=listReverse(outlist);
outlist2:=listReverse(outlist2);
end findSquareAndNonSquareBlocks;
public function findSquareAndNonSquareBlocksHelper
input list<tuple<list<Integer>,Integer>> inlist1;
input list<tuple<list<String>,Integer>> inlist2;
output list<tuple<list<Integer>,Integer>> targetblocks={};
output Boolean exists=false;
output Integer foundblock=-1;
protected
Boolean checkknowns;
list<String> blocksvarlist;
Integer count=1,rank;
list<tuple<list<Integer>,Integer>> targetblockstest={};
algorithm
for i in inlist2 loop
(blocksvarlist,rank):=i;
checkknowns:=listMember("knowns",blocksvarlist);
if(checkknowns==true) then
/* Extract Blocks After the first known blocks to update the square status of these blocks to false */
targetblocks:=List.lastN(inlist1,(listLength(inlist1)-count));
foundblock:=rank;
exists:=true;
break;
end if;
count:=count+1;
end for;
end findSquareAndNonSquareBlocksHelper;
public function getBlockVarList
input list<Integer> blocktofind;
input list<list<Integer>> inlist1;
input list<list<String>> inlist2;
output list<String> outstringlist={};
protected
Integer count=1;
Boolean b3;
algorithm
for i in inlist1 loop
b3:=List.setEqualOnTrue(i,blocktofind,intEq);
if(b3==true) then
outstringlist:=listGet(inlist2,count);
end if;
count:=count+1;
end for;
end getBlockVarList;
public function getActualBlocks
input list<Integer> searchblock;
input list<list<Integer>> inlist1;
input list<Integer> inlist2;
output list<list<Integer>> outlist={};
algorithm
for i in inlist1 loop
if(not listEmpty(List.intersectionOnTrue(searchblock,i,intEq))) then
outlist:=i::outlist;
end if;
end for;
//outlist:=listReverse(listAppend(outlist,{inlist2}));
outlist:=listReverse(outlist);
end getActualBlocks;
public function ExtractEquationsfromBlocks
/*
order of dataStructure of blockdata
list<Integer> - Blocks -> {1,2}
list<String> - Blocksvarlist ->{knowns,unknowns}
Boolean - BlockExistorNot
Integer - BlockRank
Boolean - BlockSquareStatus
*/
input list<tuple<list<Integer>,list<String>,Boolean,Integer,Boolean>> blockdata;
input list<Integer> approximatedEquation;
output list<Integer> setc={};
output list<Integer> sets={};
output list<Integer> removedeq={};
protected
list<Integer> blockitem,blockitem1,setc1,sets1,temp1,temp2,rmeqlist,tmplist1,tmplist2,tmplist3;
list<list<Integer>> usedblocklist={};
list<String> blockvarlist;
Boolean blockexist,squarestatus,used=false,checkusedblock,targetBlockSquareStatus;
Integer blockrank,knownvarcount,blocksize;
algorithm
for i in blockdata loop
(blockitem,blockvarlist,blockexist,blockrank,squarestatus):=i;
if (blockexist==true and squarestatus==true) then
/*
EXISTING BLOCKS with squarestatus True
Input Blocks Insert equations in setc
*/
(blockitem1,_,_,_,targetBlockSquareStatus):=listGet(blockdata,blockrank);
checkusedblock:=listMember(blockitem1,usedblocklist);
if(not List.setEqualOnTrue(blockitem,blockitem1,intEq)) then
/*
EXISTING NON-EQUAL BLOCKS with Target blocks different
eg: B1={B1,B2,B3}
where B1=>B3(B1 depends on B3) which contains variable of interest
*/
if (targetBlockSquareStatus==true and checkusedblock==false) then
temp1:=List.lastN(blockitem,(listLength(blockitem)-1));
if(listEmpty(temp1)) then
removedeq:=listAppend(blockitem,removedeq);
end if;
sets:=listAppend(temp1,sets);
//add one equation of found block into sets
sets:=listAppend(List.firstOrEmpty(blockitem1),sets);
usedblocklist:=blockitem1::usedblocklist;
elseif (targetBlockSquareStatus==false or checkusedblock==true) then
sets:=listAppend(blockitem,sets);
end if;
else
/*
EXISTING EQUAL BLOCKS with Target blocks same
eg: B1={B1,B2,B3}
where B1=>B1(B1 depends on B1) which contains variable of interest
insert equations in setc and sets
*/
(setc1,sets1):=extractMixedBlock(blockitem,blockvarlist);
// put the approximated equations front if present
(tmplist1,tmplist2,tmplist3):=List.intersection1OnTrue(setc1,approximatedEquation,intEq);
setc1:=listAppend(tmplist1,tmplist2);
setc:=listAppend(List.restOrEmpty(setc1),setc);
sets:=listAppend(sets,sets1);
removedeq:=listAppend(List.firstOrEmpty(setc1),removedeq);
end if;
elseif (blockexist==true and squarestatus==false) then
/*
EXISTING BLOCKS with squarestatus False
insert equations into setc and sets
*/
(setc1,sets1):=extractMixedBlock(blockitem,blockvarlist);
sets:=listAppend(sets,sets1);
setc:=listAppend(setc,setc1);
else
/*
NON EXISTING BLOCKS,Blocks to be removed
Eg: B1:={B1,B2,B3}
where B1,B2,B3 does not contain known variables
*/
removedeq:=listAppend(blockitem,removedeq);
end if;
end for;
setc:=List.unique(setc);
sets:=List.unique(sets);
removedeq:=List.unique(removedeq);
end ExtractEquationsfromBlocks;
public function getRemovedEquationSolvedVariables
input list<Integer> inlist;
input list<tuple<Integer,Integer>> solvedvar;
output list<Integer> outvarlist={};
protected
Integer eqnumber,varnumber;
algorithm
for i in inlist loop
(_,varnumber):=getSolvedVariableNumber(i,solvedvar);
outvarlist:=varnumber::outvarlist;
end for;
end getRemovedEquationSolvedVariables;
public function countKnownVariables
input list<String> inlist1;
output Integer count=0;
protected
Boolean value;
algorithm
for i in inlist1 loop
if(valueEq(i,"knowns")) then
count:=count+1;
end if;
end for;
end countKnownVariables;
public function checkBlockStatus
input list<list<Integer>> inlist1;
input list<list<String>> inlist2;
output list<list<String>> instringlist={};
protected
Integer count=0;
Boolean b1,b2,b3,setinputs=true,setinputs1=true;
algorithm
for i in inlist2 loop
b1:=listMember("knowns",i);
b2:=listMember("unknowns",i);
b3:=listMember("inputs",i);
if(setinputs==true and b2==true and b1==false) then
i:=List.fill("inputs",listLength(i));
end if;
if(b1==true and b2==false) then
setinputs:=false;
end if;
if(b1==true and b2==true) then
setinputs:=false;
end if;
instringlist:=i::instringlist;
count:=count+1;
end for;
instringlist:=listReverse(instringlist);
end checkBlockStatus;
public function originalBlocks
input list<list<Integer>> inlist;
input list<Integer> knowns;
input list<Integer> unknowns;
input list<Integer> outputs;
input list<tuple<Integer,Integer>> solvedvariables;
output list<list<Integer>> outlist={};
output list<list<String>> outstringlist={};
protected