/
Tearing.mo
4434 lines (3905 loc) · 177 KB
/
Tearing.mo
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 Tearing
" file: Tearing.mo
package: Tearing
description: Tearing contains functions used for tear strong connected components.
Implemented Methods are:
- omc tearing developed by TU Dresden: Frenkel,Schubert
- Cellier Tearing"
public import BackendDAE;
public import DAE;
protected import Array;
protected import BackendDAEEXT;
protected import BackendDAEOptimize;
protected import BackendDAEUtil;
protected import BackendDump;
protected import BackendEquation;
protected import BackendVariable;
protected import Config;
protected import DoubleEndedList;
protected import DumpGraphML;
protected import ElementSource;
protected import Error;
protected import ExecStat.execStat;
protected import Expression;
protected import ExpressionDump;
protected import ExpressionSimplify;
protected import ExpressionSolve;
protected import Flags;
protected import List;
protected import Matching;
protected import MetaModelica.Dangerous;
protected import Util;
protected import Sorting;
// =============================================================================
// section for type definitions
//
//
// =============================================================================
protected constant String BORDER = "****************************************";
protected constant String UNDERLINE = "========================================";
uniontype TearingMethod
record OMC_TEARING end OMC_TEARING;
record CELLIER_TEARING end CELLIER_TEARING;
record TOTAL_TEARING end TOTAL_TEARING;
end TearingMethod;
// =============================================================================
// section for all public functions
//
// main function to divide to the selected tearing method
// =============================================================================
public function tearingSystem "author: Frenkel TUD 2012-05"
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
outDAE := matchcontinue(inDAE)
local
String methodString;
TearingMethod method;
BackendDAE.BackendDAEType DAEtype;
// if noTearing is selected, do nothing.
case(_) equation
methodString = Config.getTearingMethod();
true = stringEqual(methodString, "noTearing");
then inDAE;
// get method function and traverse systems
case(_) equation
methodString = Config.getTearingMethod();
BackendDAE.SHARED(backendDAEType=DAEtype) = inDAE.shared;
false = stringEqual(methodString, "shuffleTearing") and stringEq("simulation",BackendDump.printBackendDAEType2String(DAEtype));
method = getTearingMethod(methodString);
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n\n\n\n" + UNDERLINE + UNDERLINE + "\nCalling Tearing for ");
BackendDump.printBackendDAEType(DAEtype);
print("!\n" + UNDERLINE + UNDERLINE + "\n");
end if;
(outDAE, _) = BackendDAEUtil.mapEqSystemAndFold(inDAE, tearingSystemWork, method);
then outDAE;
else equation
Error.addInternalError("./Compiler/BackEnd/Tearing.mo: function tearingSystem failed", sourceInfo());
then fail();
end matchcontinue;
end tearingSystem;
// =============================================================================
// protected
//
//
// =============================================================================
protected function getTearingMethod
input String inTearingMethod;
output TearingMethod outTearingMethod;
algorithm
outTearingMethod := match(inTearingMethod)
case ("omcTearing") then OMC_TEARING();
case ("cellier") then CELLIER_TEARING();
case ("totalTearing") then TOTAL_TEARING();
else equation
Error.addInternalError("./Compiler/BackEnd/Tearing.mo: function getTearingMethod failed", sourceInfo());
then fail();
end match;
end getTearingMethod;
protected function callTearingMethod
input TearingMethod inTearingMethod;
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input list<Integer> eindex;
input list<Integer> vindx;
input Option<list<tuple<Integer, Integer, BackendDAE.Equation>>> ojac;
input BackendDAE.JacobianType jacType;
input Boolean mixedSystem;
output BackendDAE.StrongComponent ocomp;
output Boolean outRunMatching;
protected
protected constant Boolean debug = false;
algorithm
(ocomp, outRunMatching) := match inTearingMethod
case OMC_TEARING()
algorithm
(ocomp,outRunMatching) := omcTearing(isyst, ishared, eindex, vindx, ojac, jacType, mixedSystem);
if debug then execStat("Tearing.omcTearing"); end if;
then (ocomp,outRunMatching);
case CELLIER_TEARING()
algorithm
(ocomp,outRunMatching) := CellierTearing(isyst, ishared, eindex, vindx, ojac, jacType, mixedSystem);
if debug then execStat("Tearing.CellierTearing"); end if;
then (ocomp,outRunMatching);
case TOTAL_TEARING()
algorithm
(ocomp,outRunMatching) := totalTearing(isyst, ishared, eindex, vindx, ojac, jacType, mixedSystem);
if debug then execStat("Tearing.totalTearing"); end if;
then (ocomp,outRunMatching);
end match;
end callTearingMethod;
protected function tearingSystemWork "author: Frenkel TUD 2012-05"
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared inShared;
input TearingMethod inTearingMethod;
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared outShared = inShared "unused";
output TearingMethod outTearingMethod = inTearingMethod "unused";
protected
BackendDAE.StrongComponents comps;
Boolean b;
array<Integer> ass1, ass2;
algorithm
BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(ass1=ass1, ass2=ass2, comps=comps)):=isyst;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n" + BORDER + "\nBEGINNING of traverseComponents\n\n");
end if;
(comps, b) := traverseComponents(comps, isyst, inShared, inTearingMethod);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nEND of traverseComponents\n" + BORDER + "\n\n");
end if;
osyst := if b then BackendDAEUtil.setEqSystMatching(isyst, BackendDAE.MATCHING(ass1, ass2, comps)) else isyst;
end tearingSystemWork;
protected function traverseComponents "author: Frenkel TUD 2012-05"
input BackendDAE.StrongComponents inComps;
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input TearingMethod inMethod;
output BackendDAE.StrongComponents oComps;
output Boolean outRunMatching = false;
algorithm
oComps := list(match co
local
BackendDAE.StrongComponent comp;
Boolean b;
case comp
equation
(comp, b) = traverseComponents1(comp, isyst, ishared, inMethod);
outRunMatching = outRunMatching or b;
then comp;
end match for co in inComps);
end traverseComponents;
protected function traverseComponents1 "author: Frenkel TUD 2012-05"
input BackendDAE.StrongComponent inComp;
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input TearingMethod inMethod;
output BackendDAE.StrongComponent oComp;
output Boolean outRunMatching;
protected
constant Boolean debug = false;
algorithm
(oComp, outRunMatching) := matchcontinue (inComp, isyst, ishared, inMethod)
local
Integer maxSize;
list<Integer> eindex, vindx;
Boolean b, b1;
BackendDAE.StrongComponents comps, acc;
BackendDAE.StrongComponent comp, comp1;
Option<list<tuple<Integer, Integer, BackendDAE.Equation>>> ojac;
BackendDAE.JacobianType jacType;
Boolean mixedSystem;
case ((BackendDAE.EQUATIONSYSTEM(eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(ojac), jacType=jacType, mixedSystem=mixedSystem)), _, _, _) equation
equality(jacType = BackendDAE.JAC_LINEAR());
maxSize = Flags.getConfigInt(Flags.MAX_SIZE_LINEAR_TEARING);
if intGt(listLength(vindx),maxSize) then
Error.addMessage(Error.MAX_TEARING_SIZE, {intString(listLength(vindx)),"Linear",intString(maxSize)});
fail();
end if;
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nCase linear in traverseComponents\nUse Flag '+d=tearingdumpV' for more details\n\n");
end if;
false = Flags.getConfigBool(Flags.DISABLE_LINEAR_TEARING);
// TODO: Remove when cpp runtime ready for doLinearTearing
//false = stringEqual(Config.simCodeTarget(), "Cpp");
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Flag 'doLinearTearing' is set\n\n");
end if;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Jacobian:\n" + BackendDump.dumpJacobianStr(ojac) + "\n\n");
end if;
if debug then execStat("Tearing.traverseComponents1 linear start"); end if;
(comp1, true) = callTearingMethod(inMethod, isyst, ishared, eindex, vindx, ojac, jacType, mixedSystem);
then (comp1, true);
// tearing of non-linear systems
case ((BackendDAE.EQUATIONSYSTEM(eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(ojac), jacType=jacType, mixedSystem=mixedSystem)), _, _, _) equation
failure(equality(jacType = BackendDAE.JAC_LINEAR()));
maxSize = Flags.getConfigInt(Flags.MAX_SIZE_NONLINEAR_TEARING);
if intGt(listLength(vindx),maxSize) then
Error.addMessage(Error.MAX_TEARING_SIZE, {intString(listLength(vindx)),"Nonlinear",intString(maxSize)});
fail();
end if;
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nCase non-linear in traverseComponents\nUse Flag '+d=tearingdumpV' for more details\n\n");
end if;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Jacobian:\n" + BackendDump.dumpJacobianStr(ojac) + "\n\n");
end if;
if debug then execStat("Tearing.traverseComponents1 NLS start"); end if;
(comp1, true) = callTearingMethod(inMethod, isyst, ishared, eindex, vindx, ojac, jacType, mixedSystem);
then (comp1, true);
// no component for tearing
else (inComp, false);
end matchcontinue;
end traverseComponents1;
// =============================================================================
//
// method: omc tearing
//
// =============================================================================
protected function omcTearing " author: Frenkel TUD 2012-05"
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input list<Integer> eindex;
input list<Integer> vindx;
input Option<list<tuple<Integer, Integer, BackendDAE.Equation>>> ojac;
input BackendDAE.JacobianType jacType;
input Boolean mixedSystem;
output BackendDAE.StrongComponent ocomp;
output Boolean outRunMatching;
protected
list<Integer> tvars,residual,unsolvables;
list<list<Integer>> othercomps;
BackendDAE.EqSystem syst,subsyst;
BackendDAE.Shared shared;
array<Integer> ass1,ass2,ass22,columark;
Integer size,tornsize,mark;
list<BackendDAE.Equation> eqn_lst;
list<BackendDAE.Var> var_lst;
BackendDAE.Variables vars;
BackendDAE.EquationArray eqns;
BackendDAE.IncidenceMatrix m,m1;
BackendDAE.IncidenceMatrix mt,mt1,mt11;
BackendDAE.AdjacencyMatrixEnhanced me;
BackendDAE.AdjacencyMatrixTEnhanced meT;
array<list<Integer>> mapEqnIncRow;
array<Integer> mapIncRowEqn;
DAE.FunctionTree funcs;
list<Integer> asslst1, asslst2;
list<Integer> tSel_always, tSel_prefer, tSel_avoid, tSel_never;
algorithm
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n" + BORDER + "\nBEGINNING of omcTearing\n\n");
end if;
// generate Subsystem to get the incidence matrix
size := listLength(vindx);
eqn_lst := BackendEquation.getEqns(eindex,BackendEquation.getEqnsFromEqSystem(isyst));
eqns := BackendEquation.listEquation(eqn_lst);
var_lst := List.map1r(vindx, BackendVariable.getVarAt, BackendVariable.daeVars(isyst));
vars := BackendVariable.listVar1(var_lst);
subsyst := BackendDAEUtil.createEqSystem(vars, eqns);
funcs := BackendDAEUtil.getFunctions(ishared);
(subsyst,m,mt,_,_) := BackendDAEUtil.getIncidenceMatrixScalar(subsyst, BackendDAE.NORMAL(), SOME(funcs));
// DumpGraphML.dumpSystem(subsyst,ishared,NONE(),"System" + intString(size) + ".graphml");
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n\n###BEGIN print Strong Component#####################\n(Function:omcTearing)\n");
BackendDump.printEqSystem(subsyst);
print("\n###END print Strong Component#######################\n(Function:omcTearing)\n\n\n");
end if;
(me,meT,mapEqnIncRow,mapIncRowEqn) := BackendDAEUtil.getAdjacencyMatrixEnhancedScalar(subsyst,ishared,false);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n\nAdjacencyMatrixEnhanced:\n");
BackendDump.dumpAdjacencyMatrixEnhanced(me);
print("\nAdjacencyMatrixTransposedEnhanced:\n");
BackendDump.dumpAdjacencyMatrixTEnhanced(meT);
print("\nmapEqnIncRow:"); //+ stringDelimitList(List.map(List.flatten(arrayList(mapEqnIncRow)),intString),",") + "\n\n");
BackendDump.dumpIncidenceMatrix(mapEqnIncRow);
print("\nmapIncRowEqn:\n" + stringDelimitList(List.map(arrayList(mapIncRowEqn),intString),",") + "\n\n");
end if;
ass1 := arrayCreate(size,-1);
ass2 := arrayCreate(size,-1);
// get all unsolvable variables
unsolvables := getUnsolvableVars(1,size,meT,{});
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n\nUnsolvable Vars:\n");
BackendDump.debuglst(unsolvables,intString,", ","\n");
end if;
columark := arrayCreate(size,-1);
// Collect variables with annotation attribute 'tearingSelect=always', 'tearingSelect=prefer', 'tearingSelect=avoid' and 'tearingSelect=never'
(tSel_always,tSel_prefer,tSel_avoid,tSel_never) := tearingSelect(var_lst);
// determine tvars and do cheap matching until a maximum matching is there
// if cheap matching stucks select additional tearing variable and continue
// (mark+1 for every call of omcTearing3)
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n" + BORDER + "\nBEGINNING of omcTearing2\n\n");
end if;
(tvars,mark) := omcTearing2(unsolvables,tSel_always,tSel_prefer,tSel_avoid,tSel_never,me,meT,mapEqnIncRow,mapIncRowEqn,size,vars,ishared,ass1,ass2,columark,1,{});
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nEND of omcTearing2\n" + BORDER + "\n\n");
end if;
// unassign tvars
ass1 := List.fold(tvars,unassignTVars,ass1);
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n" + BORDER + "\n* BFS RESULTS:\n* ass1: "+ stringDelimitList(List.map(arrayList(ass1),intString),",") +"\n");
print("* ass2: "+ stringDelimitList(List.map(arrayList(ass2),intString),",") + "\n" + BORDER +"\n\n");
end if;
// unmatched equations are residual equations
residual := Matching.getUnassigned(size,ass2,{});
// subsyst := BackendDAEUtil.setEqSystMatching(subsyst,BackendDAE.MATCHING(ass1,ass2,{}));
// DumpGraphML.dumpSystem(subsyst,ishared,NONE(),"TornSystem" + intString(size) + ".graphml");
// check if tearing makes sense
tornsize := listLength(tvars);
true := intLt(tornsize, size);
// create incidence matrices w/o tvar and residual
m1 := arrayCreate(size,{});
mt1 := arrayCreate(size,{});
m1 := getOtherEqSysIncidenceMatrix(m,size,1,ass2,ass1,m1);
mt1 := getOtherEqSysIncidenceMatrix(mt,size,1,ass1,ass2,mt1);
// run tarjan to get order of other equations
othercomps := Sorting.TarjanTransposed(mt1, ass2);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nOtherEquationsOrder:\n");
BackendDump.dumpComponentsOLD(othercomps);
print("\n");
end if;
// calculate influence of tearing vars in residual equations
// mt1: row=variable, columns: tvars, that influence the result of the variable
mt1 := arrayCreate(size, {});
mark := getDependenciesOfVars(othercomps, ass1, ass2, m, mt1, columark, mark);
(residual, mark) := sortResidualDepentOnTVars(residual, tvars, ass1, m, mt1, columark, mark);
(ocomp,outRunMatching) := omcTearing4(jacType,isyst,ishared,subsyst,tvars,residual,ass1,ass2,othercomps,eindex,vindx,mapEqnIncRow,mapIncRowEqn,columark,mark,mixedSystem);
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print(if outRunMatching then "\nStatus:\nOk system torn\n\n" else "\nStatus:\nSystem not torn\n\n");
print("\n" + BORDER + "\n* TEARING RESULTS:\n*\n* No of equations in strong component: "+intString(size)+"\n");
print("* No of tVars: "+intString(tornsize)+"\n");
print("*\n* tVars: "+ stringDelimitList(List.map(tvars,intString),",") + "\n");
print("*\n* resEq: "+ stringDelimitList(List.map(residual,intString),",") + "\n*\n*");
BackendDAE.TORNSYSTEM(BackendDAE.TEARINGSET(tearingvars=tvars,residualequations=residual)) := ocomp;
print("\n* Related to entire Equationsystem:\n* =====\n* tVars: "+ stringDelimitList(List.map(tvars,intString),",") + "\n* =====\n");
print("*\n* =====\n* resEq: "+ stringDelimitList(List.map(residual,intString),",") + "\n* =====\n" + BORDER + "\n");
end if;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n\nStrongComponents:\n");
BackendDump.dumpComponent(ocomp);
print("\n\nEND of omcTearing\n" + BORDER + "\n\n");
end if;
end omcTearing;
protected function getUnsolvableVars
" author: Frenkel TUD 2012-08"
input Integer index;
input Integer size;
input BackendDAE.AdjacencyMatrixTEnhanced meT;
input list<Integer> iAcc;
output list<Integer> oAcc;
algorithm
oAcc := matchcontinue(index,size,meT,iAcc)
local
BackendDAE.AdjacencyMatrixElementEnhanced elem;
list<Integer> acc;
Boolean b;
case(_,_,_,_)
equation
true = intLe(index,size);
elem = meT[index];
b = unsolvable(elem);
acc = List.consOnTrue(b, index, iAcc);
then
getUnsolvableVars(index+1,size,meT,acc);
case(_,_,_,_)
then
iAcc;
end matchcontinue;
end getUnsolvableVars;
public function unsolvable
" author: Frenkel TUD 2012-08"
input BackendDAE.AdjacencyMatrixElementEnhanced elem;
output Boolean b = true;
protected
Integer e;
BackendDAE.Solvability s;
algorithm
for el in elem loop
(e,s,_) := el;
if solvable(s) then
if e > 0 then
b := false;
return;
end if;
end if;
end for;
end unsolvable;
protected function unassignTVars " author: Frenkel TUD 2012-05"
input Integer v;
input array<Integer> inAss;
output array<Integer> outAss;
algorithm
outAss := arrayUpdate(inAss,v,-1);
end unassignTVars;
protected function isAssigned " author: Frenkel TUD 2012-05"
input array<Integer> ass;
input Integer i;
output Boolean b;
algorithm
b := intGt(ass[i],0);
end isAssigned;
protected function getOtherEqSysIncidenceMatrix " function to remove tvar and res from incidence matrix
author: Frenkel TUD 2012-05"
input BackendDAE.IncidenceMatrix m;
input Integer size;
input Integer index;
input array<Integer> skip;
input array<Integer> rowskip;
input BackendDAE.IncidenceMatrix mnew;
output BackendDAE.IncidenceMatrix outMNew;
algorithm
outMNew := matchcontinue(m,size,index,skip,rowskip,mnew)
local
list<Integer> row;
case (_,_,_,_,_,_)
equation
true = intGt(index,size);
then
mnew;
case (_,_,_,_,_,_)
equation
true = intGt(skip[index],0);
row = List.select(m[index], Util.intPositive);
row = List.select1r(row,isAssigned,rowskip);
arrayUpdate(mnew,index,row);
then
getOtherEqSysIncidenceMatrix(m,size,index+1,skip,rowskip,mnew);
case (_,_,_,_,_,_)
equation
arrayUpdate(mnew,index,{});
then
getOtherEqSysIncidenceMatrix(m,size,index+1,skip,rowskip,mnew);
end matchcontinue;
end getOtherEqSysIncidenceMatrix;
protected function getDependenciesOfVars " function to determine which variables are influenced by the tvars"
input list<list<Integer>> iComps;
input array<Integer> ass1;
input array<Integer> ass2;
input BackendDAE.IncidenceMatrix m;
input array<list<Integer>> mT;
input array<Integer> visited;
input Integer iMark;
output Integer oMark;
algorithm
oMark := match(iComps, ass1, ass2, m, mT, visited, iMark)
local
Integer c, v;
list<Integer> comp, tvars, vars;
list<list<Integer>> comps;
case ({}, _, _, _, _, _, _)
then iMark;
case ({c}::comps, _, _, _, _, _, _) equation
// get var of eqn
v = ass2[c];
// get TVars of Eqn
vars = List.select(m[c], Util.intPositive);
tvars = tVarsofEqn(vars, ass1, mT, visited, iMark, {});
// update map
arrayUpdate(mT, v, tvars);
then getDependenciesOfVars(comps, ass1, ass2, m, mT, visited, iMark+1);
case (comp::comps, _, _, _, _, _, _) equation
// get var of eqns
vars = List.map1r(comp,arrayGet,ass2);
// get TVars of Eqns
tvars = tVarsofEqns(comp, m, ass1, mT, visited, iMark);
// update map
_ = List.fold1r(vars, arrayUpdate, tvars, mT);
then getDependenciesOfVars(comps, ass1, ass2, m, mT, visited, iMark+1);
end match;
end getDependenciesOfVars;
protected function tVarsofEqns "determines tvars that influence this equations"
input list<Integer> iEqns;
input BackendDAE.IncidenceMatrix m;
input array<Integer> ass1;
input array<list<Integer>> mT;
input array<Integer> visited;
input Integer iMark;
output list<Integer> oAcc = {};
protected
list<Integer> vars;
algorithm
for e in iEqns loop
vars := List.select(m[e], Util.intPositive);
oAcc := tVarsofEqn(vars, ass1, mT, visited, iMark, oAcc);
end for;
end tVarsofEqns;
protected function tVarsofEqn "determines tvars that influence this equation"
input list<Integer> iVars;
input array<Integer> ass1;
input array<list<Integer>> mT;
input array<Integer> visited;
input Integer iMark;
input list<Integer> iAcc;
output list<Integer> oAcc = iAcc;
algorithm
for v in iVars loop
if intLt(ass1[v],0) then
oAcc := uniqueIntLst(v,iMark,visited,oAcc);
else
oAcc := List.fold2(mT[v],uniqueIntLst,iMark,visited,oAcc);
end if;
end for;
end tVarsofEqn;
protected function uniqueIntLst
input Integer c;
input Integer mark;
input array<Integer> markarray;
input list<Integer> iAcc;
output list<Integer> oAcc = iAcc;
algorithm
if not intEq(mark,markarray[c]) then
arrayUpdate(markarray,c,mark);
oAcc := c::oAcc;
end if;
end uniqueIntLst;
protected function sortResidualDepentOnTVars
input list<Integer> iResiduals;
input list<Integer> iTVars;
input array<Integer> ass1;
input BackendDAE.IncidenceMatrix m;
input array<list<Integer>> mT;
input array<Integer> visited;
input Integer iMark;
output list<Integer> oResiduals;
output Integer oMark;
protected
Integer size;
list<list<Integer>> maplst;
array<list<Integer>> map;
array<Integer> eqnLocalGlobal,varGlobalLocal,v1,v2;
algorithm
// eqn - local - Global indices
eqnLocalGlobal := listArray(iResiduals);
// var - global local indices
varGlobalLocal := arrayCreate(arrayLength(m),-1);
varGlobalLocal := getGlobalLocal(iTVars,1,varGlobalLocal);
// generate list of map[residual]=tvars
// change indices in map to local
(oMark,maplst) := tVarsofResidualEqns(iResiduals,m,ass1,mT,varGlobalLocal,visited,iMark);
map := listArray(maplst);
// get for each residual a tvar
size := arrayLength(map);
Matching.matchingExternalsetIncidenceMatrix(size,size,map);
BackendDAEEXT.matching(size,size,5,-1,1.0,1);
v1 := arrayCreate(size,-1);
v2 := arrayCreate(size,-1);
BackendDAEEXT.getAssignment(v2,v1);
// BackendDump.dumpIncidenceMatrix(map);
// BackendDump.dumpMatching(v1);
// BackendDump.dumpMatching(v2);
// sort residuals depent on matching to tvars
oResiduals := getTVarResiduals(size,v1,eqnLocalGlobal,{});
//print("iResiduals " + stringDelimitList(List.map(iResiduals,intString),",") + "\n");
//print("oResiduals " + stringDelimitList(List.map(oResiduals,intString),",") + "\n");
end sortResidualDepentOnTVars;
protected function getGlobalLocal
input list<Integer> iTVars;
input Integer index;
input array<Integer> iVarGlobalLocal;
output array<Integer> oVarGlobalLocal = iVarGlobalLocal;
protected
Integer idx = index;
algorithm
for i in iTVars loop
arrayUpdate(oVarGlobalLocal,i,idx);
idx := idx + 1;
end for;
end getGlobalLocal;
protected function tVarsofResidualEqns
input list<Integer> iEqns;
input BackendDAE.IncidenceMatrix m;
input array<Integer> ass1;
input array<list<Integer>> mT;
input array<Integer> varGlobalLocal;
input array<Integer> visited;
input Integer iMark;
output Integer oMark = iMark;
output list<list<Integer>> oAcc;
algorithm
oAcc := list(
match eq
local
Integer e;
list<Integer> eqns,vars,tvars;
case e
equation
vars = List.select(m[e], Util.intPositive);
tvars = tVarsofEqn(vars,ass1,mT,visited,oMark,{});
// change indices to local
tvars = List.map1r(tvars,arrayGet,varGlobalLocal);
oMark = oMark + 1;
then tvars;
end match for eq in iEqns);
end tVarsofResidualEqns;
protected function getTVarResiduals
input Integer index;
input array<Integer> v1;
input array<Integer> eqnLocalGlobal;
input list<Integer> iAcc;
output list<Integer> oAcc;
algorithm
oAcc := match(index,v1,eqnLocalGlobal,iAcc)
local
Integer e;
case (0,_,_,_) then iAcc;
case (_,_,_,_)
equation
e = v1[index];
e = eqnLocalGlobal[e];
then
getTVarResiduals(index-1,v1,eqnLocalGlobal,e::iAcc);
end match;
end getTVarResiduals;
protected function omcTearing2 " function to determine tvars and do cheap matching
author: Frenkel TUD 2012-05"
input list<Integer> unsolvables;
input list<Integer> tSel_always;
input list<Integer> tSel_prefer;
input list<Integer> tSel_avoid;
input list<Integer> tSel_never;
input BackendDAE.AdjacencyMatrixEnhanced m;
input BackendDAE.AdjacencyMatrixTEnhanced mt;
input array<list<Integer>> mapEqnIncRow;
input array<Integer> mapIncRowEqn;
input Integer size;
input BackendDAE.Variables vars;
input BackendDAE.Shared ishared;
input array<Integer> ass1;
input array<Integer> ass2;
input array<Integer> columark;
input Integer mark;
input list<Integer> inTVars;
output list<Integer> outTVars;
output Integer oMark;
algorithm
(outTVars,oMark) := matchcontinue(unsolvables,tSel_always)
local
Integer tvar;
list<Integer> unassigned,rest,ass1List, unsolv;
BackendDAE.AdjacencyMatrixElementEnhanced vareqns;
// if there are no unsolvables choose tvar by heuristic
case ({},{})
equation
// select tearing var
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\n" + BORDER + "\nBEGINNING of omcTearingSelectTearingVar\n\n\n");
end if;
tvar = omcTearingSelectTearingVar(vars,ass1,ass2,m,mt,tSel_prefer,tSel_avoid,tSel_never);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nEND of omcTearingSelectTearingVar\n" + BORDER + "\n\n");
end if;
// mark tearing var
arrayUpdate(ass1,tvar,size*2);
// equations not yet assigned containing the tvar
vareqns = List.removeOnTrue(ass2, isAssignedSaveEnhanced, mt[tvar]);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Assignable equations containing new tvar:\n");
BackendDump.dumpAdjacencyRowEnhanced(vareqns);
print("\n");
end if;
// cheap matching
tearingBFS(vareqns,m,mt,mapEqnIncRow,mapIncRowEqn,size,ass1,ass2,{});
// check for unassigned vars, if there some rerun
unassigned = Matching.getUnassigned(size,ass1,{});
(outTVars,oMark) = omcTearing3(unassigned,{},tSel_always,tSel_prefer,tSel_avoid,tSel_never,m,mt,mapEqnIncRow,mapIncRowEqn,size,vars,ishared,ass1,ass2,columark,mark+1,tvar::inTVars);
then
(outTVars,oMark);
// if there are unsolvables choose unsolvables as tvars
case (tvar::rest,{})
equation
if listMember(tvar,tSel_never) then
Error.addCompilerWarning("There are tearing variables with annotation attribute 'tearingSelect = never'. Use +d=tearingdump and +d=tearingdumpV for more information.");
end if;
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nForced selection of Tearing Variable:\n" + UNDERLINE + "\n");
end if;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("tVar: " + intString(tvar) + " (unsolvable in omcTearing2)\n\n\n");
end if;
// mark tearing var
arrayUpdate(ass1,tvar,size*2);
// equations not yet assigned containing the tvar
vareqns = List.removeOnTrue(ass2, isAssignedSaveEnhanced, mt[tvar]);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Assignable equations containing new tvar:\n");
BackendDump.dumpAdjacencyRowEnhanced(vareqns);
print("\n");
end if;
// cheap matching
tearingBFS(vareqns,m,mt,mapEqnIncRow,mapIncRowEqn,size,ass1,ass2,{});
// check for unassigned vars, if there some rerun
unassigned = Matching.getUnassigned(size,ass1,{});
(outTVars,oMark) = omcTearing3(unassigned,rest,tSel_always,tSel_prefer,tSel_avoid,tSel_never,m,mt,mapEqnIncRow,mapIncRowEqn,size,vars,ishared,ass1,ass2,columark,mark+1,tvar::inTVars);
then
(outTVars,oMark);
case (_,_)
equation
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nForced selection of Tearing Variables:\n" + UNDERLINE + "\n");
print("Variables with annotation attribute 'always' as tVars: " + stringDelimitList(List.map(tSel_always,intString),",")+"\n");
end if;
// mark tearing var
markTVars(tSel_always,ass1);
(_,unsolv,_) = List.intersection1OnTrue(unsolvables,tSel_always,intEq);
// equations not yet assigned containing the tvars
vareqns = findVareqns(ass2,isAssignedSaveEnhanced,mt,tSel_always);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Assignable equations containing new tvars:\n");
BackendDump.dumpAdjacencyRowEnhanced(vareqns);
print("\n");
end if;
// cheap matching
tearingBFS(vareqns,m,mt,mapEqnIncRow,mapIncRowEqn,size,ass1,ass2,{});
// check for unassigned vars, if there some rerun
unassigned = Matching.getUnassigned(size,ass1,{});
(outTVars,oMark) = omcTearing3(unassigned,unsolv,{},tSel_prefer,tSel_avoid,tSel_never,m,mt,mapEqnIncRow,mapIncRowEqn,size,vars,ishared,ass1,ass2,columark,mark+1,listAppend(tSel_always,inTVars));
then
(outTVars,oMark);
else
equation
print("Tearing.omcTearing2 failed!");
then
fail();
end matchcontinue;
end omcTearing2;
protected function findVareqns
"Function returns equations not yet assigned containing the currently handled tvars.
author: ptaeuber FHB 2014-05"
input array<Integer> ass2In;
input CompFunc inCompFunc;
input BackendDAE.AdjacencyMatrixTEnhanced mt;
input list<Integer> tSel_alwaysIn;
output list<tuple<Integer,BackendDAE.Solvability,BackendDAE.Constraints>> vareqnsOut = {};
partial function CompFunc
input array<Integer> inValue;
input tuple<Integer,BackendDAE.Solvability,BackendDAE.Constraints> inElement;
output Boolean outIsEqual;
end CompFunc;
algorithm
for tvar in tSel_alwaysIn loop
vareqnsOut := List.append_reverse(List.removeOnTrue(ass2In,inCompFunc,mt[tvar]), vareqnsOut);
end for;
vareqnsOut := List.unique(vareqnsOut);
end findVareqns;
protected function omcTearingSelectTearingVar " author: Frenkel TUD 2012-05"
input BackendDAE.Variables vars;
input array<Integer> ass1;
input array<Integer> ass2;
input BackendDAE.AdjacencyMatrixEnhanced m;
input BackendDAE.AdjacencyMatrixTEnhanced mt;
input list<Integer> tSel_prefer;
input list<Integer> tSel_avoid;
input list<Integer> tSel_never;
output Integer tearingVar;
algorithm
tearingVar := matchcontinue(vars,ass1,ass2,m,mt,tSel_prefer,tSel_avoid,tSel_never)
local
list<Integer> freeVars,eqns,unsolvables,pointsLst;
Integer tvar;
Integer size,varsize;
array<Integer> points;
// if vars there with no linear occurrence in any equation use all of them
/* case(_,_,_,_)
equation
then
// if states there use them as tearing variables
case(_,_,_,_)
equation
(_,states) = BackendVariable.getAllStateVarIndexFromVariables(vars);
states = List.removeOnTrue(ass1, isAssigned, states);
false = listEmpty(states);
tvar = selectVarWithMostEqns(states,ass2,mt,-1,-1);
then
tvar;
*/
// if there is a variable unsolvable select it
case(_,_,_,_,_,_,_,_)
equation
unsolvables = getUnsolvableVarsConsiderMatching(1,BackendVariable.varsSize(vars),mt,ass1,ass2,{});
false = listEmpty(unsolvables);
tvar = listHead(unsolvables);
if listMember(tvar,tSel_never) then
Error.addCompilerWarning("There are tearing variables with annotation attribute 'tearingSelect = never'. Use +d=tearingdump and +d=tearingdumpV for more information.");
end if;
if Flags.isSet(Flags.TEARING_DUMP) or Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nForced selection of Tearing Variable:\n" + UNDERLINE + "\n");
end if;
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("tVar: " + intString(tvar) + " (unsolvable in omcTearingSelectTearingVar)\n\n");
end if;
then
tvar;
case(_,_,_,_,_,_,_,_)
equation
varsize = BackendVariable.varsSize(vars);
// variables not assigned yet:
freeVars = Matching.getUnassigned(varsize,ass1,{});
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("omcTearingSelectTearingVar Candidates(unassigned vars):\n");
BackendDump.debuglst(freeVars,intString,", ","\n");
end if;
(_,freeVars,_) = List.intersection1OnTrue(freeVars,tSel_never,intEq);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Candidates without variables with annotation attribute 'never':\n");
BackendDump.debuglst(freeVars,intString,", ","\n");
end if;
size = listLength(freeVars);
true = intGt(size,0);
// CALCULATE TEARING-VARIABLE WEIGHTS
points = arrayCreate(varsize,0);
// 1st: Points for solvability (see function solvabilityWeights)
points = List.fold2(freeVars, calcVarWeights,mt,ass2,points);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("\nPoints after 'calcVarWeights':\n" + stringDelimitList(List.map(arrayList(points),intString),",") + "\n\n");
end if;
eqns = Matching.getUnassigned(arrayLength(m),ass2,{});
// 2nd: 5 points for each equation this variable would causalize
points = List.fold2(eqns,addEqnWeights,m,ass1,points);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Points after 'addEqnWeights':\n" + stringDelimitList(List.map(arrayList(points),intString),",") + "\n\n");
end if;
// 3rd: only one-tenth of points for each discrete variable
points = List.fold1(freeVars,discriminateDiscrete,vars,points);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Points after 'discriminateDiscrete':\n" + stringDelimitList(List.map(arrayList(points),intString),",") + "\n\n");
end if;
// 4th: Prefer variables with annotation attribute 'tearingSelect=prefer'
pointsLst = preferAvoidVariables(freeVars, arrayList(points), tSel_prefer, 3.0, 1);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Points after preferring variables with attribute 'prefer':\n" + stringDelimitList(List.map(pointsLst,intString),",") + "\n\n");
end if;
// 5th: Avoid variables with annotation attribute 'tearingSelect=avoid'
pointsLst = preferAvoidVariables(freeVars, pointsLst, tSel_avoid, 0.334, 1);
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("Points after discrimination against variables with attribute 'avoid':\n" + stringDelimitList(List.map(pointsLst,intString),",") + "\n\n");
end if;
tvar = selectVarWithMostPoints(freeVars,pointsLst);
// fcall(Flags.TEARING_DUMPVERBOSE,print,"VarsWithMostEqns:\n");
// fcall(Flags.TEARING_DUMPVERBOSE,BackendDump.debuglst,(freeVars,intString,", ","\n"));
if Flags.isSet(Flags.TEARING_DUMPVERBOSE) then
print("tVar: " + intString(tvar) + " (" + intString(listGet(pointsLst,tvar)) + " points)\n\n");
elseif listMember(tvar,tSel_avoid) then
Error.addCompilerWarning("The Tearing heuristic has chosen variables with annotation attribute 'tearingSelect = avoid'. Use +d=tearingdump and +d=tearingdumpV for more information.");
end if;
then
tvar;
else
equation
print("omcTearingSelectTearingVar failed because no unmatched var!\n");
then
fail();
end matchcontinue;
end omcTearingSelectTearingVar;
protected function getUnsolvableVarsConsiderMatching
" returns one unsolvable var with respect to the current matching
author: Frenkel TUD 2012-08"
input Integer index;
input Integer size;
input BackendDAE.AdjacencyMatrixTEnhanced meT;
input array<Integer> ass1;