/
SymbolicJacobian.mo
3567 lines (3190 loc) · 152 KB
/
SymbolicJacobian.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 SymbolicJacobian
" file: SymbolicJacobian.mo
package: SymbolicJacobian
description: This package contains stuff that is related to symbolic jacobian or sparsity structure.
RCS: $Id$"
public import Absyn;
public import BackendDAE;
public import DAE;
public import FCore;
public import FGraph;
protected import Array;
protected import BackendDAEOptimize;
protected import BackendDAETransform;
protected import BackendDAEUtil;
protected import BackendDump;
protected import BackendEquation;
protected import BackendVariable;
protected import BackendVarTransform;
protected import BaseHashSet;
protected import Ceval;
protected import ClockIndexes;
protected import Config;
protected import ComponentReference;
protected import DAEUtil;
protected import Debug;
protected import Differentiate;
protected import DynamicOptimization;
protected import Expression;
protected import ExpressionDump;
protected import ExpressionSimplify;
protected import Error;
protected import Flags;
protected import Global;
protected import Graph;
protected import HashSet;
protected import IndexReduction;
protected import List;
protected import SimCodeFunctionUtil;
protected import System;
protected import Util;
protected import Values;
protected import ValuesUtil;
// =============================================================================
// section for postOptModule >>calculateStateSetsJacobians<<
//
// =============================================================================
public function calculateStateSetsJacobians "author: wbraun
Calculates the Jacobian matrix with directional derivative method for dynamic
state selection."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
outDAE := BackendDAEUtil.mapEqSystem(inDAE, calculateEqSystemStateSetsJacobians);
end calculateStateSetsJacobians;
// =============================================================================
// section for postOptModule >>calculateStrongComponentJacobians<<
//
// Module for to calculate strong component Jacobian matrices
// =============================================================================
public function calculateStrongComponentJacobians "author: wbraun
Calculates Jacobian matrix with directional derivative method for each SCC."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
try
outDAE := BackendDAEUtil.mapEqSystem(inDAE, calculateEqSystemJacobians);
else
outDAE := inDAE;
end try;
end calculateStrongComponentJacobians;
// =============================================================================
// section for postOptModule >>constantLinearSystem<<
//
// constant Jacobian matrices. Linear system of equations (A x = b) where
// A and b are constant.
// =============================================================================
public function constantLinearSystem
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
(outDAE, _) := BackendDAEUtil.mapEqSystemAndFold(inDAE, constantLinearSystem0, (false,1));
end constantLinearSystem;
// =============================================================================
// section for postOptModule >>detectSparsePatternODE<<
//
// Generate sparse pattern
// =============================================================================
public function detectSparsePatternODE
input BackendDAE.BackendDAE inBackendDAE;
output BackendDAE.BackendDAE outBackendDAE;
protected
BackendDAE.BackendDAE DAE;
BackendDAE.EqSystems eqs;
BackendDAE.Shared shared;
BackendDAE.SparseColoring coloredCols;
BackendDAE.SparsePattern sparsePattern;
list<BackendDAE.Var> states;
BackendDAE.Var dummyVar;
BackendDAE.Variables v;
algorithm
// lochel: This module fails for some models (e.g. #3543)
try
BackendDAE.DAE(eqs = eqs) := inBackendDAE;
// prepare a DAE
DAE := BackendDAEUtil.copyBackendDAE(inBackendDAE);
DAE := BackendDAEOptimize.collapseIndependentBlocks(DAE);
DAE := BackendDAEUtil.transformBackendDAE(DAE, SOME((BackendDAE.NO_INDEX_REDUCTION(), BackendDAE.EXACT())), NONE(), NONE());
// get states for DAE
BackendDAE.DAE(eqs = {BackendDAE.EQSYSTEM(orderedVars = v)}, shared=shared) := DAE;
states := BackendVariable.getAllStateVarFromVariables(v);
// generate sparse pattern
(sparsePattern, coloredCols) := generateSparsePattern(DAE, states, states);
shared := addBackendDAESharedJacobianSparsePattern(sparsePattern, coloredCols, BackendDAE.SymbolicJacobianAIndex, shared);
outBackendDAE := BackendDAE.DAE(eqs, shared);
else
// skip this optimization module
Error.addCompilerWarning("The optimization module detectJacobianSparsePattern failed. This module will be skipped and the transformation process continued.");
outBackendDAE := inBackendDAE;
end try;
end detectSparsePatternODE;
// =============================================================================
// section for postOptModule >>generateSymbolicJacobianPast<<
//
// Symbolic Jacobian subsection
// =============================================================================
public function generateSymbolicJacobianPast
input BackendDAE.BackendDAE inBackendDAE;
output BackendDAE.BackendDAE outBackendDAE;
protected
BackendDAE.EqSystems eqs;
BackendDAE.Shared shared;
BackendDAE.SymbolicJacobian symJacA;
BackendDAE.SparsePattern sparsePattern;
BackendDAE.SparseColoring sparseColoring;
DAE.FunctionTree funcs, functionTree;
algorithm
System.realtimeTick(ClockIndexes.RT_CLOCK_EXECSTAT_JACOBIANS);
BackendDAE.DAE(eqs=eqs,shared=shared) := inBackendDAE;
(symJacA , sparsePattern, sparseColoring, funcs) := createSymbolicJacobianforStates(inBackendDAE);
shared := addBackendDAESharedJacobian(symJacA, sparsePattern, sparseColoring, shared);
functionTree := BackendDAEUtil.getFunctions(shared);
functionTree := DAEUtil.joinAvlTrees(functionTree, funcs);
shared := BackendDAEUtil.setSharedFunctionTree(shared, functionTree);
outBackendDAE := BackendDAE.DAE(eqs,shared);
System.realtimeTock(ClockIndexes.RT_CLOCK_EXECSTAT_JACOBIANS);
end generateSymbolicJacobianPast;
protected function createSymbolicJacobianforStates "author: wbraun
all functionODE equation are differentiated with respect to the states."
input BackendDAE.BackendDAE inBackendDAE;
output BackendDAE.SymbolicJacobian outJacobian;
output BackendDAE.SparsePattern outSparsePattern;
output BackendDAE.SparseColoring outSparseColoring;
output DAE.FunctionTree outFunctionTree;
protected
BackendDAE.BackendDAE backendDAE2;
list<BackendDAE.Var> varlst, knvarlst, states, inputvars, paramvars;
BackendDAE.Variables v, kv;
algorithm
if Flags.isSet(Flags.JAC_DUMP2) then
print("analytical Jacobians -> start generate system for matrix A time : " + realString(clock()) + "\n");
end if;
backendDAE2 := BackendDAEUtil.copyBackendDAE(inBackendDAE);
backendDAE2 := BackendDAEOptimize.collapseIndependentBlocks(backendDAE2);
backendDAE2 := BackendDAEUtil.transformBackendDAE(backendDAE2,SOME((BackendDAE.NO_INDEX_REDUCTION(),BackendDAE.EXACT())),NONE(),NONE());
BackendDAE.DAE({BackendDAE.EQSYSTEM(orderedVars = v)},BackendDAE.SHARED(knownVars = kv)) := backendDAE2;
// Prepare all needed variables
varlst := BackendVariable.varList(v);
_ := List.map(varlst,BackendVariable.varCref);
knvarlst := BackendVariable.varList(kv);
_ := List.map(knvarlst,BackendVariable.varCref);
states := BackendVariable.getAllStateVarFromVariables(v);
inputvars := List.select(knvarlst,BackendVariable.isInput);
paramvars := List.select(knvarlst, BackendVariable.isParam);
if Flags.isSet(Flags.JAC_DUMP2) then
print("analytical Jacobians -> prepared vars for symbolic matrix A time: " + realString(clock()) + "\n");
end if;
if Flags.isSet(Flags.JAC_DUMP2) then
BackendDump.bltdump("System to create symbolic jacobian of: ",backendDAE2);
end if;
(outJacobian, outSparsePattern, outSparseColoring, outFunctionTree) := createJacobian(backendDAE2,states,BackendVariable.listVar1(states),BackendVariable.listVar1(inputvars),BackendVariable.listVar1(paramvars),BackendVariable.listVar1(states),varlst,"A");
end createSymbolicJacobianforStates;
// =============================================================================
// section for postOptModule >>generateSymbolicLinearizationPast<<
//
// =============================================================================
public function generateSymbolicLinearizationPast
input BackendDAE.BackendDAE inBackendDAE;
output BackendDAE.BackendDAE outBackendDAE;
algorithm
outBackendDAE := matchcontinue(inBackendDAE)
local
BackendDAE.EqSystems eqs;
BackendDAE.Shared shared;
BackendDAE.SymbolicJacobians linearModelMatrixes;
DAE.FunctionTree funcs, functionTree;
list< .DAE.Constraint> constraints;
case(_) equation
true = Flags.getConfigBool(Flags.GENERATE_SYMBOLIC_LINEARIZATION);
System.realtimeTick(ClockIndexes.RT_CLOCK_EXECSTAT_JACOBIANS);
BackendDAE.DAE(eqs=eqs,shared=shared) = inBackendDAE;
(linearModelMatrixes, funcs) = createLinearModelMatrixes(inBackendDAE, Config.acceptOptimicaGrammar(), Flags.isSet(Flags.DIS_SYMJAC_FMI20));
shared = BackendDAEUtil.setSharedSymJacs(shared, linearModelMatrixes);
functionTree = BackendDAEUtil.getFunctions(shared);
functionTree = DAEUtil.joinAvlTrees(functionTree, funcs);
shared = BackendDAEUtil.setSharedFunctionTree(shared, functionTree);
outBackendDAE = BackendDAE.DAE(eqs,shared);
_ = System.realtimeTock(ClockIndexes.RT_CLOCK_EXECSTAT_JACOBIANS);
then outBackendDAE;
else inBackendDAE;
end matchcontinue;
end generateSymbolicLinearizationPast;
// =============================================================================
// section for postOptModule >>inputDerivativesUsed<<
//
// check for derivatives of inputs
// =============================================================================
public function inputDerivativesUsed "author: Frenkel TUD 2012-10
checks if der(input) is used and report a warning/error."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
(outDAE, _) := BackendDAEUtil.mapEqSystemAndFold(inDAE, inputDerivativesUsedWork, false);
end inputDerivativesUsed;
protected function inputDerivativesUsedWork "author: Frenkel TUD 2012-10"
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared inShared;
input Boolean inChanged;
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared outShared = inShared "unused";
output Boolean outChanged;
algorithm
(osyst, outChanged) := matchcontinue(isyst)
local
BackendDAE.EquationArray orderedEqs;
list<DAE.Exp> explst;
String s;
case BackendDAE.EQSYSTEM(orderedEqs=orderedEqs) equation
((_, explst as _::_)) = BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(orderedEqs, traverserinputDerivativesUsed, (BackendVariable.daeKnVars(inShared), {}));
s = stringDelimitList(List.map(explst, ExpressionDump.printExpStr), "\n");
Error.addMessage(Error.DERIVATIVE_INPUT, {s});
then (BackendDAEUtil.setEqSystEqs(isyst, orderedEqs), true);
else (isyst, inChanged);
end matchcontinue;
end inputDerivativesUsedWork;
protected function traverserinputDerivativesUsed "author: Frenkel TUD 2012-10"
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,list<DAE.Exp>> itpl;
output DAE.Exp e;
output tuple<BackendDAE.Variables,list<DAE.Exp>> tpl;
algorithm
(e,tpl) := Expression.traverseExpTopDown(inExp,traverserExpinputDerivativesUsed,itpl);
end traverserinputDerivativesUsed;
protected function traverserExpinputDerivativesUsed
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,list<DAE.Exp>> tpl;
output DAE.Exp outExp;
output Boolean cont;
output tuple<BackendDAE.Variables,list<DAE.Exp>> outTpl;
algorithm
(outExp,cont,outTpl) := matchcontinue (inExp,tpl)
local
BackendDAE.Variables vars;
DAE.Type tp;
DAE.Exp e;
DAE.ComponentRef cr;
BackendDAE.Var var;
list<DAE.Exp> explst;
case (e as DAE.CALL(path=Absyn.IDENT(name = "der"),expLst={DAE.CALL(path=Absyn.IDENT(name = "der"),expLst={DAE.CREF(componentRef=cr)})}),(vars,explst))
equation
(var::{},_) = BackendVariable.getVar(cr, vars);
true = BackendVariable.isVarOnTopLevelAndInput(var);
then (e,false,(vars,e::explst));
case (e as DAE.CALL(path=Absyn.IDENT(name = "der"),expLst={DAE.CREF(componentRef=cr)}),(vars,explst))
equation
(var::{},_) = BackendVariable.getVar(cr, vars);
true = BackendVariable.isVarOnTopLevelAndInput(var);
then (e,false,(vars,e::explst));
else (inExp,true,tpl);
end matchcontinue;
end traverserExpinputDerivativesUsed;
// =============================================================================
// solve linear systems with constant jacobian and variable b-Vector
//
// =============================================================================
protected function jacobianIsConstant
input list<tuple<Integer, Integer, BackendDAE.Equation>> jac;
output Boolean isConst;
protected
list<BackendDAE.Equation> eqs;
list<DAE.Exp> exps;
algorithm
eqs := List.map(jac, Util.tuple33);
isConst := not List.exist(eqs, variableResidual);
end jacobianIsConstant;
protected function variableResidual
input BackendDAE.Equation eq;
output Boolean isNotConst;
algorithm
isNotConst := match(eq)
case BackendDAE.RESIDUAL_EQUATION(exp=DAE.RCONST(_))
then false;
else true;
end match;
end variableResidual;
protected function replaceStrongComponent "replaces the indexed component with compsNew and adds compsAdd at the end. the assignments will be updated"
input BackendDAE.EqSystem systIn;
input Integer idx;
input BackendDAE.StrongComponents compsNew;
input BackendDAE.StrongComponents compsAdd;
output BackendDAE.EqSystem systOut = systIn;
protected
BackendDAE.Variables orderedVars;
BackendDAE.EquationArray orderedEqs;
BackendDAE.Matching matching;
array<Integer> ass1, ass2, ass1add, ass2add;
BackendDAE.StrongComponents comps;
algorithm
BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(ass1=ass1, ass2=ass2, comps=comps)) := systIn;
if not listEmpty(compsAdd) then
ass1add := arrayCreate(listLength(compsAdd), 0);
ass2add := arrayCreate(listLength(compsAdd), 0);
ass1 := arrayAppend(ass1, ass1add);
ass2 := arrayAppend(ass2, ass1add);
List.map2_0(compsAdd, updateAssignment, ass1, ass2);
end if;
List.map2_0(compsNew, updateAssignment, ass1, ass2);
comps := List.replaceAtWithList(compsNew, idx-1, comps);
comps := listAppend(comps, compsAdd);
systOut.matching := BackendDAE.MATCHING(ass1, ass2, comps);
systOut := BackendDAEUtil.setEqSystMatrices(systOut);
end replaceStrongComponent;
protected function updateAssignment
input BackendDAE.StrongComponent comp;
input array<Integer> ass1;
input array<Integer> ass2;
algorithm
_ := matchcontinue(comp,ass1,ass2)
local
Integer eq,var;
case(BackendDAE.SINGLEEQUATION(eqn=eq,var=var),_,_)
equation
arrayUpdate(ass2,eq,var);
arrayUpdate(ass1,var,eq);
then ();
else
then ();
end matchcontinue;
end updateAssignment;
protected function solveConstJacLinearSystem
input BackendDAE.EqSystem syst;
input BackendDAE.Shared ishared;
input list<BackendDAE.Equation> eqn_lst;
input list<Integer> eqn_indxs;
input list<BackendDAE.Var> var_lst;
input list<Integer> var_indxs;
input list<tuple<Integer, Integer, BackendDAE.Equation>> jac;
input Integer sysIdxIn;
input Integer compIdxIn;
output list<BackendDAE.Equation> sysEqsOut;
output list<BackendDAE.Equation> bEqsOut;
output list<BackendDAE.Var> bVarsOut;
output array<Integer> orderOut;
output Integer sysIdxOut;
protected
BackendDAE.Variables vars,vars1,v;
BackendDAE.EquationArray eqns,eqns1, eqns2;
list<DAE.Exp> beqs;
list<DAE.ElementSource> sources;
list<list<Real>> jacVals;
BackendDAE.Matching matching;
DAE.FunctionTree funcs;
BackendDAE.Shared shared;
BackendDAE.StateSets stateSets;
BackendDAE.BaseClockPartitionKind partitionKind;
array<Real> A,b;
Real entry;
Integer row,col,n, systIdx;
array<Integer> order;
algorithm
BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=matching,stateSets=stateSets,partitionKind=partitionKind) := syst;
BackendDAE.SHARED(functionTree=funcs) := ishared;
eqns1 := BackendEquation.listEquation(eqn_lst);
v := BackendVariable.listVar1(var_lst);
n := listLength(var_lst);
(beqs,sources) := BackendDAEUtil.getEqnSysRhs(eqns1,v,SOME(funcs));
beqs := listReverse(beqs);
//print("bside: \n"+ExpressionDump.printExpListStr(beqs)+"\n");
jacVals := evaluateConstantJacobian(listLength(var_lst),jac);
//print("JacVals\n"+stringDelimitList(List.map(jacVals,rListStr),"\n")+"\n\n");
A := arrayCreate(n*n,0.0);
b := arrayCreate(n*n,0.0); // i.e. a matrix for the b-vars to get their coefficients independently [(b1,0,0);(0,b2,0),(0,0,b3)]
order := listArray(List.fill(0,n));
for row in 1:n loop
for col in 1:n loop
entry := listGet(listGet(jacVals,row),col);
arrayUpdate(A,((row-1)*n+col),entry);
end for;
arrayUpdate(b,(row-1)*n+row,1.0);
end for;
//print("b\n"+stringDelimitList(List.map(arrayList(b),realString),", ")+"\n\n");
//print("A\n"+stringDelimitList(List.map(arrayList(A),realString),", ")+"\n\n");
gauss(A,b,1,n,List.intRange(n),order);
//print("the order: "+stringDelimitList(List.map(arrayList(order),intString),",")+"\n");
(bVarsOut,bEqsOut) := createBVecVars(sysIdxIn,compIdxIn,n,DAE.T_REAL_DEFAULT,beqs);
sysEqsOut := createSysEquations(A,b,n,order,var_lst,bVarsOut);
sysIdxOut := sysIdxIn+1;
orderOut := order;
end solveConstJacLinearSystem;
protected function createSysEquations "creates new equations for a linear system with constant Jacobian matrix.
author: Waurich TUD 2015-03"
input array<Real> A;
input array<Real> b;
input Integer n;
input array<Integer> order;
input list<BackendDAE.Var> xVars;
input list<BackendDAE.Var> bVars;
output list<BackendDAE.Equation> sysEqs = {};
protected
Integer i;
Integer row;
DAE.Exp lhs, rhs;
list<DAE.Exp> exps, coeffExps, xExps, bExps, xProds, bProds;
list<Real> coeffs;
BackendDAE.Equation eq;
algorithm
xExps := List.map(xVars, BackendVariable.varExp2);
bExps := List.map(bVars, BackendVariable.varExp2);
for i in 1:n loop
row := arrayGet(order,i);
coeffs := Array.getRange((row-1)*n+1,(row*n),A);
coeffExps := List.map(coeffs,Expression.makeRealExp);
xProds := List.threadMap1(coeffExps,xExps,makeBinaryExp,DAE.MUL(DAE.T_REAL_DEFAULT));
lhs := List.fold1(xProds,Expression.makeBinaryExp,DAE.ADD(DAE.T_REAL_DEFAULT),DAE.RCONST(0.0));
(lhs,_) := ExpressionSimplify.simplify(lhs);
coeffs := Array.getRange((row-1)*n+1,(row*n),b);
coeffExps := List.map(coeffs,Expression.makeRealExp);
bProds := List.threadMap1(coeffExps,bExps,makeBinaryExp,DAE.MUL(DAE.T_REAL_DEFAULT));
rhs := List.fold1(bProds,Expression.makeBinaryExp,DAE.ADD(DAE.T_REAL_DEFAULT),DAE.RCONST(0.0));
(rhs,_) := ExpressionSimplify.simplify(rhs);
eq := BackendDAE.EQUATION(lhs,rhs,DAE.emptyElementSource,BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
sysEqs := eq::sysEqs;
end for;
end createSysEquations;
public function makeBinaryExp
input DAE.Exp inLhs;
input DAE.Exp inRhs;
input DAE.Operator inOp;
output DAE.Exp outExp;
algorithm
outExp := DAE.BINARY(inLhs, inOp, inRhs);
end makeBinaryExp;
protected function createBVecVars "creates variables for the b-Vector of a linear system with constant Jacobian
author:Waurich TUD 2015-03"
input Integer sysIdx;
input Integer compIdx;
input Integer size;
input DAE.Type typ;
input list<DAE.Exp> bExps;
output list<BackendDAE.Var> varLst = {};
output list<BackendDAE.Equation> eqLst = {};
protected
String ident;
Integer i;
DAE.ComponentRef cref;
BackendDAE.Var var;
BackendDAE.Equation beq;
algorithm
for i in 1:size loop
ident := "$sys"+intString(sysIdx)+"_"+intString(compIdx)+"_b"+intString(i);
cref := ComponentReference.makeCrefIdent(ident,typ,{});
var := BackendVariable.makeVar(cref);
varLst := var::varLst;
beq := BackendDAE.EQUATION(listGet(bExps,i),Expression.crefExp(cref),DAE.emptyElementSource,BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
eqLst := beq::eqLst;
end for;
end createBVecVars;
protected function gauss
input array<Real> A;
input array<Real> b;
input Integer indxIn;
input Integer n;
input list<Integer> rangeIn;
input array<Integer> permutation;
protected
Integer pivotIdx,pos, ir, ic, p_ir;// ir=rowIdx, ic=columnIdx, p_ir=permuted row idx
Real pivot, entry, pr_entry, b_entry, first;
list<Integer> range;
algorithm
_ := matchcontinue(A,b,indxIn,n,rangeIn,permutation)
case(_,_,_,_,_,_)
algorithm
true := intLe(indxIn,n);
(pivotIdx,pivot) := getPivotElement(A,rangeIn,indxIn,n);
//print("pivot: "+intString(pivotIdx)+" has value: "+realString(pivot)+"\n");
arrayUpdate(permutation,indxIn,pivotIdx);
range := List.deleteMember(rangeIn,pivotIdx);
// the pivot row in the A-matrix divided by the pivot element
for ic in indxIn:n loop
pos := (pivotIdx-1)*n+ic;
entry := arrayGet(A,pos);
entry := realDiv(entry,pivot); //divide column entry with pivot element
//print(" pos "+intString(pos)+" entry "+realString(arrayGet(A,pos))+"\n");
arrayUpdate(A,pos,entry);
end for;
// the complete pivot row of the b-vector divided by the pivot element
for ic in 1:n loop
pos := (pivotIdx-1)*n+ic;
b_entry := arrayGet(b,pos);
b_entry := realDiv(b_entry,pivot);
arrayUpdate(b,pos,b_entry);
end for;
// the remaining rows
for ir in range loop
first := arrayGet(A,(ir-1)*n+indxIn); //the first row element, that is going to be zero
//print("first "+realString(first)+"\n");
for ic in indxIn:n loop
pos := (ir-1)*n+ic;
entry := arrayGet(A,pos); // the current entry
pivot := arrayGet(A,(pivotIdx-1)*n+ic); // the element from the column in the pivot row
//print("pivot "+realString(pivot)+"\n");
//print("ir "+intString(ir)+" pos "+intString(pos)+" entry0 "+realString(entry)+" entry1 "+realString(realSub(entry,realDiv(first,pivot)))+"\n");
entry := realSub(entry,realMul(first,pivot));
arrayUpdate(A,pos,entry);
b_entry := arrayGet(b,pos);
pivot := arrayGet(b,(pivotIdx-1)*n+ic);
b_entry := b_entry - realMul(first,pivot);
arrayUpdate(b,pos,b_entry);
end for;
end for;
//print("A\n"+stringDelimitList(List.map(arrayList(A),realString),", ")+"\n\n");
//print("b\n"+stringDelimitList(List.map(arrayList(b),realString),", ")+"\n\n");
//print("new permutation: "+stringDelimitList(List.map(arrayList(permutation),intString),",")+"\n");
//print("JACB "+intString(indxIn)+" \n"+stringDelimitList(List.map(arrayList(jacB),rListStr),"\n ")+"\n\n");
gauss(A,b,indxIn+1,n,range,permutation);
then();
else ();
end matchcontinue;
end gauss;
protected function getPivotElement "gets the highest element in the startIdx'th to n'th rows and the startidx'th column"
input array<Real> A;
input list<Integer> rangeIn;
input Integer startIdx;
input Integer n;
output Integer pos = 0;
output Real value = 0.0;
protected
Integer i;
Real entry;
algorithm
for i in rangeIn loop
entry := arrayGet(A,(i-1)*n+startIdx);
//print("i "+intString(i)+" pi "+intString(p_i)+" entry "+realString(entry)+"\n");
if realAbs(entry) > value then
value := entry;
pos := i;
end if;
end for;
end getPivotElement;
protected function rListStr
input list<Real> l;
output String s;
algorithm
s := stringDelimitList(List.map(l,realString)," , ");
end rListStr;
// =============================================================================
// unsorted section
//
// =============================================================================
protected function constantLinearSystem0
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared inShared;
input tuple<Boolean, Integer> iTpl "<inChanged,sysIdxIn>";
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared outShared;
output tuple<Boolean,Integer> oTpl "<oChanged,sysIdxOut>";
protected
Boolean changed;
Integer sysIdx;
BackendDAE.StrongComponents comps;
algorithm
((changed,sysIdx)) := iTpl;
BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(comps=comps)) := isyst;
(osyst, outShared, changed, sysIdx) := constantLinearSystem1(isyst, inShared, comps, changed, sysIdx, 1);
osyst := constantLinearSystem2(changed, osyst);
oTpl := (changed,sysIdx+1);
end constantLinearSystem0;
protected function constantLinearSystem2
input Boolean b;
input BackendDAE.EqSystem isyst;
output BackendDAE.EqSystem osyst;
algorithm
osyst := match(b,isyst)
local
BackendDAE.Variables vars;
BackendDAE.EquationArray eqns;
BackendDAE.StateSets stateSets;
BackendDAE.BaseClockPartitionKind partitionKind;
case (false,_) then isyst;
// case (true,BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=BackendDAE.NO_MATCHING()))
case (true,BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqns, stateSets=stateSets, partitionKind=partitionKind))
equation
// remove empty entries from vars/eqns
vars = BackendVariable.listVar1(BackendVariable.varList(vars));
eqns = BackendEquation.listEquation(BackendEquation.equationList(eqns));
then
BackendDAEUtil.createEqSystem(vars, eqns, stateSets, partitionKind);
/* case (true,BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=BackendDAE.MATCHING(ass1=ass1,ass2=ass2,comps=comps)))
then
updateEquationSystemMatching(vars,eqns,ass1,ass2,comps);
*/ end match;
end constantLinearSystem2;
protected function constantLinearSystem1
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input BackendDAE.StrongComponents inComps;
input Boolean inRunMatching;
input Integer sysIdxIn;
input Integer compIdxIn;
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared oshared;
output Boolean runMatching;
output Integer sysIdxOut;
algorithm
(osyst, oshared, runMatching, sysIdxOut) := match (inComps)
local
BackendDAE.StrongComponents comps;
BackendDAE.StrongComponent comp;
Boolean b;
BackendDAE.EqSystem syst;
BackendDAE.Shared shared;
Integer sysIdx, compIdx;
case {}
then (isyst, ishared, inRunMatching, sysIdxIn);
case comp::comps equation
(syst, shared, b, sysIdx, compIdx) = constantLinearSystemWork(isyst, ishared, comp, sysIdxIn, compIdxIn);
(syst, shared, runMatching, sysIdx) = constantLinearSystem1(syst, shared, comps, b or inRunMatching, sysIdx, compIdx);
then (syst, shared, runMatching, sysIdx);
end match;
end constantLinearSystem1;
protected function constantLinearSystemWork
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared ishared;
input BackendDAE.StrongComponent comp;
input Integer sysIdxIn;
input Integer compIdxIn;
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared oshared;
output Boolean outRunMatching;
output Integer sysIdxOut;
output Integer compIdxOut;
algorithm
(osyst, oshared, outRunMatching, sysIdxOut, compIdxOut):=
matchcontinue (isyst, ishared, comp)
local
BackendDAE.Variables vars;
BackendDAE.EquationArray eqns;
BackendDAE.StrongComponents comps;
BackendDAE.StrongComponent comp1;
Boolean b,b1;
list<BackendDAE.Equation> eqn_lst;
list<BackendDAE.Var> var_lst;
list<Integer> eindex,vindx;
list<tuple<Integer, Integer, BackendDAE.Equation>> jac;
BackendDAE.EqSystem syst;
BackendDAE.Shared shared;
Integer sysIdx;
array<Integer> order;
list<Integer> bVarIdcs,bEqIdcs;
list<BackendDAE.Var> bVars;
list<BackendDAE.Equation> bEqs,sysEqs;
BackendDAE.StrongComponents bComps,sysComps;
BackendDAE.Matching matching;
BackendDAE.StateSets stateSets;
BackendDAE.BaseClockPartitionKind partitionKind;
case (syst, shared, (BackendDAE.EQUATIONSYSTEM( eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(SOME(jac)),
jacType=BackendDAE.JAC_CONSTANT() )))
equation
//the A-matrix and the b-Vector are constant
eqn_lst = BackendEquation.getEqns(eindex, syst.orderedEqs);
var_lst = List.map1r(vindx, BackendVariable.getVarAt, syst.orderedVars);
(syst,shared) = solveLinearSystem(syst, shared, eqn_lst, eindex, var_lst, vindx, jac);
then (syst,shared,true,sysIdxIn,compIdxIn+1);
case ( syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqns), shared,
BackendDAE.EQUATIONSYSTEM( eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(SOME(jac)),
jacType=BackendDAE.JAC_LINEAR() ) )
equation
true = BackendDAEUtil.isSimulationDAE(ishared);
//only the A-matrix is constant, apply Gaussian Elimination
eqn_lst = BackendEquation.getEqns(eindex, eqns);
var_lst = List.map1r(vindx, BackendVariable.getVarAt, vars);
true = jacobianIsConstant(jac);
true = Flags.isSet(Flags.CONSTJAC);
//true = intEq(compIdxIn,37) and intEq(sysIdxIn,1);
//print("ITS CONSTANT\n");
//print("THE COMPIDX: "+intString(compIdxIn)+" THE SYSIDX"+intString(sysIdxIn)+"\n");
//BackendDump.dumpEqnsSolved2({comp},eqns,vars);
eqn_lst = BackendEquation.getEqns(eindex,eqns);
var_lst = List.map1r(vindx, BackendVariable.getVarAt, vars);
(sysEqs, bEqs, bVars, order, sysIdx) =
solveConstJacLinearSystem(syst, shared, eqn_lst, eindex, listReverse(var_lst), vindx, jac, sysIdxIn, compIdxIn);
//print("the b-vector stuff \n");
//BackendDump.printEquationList(bEqs);
//BackendDump.printVarList(bVars);
//print("the sysEqs stuff \n");
//BackendDump.printEquationList(sysEqs);
//build comps
//print("size"+intString(BackendDAEUtil.equationSize(eqns))+"\n");
//print("numberOfElement"+intString(BackendDAEUtil.equationArraySize(eqns))+"\n");
//print("arrSize"+intString(BackendDAEUtil.equationArraySize2(eqns))+"\n");
//print("length"+intString(listLength(BackendEquation.equationList(eqns)))+"\n");
bVarIdcs = List.intRange2(BackendVariable.varsSize(vars)+1, BackendVariable.varsSize(vars)+listLength(bVars));
bEqIdcs = List.intRange2(BackendDAEUtil.equationArraySize(eqns)+1, BackendDAEUtil.equationArraySize(eqns)+listLength(bEqs));
bComps = List.threadMap(bEqIdcs, bVarIdcs, BackendDAEUtil.makeSingleEquationComp);
sysComps = List.threadMap( List.map1(arrayList(order), List.getIndexFirst, eindex), listReverse(vindx),
BackendDAEUtil.makeSingleEquationComp );
//print("bCOMPS\n");
//BackendDump.dumpComponents(bComps);
//print("SYSCOMPS\n");
//BackendDump.dumpComponents(sysComps);
//build system
syst.orderedVars = List.fold(bVars, BackendVariable.addVar, vars);
eqns = List.fold(bEqs, BackendEquation.addEquation, eqns);
syst.orderedEqs = List.threadFold(eindex, sysEqs, BackendEquation.setAtIndexFirst, eqns);
syst = BackendDAEUtil.setEqSystMatrices(syst);
syst = replaceStrongComponent(syst,compIdxIn,sysComps,bComps);
//print("compIdxIn"+intString(compIdxIn)+"\n");
then (syst, ishared, false, sysIdx, compIdxIn+listLength(sysComps));
else (isyst, ishared, false, sysIdxIn, compIdxIn+1);
end matchcontinue;
end constantLinearSystemWork;
protected function solveLinearSystem
input BackendDAE.EqSystem inSyst;
input BackendDAE.Shared ishared;
input list<BackendDAE.Equation> eqn_lst;
input list<Integer> eqn_indxs;
input list<BackendDAE.Var> var_lst;
input list<Integer> var_indxs;
input list<tuple<Integer, Integer, BackendDAE.Equation>> jac;
output BackendDAE.EqSystem osyst;
output BackendDAE.Shared oshared;
algorithm
(osyst, oshared) := match (inSyst, ishared)
local
BackendDAE.Variables v;
BackendDAE.EquationArray eqns, eqns1;
list<DAE.Exp> beqs;
list<DAE.ElementSource> sources;
list<Real> rhsVals,solvedVals;
list<list<Real>> jacVals;
Integer linInfo;
list<DAE.ComponentRef> names;
DAE.FunctionTree funcs;
BackendDAE.Shared shared;
BackendDAE.EqSystem syst;
case (syst as BackendDAE.EQSYSTEM(), BackendDAE.SHARED(functionTree=funcs))
equation
eqns1 = BackendEquation.listEquation(eqn_lst);
v = BackendVariable.listVar1(var_lst);
(beqs, sources) = BackendDAEUtil.getEqnSysRhs(eqns1, v, SOME(funcs));
beqs = listReverse(beqs);
rhsVals = ValuesUtil.valueReals(List.map(beqs, Ceval.cevalSimple));
jacVals = evaluateConstantJacobian(listLength(var_lst), jac);
(solvedVals, linInfo) = System.dgesv(jacVals, rhsVals);
names = List.map(var_lst, BackendVariable.varCref);
checkLinearSystem(linInfo, names, jacVals, rhsVals, eqn_lst);
sources = List.map1( sources, DAEUtil.addSymbolicTransformation,
DAE.LINEAR_SOLVED(names, jacVals, rhsVals, solvedVals) );
(v, eqns, shared) = changeConstantLinearSystemVars( var_lst, solvedVals, sources, var_indxs,
syst.orderedVars, syst.orderedEqs, ishared );
syst.orderedVars = v;
syst.orderedEqs = List.fold(eqn_indxs, BackendEquation.equationRemove, eqns);
then
(BackendDAEUtil.setEqSystMatrices(syst), shared);
end match;
end solveLinearSystem;
protected function changeConstantLinearSystemVars
input list<BackendDAE.Var> inVarLst;
input list<Real> inSolvedVals;
input list<DAE.ElementSource> inSources;
input list<Integer> var_indxs;
input BackendDAE.Variables inVars;
input BackendDAE.EquationArray ieqns;
input BackendDAE.Shared ishared;
output BackendDAE.Variables outVars;
output BackendDAE.EquationArray oeqns;
output BackendDAE.Shared oshared;
algorithm
(outVars,oeqns,oshared) := match (inVarLst,inSolvedVals,inSources,var_indxs,inVars,ieqns,ishared)
local
BackendDAE.Var v,v1;
list<BackendDAE.Var> varlst;
DAE.ElementSource s;
list<DAE.ElementSource> slst;
BackendDAE.Variables vars,vars1,vars2;
Real r;
list<Real> rlst;
BackendDAE.Shared shared;
BackendDAE.EquationArray eqns;
Integer indx;
list<Integer> vindxs;
DAE.ComponentRef cref;
DAE.Type tp;
DAE.Exp e;
case ({},{},{},_,vars,eqns,_) then (vars,eqns,ishared);
case ((BackendDAE.VAR(varName=cref,varKind=BackendDAE.STATE(),varType=tp))::varlst,r::rlst,_::slst,_::vindxs,vars,eqns,_)
equation
e = Expression.makeCrefExp(cref, tp);
e = Expression.expDer(e);
eqns = BackendEquation.addEquation(BackendDAE.EQUATION(e, DAE.RCONST(r), DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_UNKNOWN), eqns);
(vars2,eqns,shared) = changeConstantLinearSystemVars(varlst,rlst,slst,vindxs,vars,eqns,ishared);
then (vars2,eqns,shared);
case (v::varlst,r::rlst,_::slst,indx::vindxs,vars,eqns,_)
equation
v1 = BackendVariable.setBindExp(v, SOME(DAE.RCONST(r)));
v1 = BackendVariable.setVarStartValue(v1,DAE.RCONST(r));
// ToDo: merge source of var and equation
(vars1,_) = BackendVariable.removeVar(indx, vars);
shared = BackendVariable.addKnVarDAE(v1,ishared);
(vars2,eqns,shared) = changeConstantLinearSystemVars(varlst,rlst,slst,vindxs,vars1,eqns,shared);
then (vars2,eqns,shared);
end match;
end changeConstantLinearSystemVars;
public function evaluateConstantJacobian
"Evaluate a constant Jacobian so we can solve a linear system during runtime"
input Integer size;
input list<tuple<Integer,Integer,BackendDAE.Equation>> jac;
output list<list<Real>> vals;
protected
array<array<Real>> valarr;
array<Real> tmp;
list<array<Real>> tmp2;
list<Real> rs;
algorithm
rs := List.fill(0.0,size);
tmp := listArray(rs);
tmp2 := List.map(List.fill(tmp,size),arrayCopy);
valarr := listArray(tmp2);
List.map1_0(jac,evaluateConstantJacobian2,valarr);
tmp2 := arrayList(valarr);
vals := List.map(tmp2,arrayList);
end evaluateConstantJacobian;
protected function evaluateConstantJacobian2
input tuple<Integer,Integer,BackendDAE.Equation> jac;
input array<array<Real>> vals;
algorithm
_ := match (jac,vals)
local
DAE.Exp exp;
Integer i1,i2;
Real r;
case ((i1,i2,BackendDAE.RESIDUAL_EQUATION(exp=exp)),_)
equation
Values.REAL(r) = Ceval.cevalSimple(exp);
arrayUpdate(arrayGet(vals,i1),i2,r);
then ();
end match;
end evaluateConstantJacobian2;
protected function checkLinearSystem
input Integer info;
input list<DAE.ComponentRef> vars;
input list<list<Real>> jac;
input list<Real> rhs;
input list<BackendDAE.Equation> eqnlst;
algorithm
_ := matchcontinue (info,vars,jac,rhs,eqnlst)
local
String infoStr,syst,varnames,varname,rhsStr,jacStr,eqnstr;
case (0,_,_,_,_) then ();
case (_,_,_,_,_)
equation
true = info > 0;
varname = ComponentReference.printComponentRefStr(listGet(vars,info));
infoStr = intString(info);
varnames = stringDelimitList(List.map(vars,ComponentReference.printComponentRefStr)," ;\n ");
rhsStr = stringDelimitList(List.map(rhs, realString)," ;\n ");
jacStr = stringDelimitList(List.map1(List.mapList(jac,realString),stringDelimitList," , ")," ;\n ");
eqnstr = BackendDump.dumpEqnsStr(eqnlst);
syst = stringAppendList({"\n",eqnstr,"\n[\n ", jacStr, "\n]\n *\n[\n ",varnames,"\n]\n =\n[\n ",rhsStr,"\n]"});
Error.addMessage(Error.LINEAR_SYSTEM_SINGULAR, {syst,infoStr,varname});
then fail();
case (_,_,_,_,_)
equation
true = info < 0;
varnames = stringDelimitList(List.map(vars,ComponentReference.printComponentRefStr)," ;\n ");
rhsStr = stringDelimitList(List.map(rhs, realString)," ; ");
jacStr = stringDelimitList(List.map1(List.mapList(jac,realString),stringDelimitList," , ")," ; ");
eqnstr = BackendDump.dumpEqnsStr(eqnlst);
syst = stringAppendList({eqnstr,"\n[", jacStr, "] * [",varnames,"] = [",rhsStr,"]"});
Error.addMessage(Error.LINEAR_SYSTEM_INVALID, {"LAPACK/dgesv",syst});
then fail();
end matchcontinue;
end checkLinearSystem;
protected function generateSparsePattern "author: wbraun
Function generated for a given set of variables and
equations the sparsity pattern and a coloring of Jacobian matrix A^(NxM).
col: N = size(diffVars)
rows : M = size(diffedVars)
The sparsity pattern is represented basically as a list of lists, every list
represents the non-zero elements of a row.
The coloring is saved as a list of lists, every list contains the