-
Notifications
You must be signed in to change notification settings - Fork 298
/
ResolveLoops.mo
3123 lines (2908 loc) · 116 KB
/
ResolveLoops.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 ResolveLoops
" file: ResolveLoops.mo
package: ResolveLoops
description: This package contains functions for the optimization module
resolveLoops."
import BackendDAE;
import DAE;
protected
import Array;
import AvlSetInt;
import BackendDAEUtil;
import BackendEquation;
import BackendVariable;
import BackendDump;
import ComponentReference;
import Expression;
import ExpressionSimplify;
import ExpressionSolve;
import ExpressionDump;
import Flags;
import HpcOmTaskGraph;
import List;
import Util;
import Tearing;
public function resolveLoops "author:Waurich TUD 2013-12
traverses the equations and finds simple equations(i.e. linear functions
withcoefficients of 1 or -1). if these equations form loops, they will be
contracted.
This happens especially in eletrical models. Here, kirchhoffs voltage and
current law can be applied."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
protected
BackendDAE.EqSystems eqSysts;
BackendDAE.Shared shared;
algorithm
(eqSysts, shared, _) := List.mapFold2(inDAE.eqs, resolveLoops_main, inDAE.shared, 1);
outDAE := BackendDAE.DAE(eqSysts, shared);
end resolveLoops;
protected function resolveLoops_main "author: Waurich TUD 2014-01
Collects the linear equations of the whole DAE. bipartite graphs of the
eqSystem can be output. All variables and equations which do not belong to a
loop will be removed. the loops will be analysed and resolved"
input BackendDAE.EqSystem inEqSys;
input BackendDAE.Shared inShared "unused, just for dumping graphml";
input Integer inSysIdx;
output BackendDAE.EqSystem outEqSys;
output BackendDAE.Shared outShared = inShared "unused";
output Integer outSysIdx;
algorithm
(outEqSys, outSysIdx) := matchcontinue(inEqSys)
local
Integer numSimpEqs, numVars, numSimpVars;
array<Integer> eqMapArr,varMapArr,nonLoopEqMark,markLinEqVars;
list<Integer> eqMapping, varMapping, eqCrossLst, varCrossLst;
list<list<Integer>> partitions, loops;
list<tuple<Boolean,String>> varAtts,eqAtts;
BackendDAE.Variables vars,simpVars;
BackendDAE.EquationArray eqs,simpEqs;
BackendDAE.EqSystem syst;
BackendDAE.AdjacencyMatrix m,mT,m_cut, mT_cut, m_after, mT_after;
BackendDAE.Matching matching;
BackendDAE.StateSets stateSets;
list<DAE.ComponentRef> crefs;
list<BackendDAE.Equation> simpEqLst,resolvedEqs;
list<BackendDAE.Var> simpVarLst;
case syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqs)
equation
(m,_) = BackendDAEUtil.adjacencyMatrix(syst, BackendDAE.ABSOLUTE(), NONE(), BackendDAEUtil.isInitializationDAE(inShared));
if Flags.isSet(Flags.RESOLVE_LOOPS_DUMP) then
BackendDump.dumpBipartiteGraphEqSystem(syst,inShared, "whole System_"+intString(inSysIdx));
end if;
//BackendDump.dumpEqSystem(syst,"the complete DAE");
// get the linear equations and their vars
markLinEqVars = arrayCreate(BackendVariable.varsSize(vars),-1);
(simpEqLst,eqMapping,_,_,markLinEqVars,_) = BackendEquation.traverseEquationArray(eqs, getSimpleEquations, ({},{},1,vars,markLinEqVars,m));
eqMapArr = listArray(eqMapping);
(simpVarLst,varMapArr) = getSimpleEquationVariables(markLinEqVars,vars);
simpEqs = BackendEquation.listEquation(simpEqLst);
simpVars = BackendVariable.listVar1(simpVarLst);
// build the adjacency matrix for the linear equations
numSimpEqs = listLength(simpEqLst);
numVars = listLength(simpVarLst);
(m,mT) = BackendDAEUtil.adjacencyMatrixDispatch(simpVars,simpEqs, BackendDAE.ABSOLUTE(), NONE(), BackendDAEUtil.isInitializationDAE(inShared));
if Flags.isSet(Flags.RESOLVE_LOOPS_DUMP) then
varAtts = List.threadMap(List.fill(false,numVars),List.fill("",numVars),Util.makeTuple);
eqAtts = List.threadMap(List.fill(false,numSimpEqs),List.fill("",numSimpEqs),Util.makeTuple);
BackendDump.dumpBipartiteGraphStrongComponent2(simpVars,simpEqs,m,varAtts,eqAtts,"rL_simpEqs_"+intString(inSysIdx));
end if;
//partition graph
partitions = arrayList(partitionBipartiteGraph(m,mT));
partitions = List.filterOnTrue(partitions,List.hasSeveralElements);
//print("the partitions for system "+intString(inSysIdx)+" : \n"+stringDelimitList(List.map(partitions,HpcOmTaskGraph.intLstString),"\n")+"\n");
// cut the deadends (vars and eqs outside of the loops)
m_cut = arrayCopy(m);
mT_cut = arrayCopy(mT);
(_,nonLoopEqMark) = resolveLoops_cutNodes(m_cut,mT_cut); // this is pretty memory intensive
if Flags.isSet(Flags.RESOLVE_LOOPS_DUMP) then
varAtts = List.threadMap(List.fill(false,numVars),List.fill("",numVars),Util.makeTuple);
eqAtts = List.threadMap(List.fill(false,numSimpEqs),List.fill("",numSimpEqs),Util.makeTuple);
BackendDump.dumpBipartiteGraphStrongComponent2(simpVars,simpEqs,m_cut,varAtts,eqAtts,"rL_loops_"+intString(inSysIdx));
end if;
// handle the partitions separately, resolve the loops in the partitions, insert the resolved equation
eqs = resolveLoops_resolvePartitions(partitions,m_cut,mT_cut,m,mT,eqMapArr,varMapArr,eqs,vars,nonLoopEqMark);
syst.orderedEqs = eqs;
//BackendDump.dumpEquationList(eqLst,"the complete DAE after resolving");
if Flags.isSet(Flags.RESOLVE_LOOPS_DUMP) then
// get the graphML for the resolved System
simpEqLst = BackendEquation.getList(eqMapping,eqs);
simpEqs = BackendEquation.listEquation(simpEqLst);
numSimpEqs = listLength(simpEqLst);
numVars = listLength(simpVarLst);
m_after = BackendDAEUtil.adjacencyMatrixDispatch(simpVars,simpEqs, BackendDAE.ABSOLUTE(),NONE(),BackendDAEUtil.isInitializationDAE(inShared));
varAtts = List.threadMap(List.fill(false,numVars),List.fill("",numVars),Util.makeTuple);
eqAtts = List.threadMap(List.fill(false,numSimpEqs),List.fill("",numSimpEqs),Util.makeTuple);
BackendDump.dumpBipartiteGraphStrongComponent2(simpVars,simpEqs,m_after,varAtts,eqAtts,"rL_after_"+intString(inSysIdx));
end if;
syst = BackendDAEUtil.clearEqSyst(syst);
//BackendDump.dumpEqSystem(eqSys,"the complete DAE after");
then (syst, inSysIdx+1);
else (inEqSys, inSysIdx+1);
end matchcontinue;
end resolveLoops_main;
protected function resolveLoops_resolvePartitions "author:Waurich TUD 2014-02
checks every partition for loops and resolves them if its worth to."
input list<list<Integer>> partitionsIn;
input BackendDAE.AdjacencyMatrix mIn;
input BackendDAE.AdjacencyMatrixT mTIn;
input BackendDAE.AdjacencyMatrix m_uncut;
input BackendDAE.AdjacencyMatrixT mT_uncut;
input array<Integer> eqMap;
input array<Integer> varMap;
input BackendDAE.EquationArray daeEqs;
input BackendDAE.Variables daeVars;
input array<Integer> nonLoopEqMark;
output BackendDAE.EquationArray daeEqsOut;
algorithm
daeEqsOut := matchcontinue(partitionsIn,mIn,mTIn,m_uncut,mT_uncut,eqMap,varMap,daeEqs,daeVars,nonLoopEqMark)
local
Option<tuple<list<Integer>,BackendDAE.AdjacencyMatrix,list<list<Integer>>>> optStructureMapping;
list<Integer> partition, eqCrossLst, varCrossLst, mapIndices;
list<list<Integer>> rest, loops;
BackendDAE.EquationArray eqs;
BackendDAE.AdjacencyMatrix map;
case(partition::rest,_,_,_,_,_,_,_,_,_)
equation
partition = List.filter1OnTrue(partition,arrayIsZeroAt,nonLoopEqMark); //the eqs that are loops
true = listEmpty(partition);
eqs = resolveLoops_resolvePartitions(rest,mIn,mTIn,m_uncut,mT_uncut,eqMap,varMap,daeEqs,daeVars,nonLoopEqMark);
then
eqs;
case(partition::rest,_,_,_,_,_,_,_,_,_)
equation
// search the partitions for loops
partition = List.filter1OnTrue(partition,arrayIsZeroAt,nonLoopEqMark); //the eqs that are loops
//print("\nanalyse the partition "+stringDelimitList(List.map(partition,intString),",")+"\n");
(loops,eqCrossLst,varCrossLst,optStructureMapping) = resolveLoops_findLoops({partition},mIn,mTIn);
loops = List.filterOnFalse(loops,listEmpty);
//print("the loops in this partition: \n"+stringDelimitList(List.map(loops,HpcOmTaskGraph.intLstString),"\n")+"\n");
// check if its worth to resolve the loops
if isSome(optStructureMapping) then
SOME((mapIndices,map,loops)) = optStructureMapping;
loops = List.filter1OnTrueAndUpdate(loops,evaluateTripleLoop,updateTripleLoop,(m_uncut,mT_uncut,eqCrossLst,mapIndices,map));
else
loops = List.filter1OnTrue(loops,evaluateLoop,(m_uncut,mT_uncut,eqCrossLst));
end if;
//print("the loops that will be resolved: \n"+stringDelimitList(List.map(loops,HpcOmTaskGraph.intLstString),"\n")+"\n");
// resolve the loops
(eqs,_) = resolveLoops_resolveAndReplace(loops,eqCrossLst,varCrossLst,mIn,mTIn,eqMap,varMap,daeEqs,daeVars,{}); //KAB4
eqs = resolveLoops_resolvePartitions(rest,mIn,mTIn,m_uncut,mT_uncut,eqMap,varMap,eqs,daeVars,nonLoopEqMark);
then
eqs;
case({},_,_,_,_,_,_,_,_,_)
equation
then
daeEqs;
end matchcontinue;
end resolveLoops_resolvePartitions;
protected function resolveLoops_cutNodes "author: Waurich TUD 2014-01
cut the deadend nodes from the partitions"
input BackendDAE.AdjacencyMatrix mIn;
input BackendDAE.AdjacencyMatrix mTIn;
output array<Integer> deadEndVarsMark;
output array<Integer> deadEndEqsMark;
algorithm
(deadEndVarsMark,deadEndEqsMark) := matchcontinue(mIn,mTIn)
local
Integer numVars, numEqs, idx;
list<Integer> loopVars, loopEqs, eqs, nonLoopVars, nonLoopEqs, eqCrossLst, varCrossLst;
list<list<Integer>> restPartitions, loopVarLst;
list<BackendDAE.Equation> eqLst;
list<BackendDAE.Var> varLst;
case(_,_)
algorithm
// get the outer deadEnd variables
numVars := arrayLength(mTIn);
numEqs := arrayLength(mIn);
nonLoopVars := List.filter2OnTrue(List.intRange(numVars),arrayEntryLengthIs,mTIn,1);
//print("nonLoopVars: \n"+stringDelimitList(List.map(nonLoopVars,intString)," / ")+"\n");
deadEndVarsMark := arrayCreate(numVars,0);
deadEndEqsMark := arrayCreate(numVars,0);
for idx in nonLoopVars loop
arrayUpdate(deadEndVarsMark,idx,1);
end for;
for idx in nonLoopVars loop
// DFS
markDeadEndsInBipartiteGraph(idx,mIn,mTIn,deadEndEqsMark,deadEndVarsMark);
end for;
idx := 1;
while idx <= numVars loop
// non-loop var
if arrayGet(deadEndVarsMark,idx) == 1 then
arrayUpdate(mTIn,idx,{});
//loop var
else
loopEqs := arrayGet(mTIn,idx);
loopEqs := List.filter1OnTrue(loopEqs,arrayIsZeroAt,deadEndEqsMark); //the loop equations
arrayUpdate(mTIn,idx,loopEqs);
end if;
idx := idx+1;
end while;
idx := 1;
while idx <= numEqs loop
// non-loop eq
if arrayGet(deadEndEqsMark,idx) == 1 then
arrayUpdate(mIn,idx,{});
//loop eq
else
loopVars := arrayGet(mIn,idx);
loopVars := List.filter1OnTrue(loopVars,arrayIsZeroAt,deadEndVarsMark); //the loop vars
arrayUpdate(mIn,idx,loopVars);
end if;
idx := idx+1;
end while;
then (deadEndVarsMark,deadEndEqsMark);
else
equation
Error.addInternalError("function resolveLoops_cutNodes failed", sourceInfo());
then
fail();
end matchcontinue;
end resolveLoops_cutNodes;
protected function arrayEntryLengthIs "author:Waurich TUD 2014-01
gets the indexed entry of the array and compares the length with the given value."
input Integer idx;
input array<list<Integer>> arr;
input Integer len;
output Boolean eqLen;
protected
list<Integer> entry;
Integer len1;
algorithm
entry := arrayGet(arr,idx);
len1 := listLength(entry);
eqLen := intEq(len,len1);
end arrayEntryLengthIs;
protected function getSimpleEquations
"if the linear equation contains only variables with factor 1 or -1 except for the states."
input BackendDAE.Equation inEq;
input tuple<list<BackendDAE.Equation>, list<Integer>, Integer, BackendDAE.Variables, array<Integer>, BackendDAE.AdjacencyMatrix> inTpl;
output BackendDAE.Equation outEq = inEq;
output tuple<list<BackendDAE.Equation>, list<Integer>, Integer, BackendDAE.Variables, array<Integer>, BackendDAE.AdjacencyMatrix> outTpl;
protected
Boolean isSimple;
Integer idx;
BackendDAE.Equation eq;
BackendDAE.AdjacencyMatrix m;
BackendDAE.Variables vars;
array<Integer> markLinEqVars;
list<BackendDAE.Equation> eqLst;
list<Integer> idxMap;
algorithm
(eqLst, idxMap, idx, vars, markLinEqVars, m) := inTpl;
if BackendEquation.isEquation(inEq) and not eqIsConst(inEq)/*simple assignments should not occur here, they cannot be improved any further*/ then
(eq,(isSimple,_)) := BackendEquation.traverseExpsOfEquation(inEq,isAddOrSubExp,(true,vars));
if isSimple then
eqLst := eq::eqLst;
idxMap := idx::idxMap;
for varIdx in m[idx] loop
arrayUpdate(markLinEqVars,intAbs(varIdx),1);
end for;
end if;
end if;
outTpl := (eqLst,idxMap,idx+1,vars,markLinEqVars,m);
end getSimpleEquations;
protected function getSimpleEquationVariables"
Get the variables which occur in the linear equations and have been marked in the markLinEqVars array.
author:Waurich 2017-07"
input array<Integer> markLinEqVars;
input BackendDAE.Variables vars;
output list<BackendDAE.Var> simpVars={};
output array<Integer> varMapArr;
protected
Integer varIdx;
list<Integer> varMap;
algorithm
varMap := {};
for varIdx in 1:arrayLength(markLinEqVars) loop
if markLinEqVars[varIdx] > 0 then
varMap := varIdx::varMap;
simpVars := BackendVariable.getVarAt(vars, varIdx)::simpVars;
end if;
end for;
varMapArr := listArray(varMap);
end getSimpleEquationVariables;
public function resolveLoops_findLoops "author:Waurich TUD 2014-02
gets the crossNodes for the partitions and searches for loops"
input list<list<Integer>> partitionsIn;
input BackendDAE.AdjacencyMatrix mIn; // the whole system of simpleEquations
input BackendDAE.AdjacencyMatrixT mTIn;
input Boolean findExactlyOneLoop=false;
output list<list<Integer>> loopsOut = {};
output list<Integer> crossEqsOut = {};
output list<Integer> crossVarsOut = {};
output Option<tuple<list<Integer>,BackendDAE.AdjacencyMatrix,list<list<Integer>>>> optStructureMapping;
protected
list<list<Integer>> loops, eqVars;
list<Integer> eqCrossLst, varCrossLst, partitionVars;
AvlSetInt.Tree set;
tuple<list<Integer>,BackendDAE.AdjacencyMatrix,list<list<Integer>>> structureMapping;
algorithm
for partition in partitionsIn loop
try
// get the eqCrossNodes and varCrossNodes i.e. nodes with more than 2 edges
eqVars := List.map1(partition,Array.getIndexFirst,mIn);
set := AvlSetInt.EMPTY();
for vars in eqVars loop
set := AvlSetInt.addList(set, vars);
end for;
partitionVars := AvlSetInt.listKeys(set);
eqCrossLst := List.fold2(partition,gatherCrossNodes,mIn,mTIn,{});
varCrossLst := List.fold2(partitionVars,gatherCrossNodes,mTIn,mIn,{});
// search the partitions for loops
(loops,optStructureMapping) := resolveLoops_findLoops2(partition,eqCrossLst,varCrossLst,mIn,mTIn,findExactlyOneLoop);
if if findExactlyOneLoop then (not listEmpty(loops) and not listEmpty(loopsOut)) else false then
fail();
end if;
loopsOut := listAppend(loops,loopsOut);
if isPresent(crossEqsOut) then
crossEqsOut := listAppend(eqCrossLst,crossEqsOut);
end if;
if isPresent(crossVarsOut) then
crossVarsOut := listAppend(varCrossLst,crossVarsOut);
end if;
else
return;
end try;
end for;
end resolveLoops_findLoops;
protected function resolveLoops_findLoops2 "author: Waurich TUD 2014-01
handles the given partition of eqs and vars depending whether there are only varCrossNodes, only EqCrossNodes, both of them or none of them."
input list<Integer> eqsIn;
input list<Integer> eqCrossLstIn;
input list<Integer> varCrossLstIn;
input BackendDAE.AdjacencyMatrix mIn; // the whole system of simpleEquations
input BackendDAE.AdjacencyMatrixT mTIn;
input Boolean findExactlyOneLoop;
output list<list<Integer>> loopsOut;
output Option<tuple<list<Integer>,BackendDAE.AdjacencyMatrix,list<list<Integer>>>> structureMapping;
algorithm
(loopsOut,structureMapping) := match(eqsIn,eqCrossLstIn,varCrossLstIn,mIn,mTIn)
local
Boolean isNoSingleLoop;
Integer replaceIdx,eqIdx,varIdx,parEqIdx,daeEqIdx;
list<Integer> varCrossLst, eqCrossLst, crossNodes, restNodes, adjCrossNodes, partition, partition2, replEqs, subLoop, mapIndices;
list<list<Integer>> paths, allPaths, simpleLoops, tripleLoops, varEqsLst, crossEqLst, paths0, paths1, closedPaths, loopConnectors, connectedPaths;
BackendDAE.Equation resolvedEq, startEq;
list<BackendDAE.Equation> eqLst;
AvlSetInt.Tree eqCrossSet;
BackendDAE.AdjacencyMatrix minAdj,map;
tuple<list<Integer>,BackendDAE.AdjacencyMatrix> mapping;
Option<tuple<list<Integer>,BackendDAE.AdjacencyMatrix,list<list<Integer>>>> optTripleMapping;
case(_,_::_,{},_,_)
equation //KAB1
//print("partition has only eqCrossNodes\n");
// get the paths between the crossEqNodes and order them according to their length
allPaths = getPathTillNextCrossEq(eqCrossLstIn,mIn,mTIn,eqCrossLstIn,{},{});
allPaths = List.sort(allPaths,List.listIsLonger);
//print("all paths: \n"+stringDelimitList(List.map(allPaths,HpcOmTaskGraph.intLstString)," / ")+"\n");
paths1 = List.fold1(allPaths,getReverseDoubles,allPaths,{}); // all paths with just one direction
paths0 = List.unique(paths1); // only the paths between the eqs without concerning the vars in between
simpleLoops = getDoubles(paths1,{}); // get 2 adjacent equations which form a simple loop i.e. they share 2 variables
//print("all simpleLoop-paths: \n"+stringDelimitList(List.map(simpleLoops,HpcOmTaskGraph.intLstString)," / ")+"\n");
(_,paths,_) = List.intersection1OnTrue(paths1,simpleLoops,intLstIsEqual);
// special case to find more complex structures (arrays and triple loops)
if listEmpty(simpleLoops) then
(eqCrossLst,paths1,mapping,minAdj) = findEqualPathStructure(eqCrossLstIn,paths1);
//print("crossNodes: " + HpcOmTaskGraph.intLstString(eqCrossLst) + "\n");
(mapIndices,map) = mapping;
(tripleLoops,paths0) = getTriples(eqCrossLst,minAdj);
optTripleMapping = SOME((mapIndices,map,tripleLoops));
//print("all tripleLoop-paths after equal structure: \n"+stringDelimitList(List.map(tripleLoops,HpcOmTaskGraph.intLstString)," / ")+"\n");
else
optTripleMapping = NONE();
paths0 = List.sort(paths,List.listIsLonger); // solve the small loops first
(connectedPaths,loopConnectors) = connect2PathsToLoops(paths0,{},{});
loopConnectors = List.filter1OnTrue(loopConnectors,connectsLoops,simpleLoops);
simpleLoops = listAppend(simpleLoops,loopConnectors) annotation(__OpenModelica_DisableListAppendWarning=true);
//print("all simpleLoop-paths: \n"+stringDelimitList(List.map(simpleLoops,HpcOmTaskGraph.intLstString)," / ")+"\n");
subLoop = connectPathsToOneLoop(simpleLoops,{}); // try to build a a closed loop from these paths
isNoSingleLoop = listEmpty(subLoop);
simpleLoops = if isNoSingleLoop then simpleLoops else {subLoop};
paths0 = listAppend(simpleLoops,connectedPaths);
paths0 = sortPathsAsChain(paths0);
if findExactlyOneLoop then
if not listEmpty(paths0) then
{_} = paths0;
end if;
end if;
end if;
//print("all paths to be resolved: \n"+stringDelimitList(List.map(paths0,HpcOmTaskGraph.intLstString)," / ")+"\n");
then
(paths0, optTripleMapping);
case(_,{},_::_,_,_)
equation
//print("partition has only varCrossNodes\n");
// get the paths between the crossVarNodes and order them according to their length
paths = getPathTillNextCrossEq(varCrossLstIn,mTIn,mIn,varCrossLstIn,{},{});
paths = List.sort(paths,List.listIsLonger);
paths = listReverse(paths);
//print("from all the paths: \n"+stringDelimitList(List.map(paths,HpcOmTaskGraph.intLstString)," / ")+"\n");
(paths0,paths1) = List.extract1OnTrue(paths,listLengthIs,listLength(List.last(paths)));
//print("the shortest paths: \n"+stringDelimitList(List.map(paths0,HpcOmTaskGraph.intLstString)," / ")+"\n");
paths1 = if listEmpty(paths1) then paths0 else paths1;
closedPaths = List.map1(paths1,closePathDirectly,paths0);
closedPaths = List.fold1(closedPaths,getReverseDoubles,closedPaths,{}); // all paths with just one direction
closedPaths = List.map(closedPaths,List.unique);
closedPaths = List.map1(closedPaths,getEqNodesForVarLoop,mTIn);// get the eqs for these varLoops
//print("solve the smallest loops: \n"+stringDelimitList(List.map(closedPaths,HpcOmTaskGraph.intLstString)," / ")+"\n");
if findExactlyOneLoop then
if not listEmpty(closedPaths) then
{_} = closedPaths;
end if;
end if;
then (closedPaths,NONE());
case(_,{},{},_,_)
algorithm
// no crossNodes
//print("no crossNodes\n");
subLoop := eqsIn;
for e in eqsIn loop
if listEmpty(mIn[e]) then
subLoop := {};
break;
end if;
end for;
then ({subLoop},NONE());
case(_,_::_,_::_,_,_)
algorithm
//print("there are both varCrossNodes and eqNodes\n");
//at least get paths of length 2 between eqCrossNodes
for i in 1:arrayLength(mIn) loop
arrayUpdate(mIn, i, List.heapSortIntList(mIn[i]));
end for;
for i in 1:arrayLength(mTIn) loop
arrayUpdate(mTIn, i, List.heapSortIntList(mTIn[i]));
end for;
eqCrossSet := AvlSetInt.addList(AvlSetInt.EMPTY(), eqCrossLstIn);
paths := getShortPathsBetweenEqCrossNodes(AvlSetInt.listKeysReverse(eqCrossSet), eqCrossSet, mIn, mTIn, {}, findExactlyOneLoop);
//
//print("GOT SOME NEW LOOPS: \n"+stringDelimitList(List.map(paths,HpcOmTaskGraph.intLstString)," / ")+"\n");
then (paths,NONE());
else
equation
Error.addInternalError("function resolveLoops_findLoops2 failed", sourceInfo());
then
fail();
end match;
end resolveLoops_findLoops2;
protected function findEqualPathStructure //KAB2
"author: kabdelhak FHB 2019-06
Resolves seemingly hard structures mostly formed through array connectors.
By finding equally connected crossNodes and merging them to one single
node, the loop becomes way simpler. All merged nodes will get treated the
same as the super node. The mapping contains the information which nodes
got merged and which index contains the super node."
input output list<Integer> crossNodes;
input output list<list<Integer>> uniquePaths;
output tuple<list<Integer>,BackendDAE.AdjacencyMatrix> mapping;
output BackendDAE.AdjacencyMatrix minAdj;
protected
list<Integer> mapIndices;
BackendDAE.AdjacencyMatrix map;
algorithm
minAdj := getMinimalAdjacencyMatrix(crossNodes,uniquePaths);
(minAdj,uniquePaths,mapIndices,map,crossNodes) := removeEqualPaths(crossNodes,minAdj,uniquePaths,{},arrayCreate(max(cn for cn in crossNodes),{}));
mapping := (mapIndices,map);
end findEqualPathStructure;
protected function getMinimalAdjacencyMatrix
"author: kabdelhak FHB 2019-06
Returns the minimal adjacency matrix of connected equations in the partition.
NOTE: Rows AND Columns represent equations. No variables involved."
input list<Integer> crossNodes;
input list<list<Integer>> uniquePaths;
output BackendDAE.AdjacencyMatrix minAdj;
algorithm
minAdj := arrayCreate(max(cn for cn in crossNodes),{});
for path in uniquePaths loop
_ := match path
local
Integer a, b;
case a::{b} algorithm // a::rest ?
minAdj := Array.appendToElement(a, {b}, minAdj);
minAdj := Array.appendToElement(b, {a}, minAdj);
then 0;
else 1;
end match;
end for;
//sort
for cn in crossNodes loop
arrayUpdate(minAdj,cn,List.sort(arrayGet(minAdj,cn),intGt));
end for;
end getMinimalAdjacencyMatrix;
protected function removeEqualPaths
"author: kabdelhak FHB 2019-06
Helper function for findEqualPathStructure. It removes the superfluous nodes
and declares the index first as super node."
input list<Integer> crossNodes;
input output BackendDAE.AdjacencyMatrix minAdj;
input output list<list<Integer>> uniquePaths;
input output list<Integer> mapIndices;
input output BackendDAE.AdjacencyMatrix map;
input output list<Integer> accCrossNodes = {};
algorithm
(minAdj,uniquePaths,mapIndices,map,accCrossNodes) := match crossNodes
local
Integer cn1;
list<Integer> rest, assigned = {}, unassigned = {};
case cn1::rest algorithm
accCrossNodes:=cn1::accCrossNodes;
for cn2 in rest loop
if HpcOmTaskGraph.equalLists(arrayGet(minAdj,cn1),arrayGet(minAdj,cn2)) then
assigned := cn2::assigned;
arrayUpdate(minAdj,cn2,{});
uniquePaths := removeNode(cn2,uniquePaths);
else
unassigned := cn2::unassigned;
accCrossNodes := cn2::accCrossNodes;
end if;
end for;
if not listEmpty(assigned) then
mapIndices := cn1::mapIndices;
map := Array.appendToElement(cn1, assigned, map);
end if;
then removeEqualPaths(unassigned,minAdj,uniquePaths,mapIndices,map,accCrossNodes);
else (minAdj,uniquePaths,mapIndices,map,accCrossNodes);
end match;
end removeEqualPaths;
protected function removeNode
"author: kabdelhak FHB 2019-06
Helper function for findEqualPathStructure. It removes all paths containing
a specific node."
input Integer node;
input list<list<Integer>> inPaths;
input output list<list<Integer>> accPaths={};
algorithm
accPaths:=matchcontinue inPaths
local
list<Integer> path;
list<list<Integer>> rest, acc;
case path::rest
algorithm
if not pathContainsNode(node,path) then
acc := path::accPaths;
else
acc := accPaths;
end if;
then removeNode(node,rest,acc);
case {}
then accPaths;
end matchcontinue;
end removeNode;
protected function pathContainsNode
"author: kabdelhak FHB 2019-06
Helper function for findEqualPathStructure. Returns true, if the node is contained
in given path."
input Integer node;
input list<Integer> inPath;
output Boolean c;
algorithm
c := match inPath
local
Integer n;
list<Integer> rest;
case n::rest guard(intEq(n,node))
then true;
case _::rest
then pathContainsNode(node,rest);
case {}
then false;
end match;
end pathContainsNode;
protected function listContains
input list<Integer> lst;
input Integer int;
output Boolean res = false;
algorithm
for i in lst loop
if intEq(i,int) then
res := true;
return;
end if;
end for;
end listContains;
protected function hasSameIntSortedExcept
input list<Integer> inList1;
input list<Integer> inList2;
input Integer excl;
output Boolean rv = false;
protected
Integer i1, i2;
list<Integer> l1 = inList1, l2 = inList2;
algorithm
if listEmpty(inList1) or listEmpty(inList2) then
return;
end if;
i1::l1 := l1;
i2::l2 := l2;
while true loop
if i1 > i2 then
if listEmpty(l2) then
return;
end if;
i2::l2 := l2;
elseif i1 < i2 then
if listEmpty(l1) then
return;
end if;
i1::l1 := l1;
else
if i1 <> excl then
rv := true;
return;
end if;
if listEmpty(l1) or listEmpty(l2) then
return;
end if;
i1::l1 := l1;
i2::l2 := l2;
end if;
end while;
end hasSameIntSortedExcept;
protected function getShortPathsBetweenEqCrossNodes"find closedLoops between 2 eqCrossNode, no matter whether there are var cross nodes between them.
author: vwaurich TUD 12-2016"
input list<Integer> eqCrossLstIn;
input AvlSetInt.Tree eqCrossSet;
input BackendDAE.AdjacencyMatrix mIn;
input BackendDAE.AdjacencyMatrixT mTIn;
input list<list<Integer>> pathsIn;
input Boolean findExactlyOneLoop;
output list<list<Integer>> pathsOut;
algorithm
pathsOut := match(eqCrossLstIn, mIn, mTIn, pathsIn)
local
Integer crossEq, adjVar, adjEq;
list<Integer> rest, adjVars, adjVars2, adjEqs, sharedVars, newPath;
list<list<Integer>> paths = {};
case(crossEq::rest,_,_,_)
algorithm
//print("check crossEq "+intString(crossEq)+"\n");
adjVars := arrayGet(mIn, crossEq);
for adjVar in adjVars loop
//print("all adj eqs "+stringDelimitList(List.map(adjEqs, intString),",")+"\n");
//all adjEqs which are crossnodes as well
for adjEq in arrayGet(mTIn, adjVar) loop
if if adjEq > crossEq then (not AvlSetInt.hasKey(eqCrossSet, adjEq)) else true then
continue;
end if;
//print("all sharedVars "+stringDelimitList(List.map(sharedVars, intString),",")+"\n");
if hasSameIntSortedExcept(adjVars, arrayGet(mIn, adjEq), adjVar) then
newPath := adjEq::{crossEq};
// TODO: List.unionElt is slow
paths := List.unionElt(newPath, paths);
//print("found path "+stringDelimitList(List.map(newPath,intString)," ; ")+"\n");
if if findExactlyOneLoop then (not listEmpty(pathsIn)) else false then
fail();
end if;
end if;
end for;
end for;
paths := getShortPathsBetweenEqCrossNodes(rest, eqCrossSet, mIn, mTIn, listAppend(paths, pathsIn), findExactlyOneLoop);
then paths;
case({},_,_,_)
then pathsIn;
end match;
end getShortPathsBetweenEqCrossNodes;
protected function connectsLoops "author:Waurich TUD 2014-02
checks if the given path connects 2 closed simple Loops"
input list<Integer> path;
input list<list<Integer>> allLoops;
output Boolean connected;
protected
Boolean b1, b2;
Integer startNode, endNode;
list<list<Integer>> loops1, loops2;
algorithm
startNode := listHead(path);
endNode := List.last(path);
// the startNode is connected to a loop
loops1 := List.filter1OnTrue(allLoops,firstInListIsEqual,startNode);
loops2 := List.filter1OnTrue(allLoops,lastInListIsEqual,startNode);
b1 := (not listEmpty(loops1)) or (not listEmpty(loops2));
// the endNode is connected to a loop
loops1 := List.filter1OnTrue(allLoops,firstInListIsEqual,endNode);
loops2 := List.filter1OnTrue(allLoops,lastInListIsEqual,endNode);
b2 := (not listEmpty(loops1)) or (not listEmpty(loops2));
connected := b1 and b2;
end connectsLoops;
protected function connectPathsToOneLoop "author:Waurich TUD 2014-02
tries to connect various paths to one closed, simple loop"
input list<list<Integer>> allPathsIn;
input list<Integer> loopIn;
output list<Integer> loopOut;
algorithm
loopOut := matchcontinue(allPathsIn,loopIn)
local
Integer startNode, endNode, startNode1, endNode1;
list<Integer> path, nextPath, restPath;
list<list<Integer>> rest, nextPaths1, nextPaths2;
case(_,startNode::path)
equation
endNode = List.last(path);
true = intEq(startNode,endNode);
then
path;
case(_,startNode::_)
equation
// TODO: This makes a list of all matching paths when it seems to really
// only need the first matching. Same in the case below.
nextPaths1 = List.filter1OnTrue(allPathsIn, firstInListIsEqual, startNode);
nextPaths2 = List.filter1OnTrue(allPathsIn, lastInListIsEqual, startNode);
nextPaths2 = listAppend(nextPaths1,nextPaths2);
nextPath = listHead(nextPaths2);
rest = List.deleteMember(allPathsIn,nextPath);
nextPath = List.deleteMember(nextPath,startNode);
path = listAppend(nextPath,loopIn);
path = connectPathsToOneLoop(rest,path);
then
path;
case(path::rest,{})
equation
startNode::restPath = path;
nextPaths1 = List.filter1OnTrue(rest, firstInListIsEqual, startNode);
nextPaths2 = List.filter1OnTrue(rest, lastInListIsEqual, startNode);
nextPaths2 = listAppend(nextPaths1,nextPaths2);
nextPath = listHead(nextPaths2);
rest = List.deleteMember(rest,nextPath);
path = listAppend(nextPath,restPath);
path = connectPathsToOneLoop(rest,path);
then
path;
else
equation
then
{};
end matchcontinue;
end connectPathsToOneLoop;
protected function resolveLoops_resolveAndReplace "author:Waurich TUD 2014-01
resolves a singleLoop. depending on whether there are only eqCrossNodes, varCrossNodes, both or none."
input list<list<Integer>> loopsIn;
input list<Integer> eqCrossLstIn;
input list<Integer> varCrossLstIn;
input BackendDAE.AdjacencyMatrix mIn;
input BackendDAE.AdjacencyMatrixT mTIn;
input array<Integer> eqMap;
input array<Integer> varMap;
input BackendDAE.EquationArray daeEqsIn;
input BackendDAE.Variables daeVarsIn;
input list<Integer> replEqsIn;
output BackendDAE.EquationArray daeEqsOut;
output list<Integer> replEqsOut;
algorithm
(daeEqsOut,replEqsOut) := matchcontinue(loopsIn,eqCrossLstIn,varCrossLstIn,mIn,mTIn,eqMap,varMap,daeEqsIn,daeVarsIn,replEqsIn)
local
Integer pos,crossEq,crossVar,eq1,eq2;
list<Integer> loop1, eqs, vars, crossEqs, crossEqs2, removeCrossEqs, crossVars, replEqs, loopVars, adjVars;
list<list<Integer>> rest, eqVars;
BackendDAE.Equation resolvedEq;
BackendDAE.EquationArray daeEqs;
case({},_,_,_,_,_,_,_,_,_)
equation
then
(daeEqsIn,replEqsIn);
case(loop1::rest,_::crossEqs,{},_,_,_,_,_,_,_)
equation
// only eqCrossNodes
//print("only eqCrossNodes\n");
loop1 = List.unique(loop1);
resolvedEq = resolveClosedLoop(loop1,mIn,mTIn,eqMap,varMap,daeEqsIn,daeVarsIn);
// get the equation that will be replaced and the rest
(crossEqs,eqs,_) = List.intersection1OnTrue(loop1,eqCrossLstIn,intEq); // replace a crossEq in the loop
replEqs = List.intersectionOnTrue(replEqsIn,loop1,intEq); // just consider the already replaced equations in this loop
// first try to replace a non cross node, otherwise an already replaced eq, or if none of them is available take a crossnode (THIS IS NOT YET CLEAR)
if not listEmpty(eqs) then
pos = listHead(eqs);
elseif not listEmpty(replEqs) then
pos = listHead(replEqs);
elseif not listEmpty(crossEqs) then
pos = listHead(crossEqs);
else
pos = -1;
end if;
eqs = List.deleteMember(loop1,pos);
//print("contract eqs: "+stringDelimitList(List.map(eqs,intString),",")+" to eq "+intString(pos)+"\n");
// get the corresponding vars
eqVars = List.map1(loop1,Array.getIndexFirst,mIn);
vars = List.flatten(eqVars);
loopVars = doubleEntriesInLst(vars,{},{}); // the vars in the loop
(_,adjVars,_) = List.intersection1OnTrue(vars,loopVars,intEq); // the vars adjacent to the loop
// update adjacencyMatrix
List.map2_0(loopVars,Array.updateIndexFirst,{},mTIn); //delete the vars in the loop
List.map2_0(adjVars,arrayGetDeleteInLst,loop1,mTIn); // remove the loop eqs from the adjacent vars
List.map2_0(adjVars,arrayGetAppendLst,{pos},mTIn); // redirect the adjacent vars to the replaced eq
List.map2_0(loop1,Array.updateIndexFirst,{},mIn); //delete the eqs in the loop
arrayUpdate(mIn,pos,adjVars); // redirect the replaced equation to the vars outside of the loops
// update remaining paths
rest = List.map2(rest,replaceContractedNodes,pos,eqs);
rest = List.unique(rest);
//print("the remaining paths: "+stringDelimitList(List.map(rest,HpcOmTaskGraph.intLstString),"\n")+"\n\n");
// replace Equation
//print("replace equation "+intString(pos)+"\n");
replEqs = pos::replEqsIn;
pos = arrayGet(eqMap,pos);
daeEqs = BackendEquation.setAtIndex(daeEqsIn,pos,resolvedEq);
(daeEqs,replEqs) = resolveLoops_resolveAndReplace(rest,eqCrossLstIn,varCrossLstIn,mIn,mTIn,eqMap,varMap,daeEqs,daeVarsIn,replEqs);
then
(daeEqs,replEqs);
case(loop1::rest,{},_::crossVars,_,_,_,_,_,_,_)
equation
// only varCrossNodes
//print("only varCrossNodes\n");
loop1 = List.unique(loop1);
resolvedEq = resolveClosedLoop(loop1,mIn,mTIn,eqMap,varMap,daeEqsIn,daeVarsIn);
// get the equation that will be replaced and the rest
(replEqs,_,eqs) = List.intersection1OnTrue(replEqsIn,loop1,intEq); // just consider the already replaced equations in this loop
//priorize the not yet replaced equations
eqs = priorizeEqsWithVarCrosses(eqs,mIn,varCrossLstIn);
//print("priorized eqs: "+stringDelimitList(List.map(eqs,intString),",")+"\n");
// first try to replace a non cross node, otherwise an already replaced eq
pos = if not listEmpty(replEqs) then listHead(replEqs) else -1;
pos = if not listEmpty(eqs) then listHead(eqs) else pos;
eqs = List.deleteMember(loop1,pos);
//print("contract eqs: "+stringDelimitList(List.map(eqs,intString),",")+" to eq "+intString(pos)+"\n");
// get the corresponding vars
eqVars = List.map1(loop1,Array.getIndexFirst,mIn);
vars = List.flatten(eqVars);
loopVars = doubleEntriesInLst(vars,{},{}); // the vars in the loop
(crossVars,loopVars,_) = List.intersection1OnTrue(loopVars,varCrossLstIn,intEq); // some crossVars have to remain
//print("loopVars: "+stringDelimitList(List.map(loopVars,intString),",")+"\n");
(_,adjVars,_) = List.intersection1OnTrue(vars,loopVars,intEq); // the vars adjacent to the loop
adjVars = listAppend(crossVars,adjVars);
adjVars = List.unique(adjVars);
// update adjacencyMatrix
List.map2_0(loopVars,Array.updateIndexFirst,{},mTIn); //delete the vars in the loop
List.map2_0(adjVars,arrayGetDeleteInLst,loop1,mTIn); // remove the loop eqs from the adjacent vars
List.map2_0(adjVars,arrayGetAppendLst,{pos},mTIn); // redirect the adjacent vars to the replaced eq
List.map2_0(loop1,Array.updateIndexFirst,{},mIn); //delete the eqs in the loop
arrayUpdate(mIn,pos,adjVars); // redirect the replaced equation to the vars outside of the loops
// update remaining paths
rest = List.map2(rest,replaceContractedNodes,pos,eqs);
rest = List.unique(rest);
//print("the remaining paths: "+stringDelimitList(List.map(rest,HpcOmTaskGraph.intLstString),"\n")+"\n\n");
// replace Equation
//print("replace equation "+intString(pos)+"\n");
replEqs = pos::replEqsIn;
pos = arrayGet(eqMap,pos);
daeEqs = BackendEquation.setAtIndex(daeEqsIn,pos,resolvedEq);
(daeEqs,replEqs) = resolveLoops_resolveAndReplace(rest,eqCrossLstIn,varCrossLstIn,mIn,mTIn,eqMap,varMap,daeEqs,daeVarsIn,replEqs);
then
(daeEqs,replEqs);
case(loop1::rest,{},{},_,_,_,_,_,_,_)
equation
// single Loop
loop1 = List.unique(loop1);
//print("single loop\n");
resolvedEq = resolveClosedLoop(loop1,mIn,mTIn,eqMap,varMap,daeEqsIn,daeVarsIn);
// update AdjacencyMatrix
(_,crossEqs,_) = List.intersection1OnTrue(loop1,replEqsIn,intEq); // do not replace an already replaced Eq
(pos::_) = crossEqs; // the equation that will be replaced = pos
eqVars = List.map1(loop1,Array.getIndexFirst,mIn);
vars = List.flatten(eqVars);
//print("delete vars: "+stringDelimitList(List.map(vars,intString),",")+" in the eqs: "+stringDelimitList(List.map(crossEqs,intString),",")+"\n");
List.map2_0(loop1,Array.updateIndexFirst,{},mIn); //delete the equations in the loop
List.map2_0(vars,Array.updateIndexFirst,{},mTIn); //delete the vars from the loop
// replace Equation
//print("replace equation "+intString(pos)+"\n");
replEqs = pos::replEqsIn;
pos = arrayGet(eqMap,pos);
daeEqs = BackendEquation.setAtIndex(daeEqsIn,pos,resolvedEq);
(daeEqs,replEqs) = resolveLoops_resolveAndReplace(rest,eqCrossLstIn,varCrossLstIn,mIn,mTIn,eqMap,varMap,daeEqs,daeVarsIn,replEqs);
then
(daeEqs,replEqs);
case(loop1::rest,_::_,_::_,_,_,_,_,_,_,_)
algorithm
// both eqCrossNodes and varCrossNodes, at least try the small loops
//print("both eqCrossNodes and varCrossNodes, loopLength"+intString(listLength(loop1))+"\n");
loop1 := List.unique(loop1);
true := listLength(loop1) == 2;
resolvedEq := resolveClosedLoop(loop1,mIn,mTIn,eqMap,varMap,daeEqsIn,daeVarsIn);