-
Notifications
You must be signed in to change notification settings - Fork 298
/
NBAdjacency.mo
1832 lines (1667 loc) · 78.4 KB
/
NBAdjacency.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-2020, 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 NBAdjacency
"file: NBAdjacency.mo
package: NBAdjacency
description: This file contains the functions which will create adjacency matrices.
"
public
// self import
import Adjacency = NBAdjacency;
protected
// NF imports
import Call = NFCall;
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import Expression = NFExpression;
import FunctionTree = NFFlatten.FunctionTree;
import Subscript = NFSubscript;
import Type = NFType;
import Operator = NFOperator;
import Variable = NFVariable;
// NB imports
import Differentiate = NBDifferentiate;
import BEquation = NBEquation;
import NBEquation.{Equation, EquationAttributes, EquationPointers, Iterator, IfEquationBody, WhenEquationBody, WhenStatement};
import BVariable = NBVariable;
import NBVariable.VariablePointers;
// Util import
import Array;
import BackendUtil = NBBackendUtil;
import BuiltinSystem = System;
import Slice = NBSlice;
import StringUtil;
// SetBased Graph imports
import SBGraph.BipartiteIncidenceList;
import SBGraph.VertexDescriptor;
import SBGraph.SetType;
import SBInterval;
import SBMultiInterval;
import SBPWLinearMap;
import SBSet;
public
type MatrixStrictness = enumeration(LINEAR, SOLVABLE, FULL);
uniontype Mapping
record MAPPING
array<Integer> eqn_StA "eqn: scal_idx -> arr_idx";
array<Integer> var_StA "var: scal_idx -> arr_idx";
array<tuple<Integer,Integer>> eqn_AtS "eqn: arr_idx -> start_idx/length";
array<tuple<Integer,Integer>> var_AtS "var: arr_idx -> start_idx/length";
end MAPPING;
function toString
input Mapping mapping;
output String str;
protected
Integer start, size;
algorithm
str := StringUtil.headline_4("Equation Index Mapping (ARR) -> START | SIZE");
for i in 1:arrayLength(mapping.eqn_AtS) loop
(start, size) := mapping.eqn_AtS[i];
str := str + "(" + intString(i) + ")\t" + intString(start) + " | " + intString(size) + "\n";
end for;
str := str + StringUtil.headline_4("Variable Index Mapping (ARR) -> START | SIZE");
for i in 1:arrayLength(mapping.var_AtS) loop
(start, size) := mapping.var_AtS[i];
str := str + "(" + intString(i) + ")\t" + intString(start) + " | " + intString(size) + "\n";
end for;
end toString;
function empty
output Mapping mapping = MAPPING(arrayCreate(0, 0), arrayCreate(0, 0),arrayCreate(0, (0,0)),arrayCreate(0, (0,0)));
end empty;
function create
input EquationPointers eqns;
input VariablePointers vars;
output Mapping mapping;
protected
list<Pointer<Equation>> eqn_lst = EquationPointers.toList(eqns);
list<Pointer<Variable>> var_lst = VariablePointers.toList(vars);
array<Integer> eqn_StA, var_StA;
array<tuple<Integer,Integer>> eqn_AtS, var_AtS;
Integer eqn_scalar_size, var_scalar_size, size;
Integer eqn_idx_scal = 1, eqn_idx_arr = 1, var_idx_scal = 1, var_idx_arr = 1;
algorithm
// prepare the mappings
eqn_scalar_size := sum(array(Equation.size(eqn) for eqn in eqn_lst));
var_scalar_size := sum(array(BVariable.size(var) for var in var_lst));
eqn_StA := arrayCreate(eqn_scalar_size, -1);
var_StA := arrayCreate(var_scalar_size, -1);
eqn_AtS := arrayCreate(EquationPointers.size(eqns), (-1, -1));
var_AtS := arrayCreate(VariablePointers.size(vars), (-1, -1));
// fill the arrays
(eqn_StA, var_StA, eqn_AtS, var_AtS) := fill_(eqn_StA, var_StA, eqn_AtS, var_AtS, eqn_lst, var_lst, eqn_idx_scal, eqn_idx_arr, var_idx_scal, var_idx_arr);
// compile mapping
mapping := MAPPING(eqn_StA, var_StA, eqn_AtS, var_AtS);
end create;
function expand
input output Mapping mapping;
input list<Pointer<Equation>> eqn_lst;
input list<Pointer<Variable>> var_lst;
input Integer neqn_scal;
input Integer nvar_scal;
input Integer neqn_arr;
input Integer nvar_arr;
protected
array<Integer> eqn_StA, var_StA;
array<tuple<Integer,Integer>> eqn_AtS, var_AtS;
Integer eqn_scalar_size, var_scalar_size;
Integer eqn_idx_scal = arrayLength(mapping.eqn_StA) + 1, eqn_idx_arr = arrayLength(mapping.eqn_AtS) + 1;
Integer var_idx_scal = arrayLength(mapping.var_StA) + 1, var_idx_arr = arrayLength(mapping.var_AtS) + 1;
algorithm
// copy all data
eqn_StA := Array.expandToSize(eqn_idx_scal - 1 + neqn_scal, mapping.eqn_StA, -1);
var_StA := Array.expandToSize(var_idx_scal - 1 + nvar_scal, mapping.var_StA, -1);
eqn_AtS := Array.expandToSize(eqn_idx_arr - 1 + neqn_arr, mapping.eqn_AtS, (-1, -1));
var_AtS := Array.expandToSize(var_idx_arr - 1 + nvar_arr, mapping.var_AtS, (-1, -1));
// fill the new sections
(eqn_StA, var_StA, eqn_AtS, var_AtS) := fill_(eqn_StA, var_StA, eqn_AtS, var_AtS, eqn_lst, var_lst, eqn_idx_scal, eqn_idx_arr, var_idx_scal, var_idx_arr);
// compile mapping
mapping := MAPPING(eqn_StA, var_StA, eqn_AtS, var_AtS);
end expand;
function getEqnScalIndices
input Integer arr_idx;
input Mapping mapping;
input Boolean reverse = false;
output list<Integer> scal_indices;
protected
Integer start, length;
algorithm
(start, length) := mapping.eqn_AtS[arr_idx];
scal_indices := if reverse then
List.intRange2(start + length - 1, start) else
List.intRange2(start, start + length - 1);
end getEqnScalIndices;
function getVarScalIndices
input Integer arr_idx;
input Mapping mapping;
input list<Subscript> subs;
input list<Dimension> dims;
input Boolean reverse = false;
output list<Integer> scal_indices;
protected
Integer start, length;
function subscriptedIndices
input Integer start;
input Integer length;
input list<Integer> slice;
output list<Integer> scal_indices;
algorithm
scal_indices := List.intRange2(start, start + length - 1);
if not listEmpty(slice) then
scal_indices := List.keepPositions(scal_indices, slice);
end if;
end subscriptedIndices;
algorithm
(start, length) := mapping.var_AtS[arr_idx];
scal_indices := match subs
local
Subscript sub;
list<list<Subscript>> subs_lst;
list<Integer> slice = {}, dim_sizes, values;
list<tuple<Integer, Integer>> ranges;
// no subscripts -> create full index list
case {} then subscriptedIndices(start, length, {});
// all subscripts are whole -> create full index list
case _ guard(List.all(subs, Subscript.isWhole)) then subscriptedIndices(start, length, {});
// only one subscript -> apply simple rule
case {sub} algorithm
slice := Subscript.toIndexList(sub, length);
then subscriptedIndices(start, length, slice);
// multiple subscripts -> apply location to index mapping rules
case _ algorithm
subs_lst := Subscript.scalarizeList(subs, dims);
subs_lst := List.combination(subs_lst);
dim_sizes := list(Dimension.size(dim) for dim in dims);
for sub_lst in listReverse(subs_lst) loop
values := list(Subscript.toInteger(s) for s in sub_lst);
ranges := List.zip(dim_sizes, values);
slice := Slice.locationToIndex(ranges, start) :: slice;
end for;
then slice;
else fail();
end match;
if reverse then
scal_indices := listReverse(scal_indices);
end if;
end getVarScalIndices;
protected
function fill_
input output array<Integer> eqn_StA;
input output array<Integer> var_StA;
input output array<tuple<Integer,Integer>> eqn_AtS;
input output array<tuple<Integer,Integer>> var_AtS;
input list<Pointer<Equation>> eqn_lst;
input list<Pointer<Variable>> var_lst;
input Integer eqn_idx_scal_start;
input Integer eqn_idx_arr_start;
input Integer var_idx_scal_start;
input Integer var_idx_arr_start;
protected
Integer size;
Integer eqn_idx_scal = eqn_idx_scal_start;
Integer eqn_idx_arr = eqn_idx_arr_start;
Integer var_idx_scal = var_idx_scal_start;
Integer var_idx_arr= var_idx_arr_start;
algorithm
// fill equation mapping
for eqn_ptr in eqn_lst loop
size := Equation.size(eqn_ptr);
eqn_AtS[eqn_idx_arr] := (eqn_idx_scal, size);
for i in eqn_idx_scal:eqn_idx_scal+size-1 loop
eqn_StA[i] := eqn_idx_arr;
end for;
eqn_idx_scal := eqn_idx_scal + size;
eqn_idx_arr := eqn_idx_arr + 1;
end for;
// fill variable mapping
for var_ptr in var_lst loop
size := BVariable.size(var_ptr);
var_AtS[var_idx_arr] := (var_idx_scal, size);
for i in var_idx_scal:var_idx_scal+size-1 loop
var_StA[i] := var_idx_arr;
end for;
var_idx_scal := var_idx_scal + size;
var_idx_arr := var_idx_arr + 1;
end for;
end fill_;
end Mapping;
uniontype CausalizeModes
record CAUSALIZE_MODES
"for-loop reconstruction information"
array<array<Integer>> mode_to_var "scal_eqn: mode idx -> var";
array<array<ComponentRef>> mode_to_cref "arr_eqn: mode idx -> cref to solve for";
Pointer<list<Integer>> mode_eqns "array indices of relevant eqns";
end CAUSALIZE_MODES;
function empty
input Integer eqn_scalar_size;
input Integer eqn_array_size;
output CausalizeModes modes = CAUSALIZE_MODES(
mode_to_var = arrayCreate(eqn_scalar_size, arrayCreate(0,0)),
mode_to_cref = arrayCreate(eqn_array_size, arrayCreate(0,ComponentRef.EMPTY())),
mode_eqns = Pointer.create({})
);
end empty;
function contains
"checks if there is a mode for this eqn array index"
input Integer eqn_scal_idx;
input CausalizeModes modes;
output Boolean b = not arrayEmpty(arrayGet(modes.mode_to_var, eqn_scal_idx));
end contains;
function get
"returns the proper mode for an eqn-var index tuple"
input Integer eqn_scal_idx;
input Integer var_scal_idx;
input CausalizeModes modes;
output Integer mode = -1;
protected
array<Integer> mtv = arrayGet(modes.mode_to_var, eqn_scal_idx);
algorithm
for i in 1:arrayLength(mtv) loop
if mtv[i] == var_scal_idx then
mode := i;
return;
end if;
end for;
end get;
function expand
input output CausalizeModes modes;
input Mapping mapping;
protected
array<array<Integer>> mode_to_var = arrayCreate(arrayLength(mapping.eqn_StA), arrayCreate(0,0));
array<array<ComponentRef>> mode_to_cref = arrayCreate(arrayLength(mapping.eqn_AtS), arrayCreate(0,ComponentRef.EMPTY()));
algorithm
Array.copy(modes.mode_to_var, mode_to_var);
Array.copy(modes.mode_to_cref, mode_to_cref);
modes := CAUSALIZE_MODES(mode_to_var, mode_to_cref, modes.mode_eqns);
end expand;
function update
input CausalizeModes modes;
input Integer eqn_scal_idx;
input Integer eqn_arr_idx;
input array<array<Integer>> mode_to_var_part;
input list<ComponentRef> unique_dependencies;
protected
// get clean pointers -> type checking fails otherwise
array<array<Integer>> mode_to_var = modes.mode_to_var;
array<array<ComponentRef>> mode_to_cref = modes.mode_to_cref;
algorithm
// if there is no mode yet this equation index has not been added
if arrayLength(mode_to_cref[eqn_arr_idx]) == 0 then
Pointer.update(modes.mode_eqns, eqn_arr_idx :: Pointer.access(modes.mode_eqns));
end if;
// create scalar mode idx to variable mapping
for i in 1:arrayLength(mode_to_var_part) loop
arrayUpdate(mode_to_var, eqn_scal_idx+(i-1), arrayAppend(mode_to_var_part[i], mode_to_var[eqn_scal_idx+(i-1)]));
end for;
// create array mode to cref mapping
arrayUpdate(mode_to_cref, eqn_arr_idx, arrayAppend(listArray(unique_dependencies), mode_to_cref[eqn_arr_idx]));
end update;
function clean
"cleans up all equation causalize modes of given indices
used for the updating routine."
input CausalizeModes modes;
input Mapping mapping;
input list<Integer> idx_lst;
protected
array<array<Integer>> mode_to_var = modes.mode_to_var;
array<array<ComponentRef>> mode_to_cref = modes.mode_to_cref;
list<Integer> scal_indices;
algorithm
for arr_idx in idx_lst loop
scal_indices := Mapping.getEqnScalIndices(arr_idx, mapping);
mode_to_cref[arr_idx] := arrayCreate(0, ComponentRef.EMPTY());
for scal_idx in scal_indices loop
mode_to_var[scal_idx] := arrayCreate(0, 0);
end for;
end for;
end clean;
function toString
input CausalizeModes modes;
output String str;
protected
array<Integer> mtv;
array<ComponentRef> mtc;
algorithm
str := StringUtil.headline_2("Causalization Modes");
str := str + StringUtil.headline_3("(scalar) mode index -> variable index");
for j in 1:arrayLength(modes.mode_to_var) loop
mtv := modes.mode_to_var[j];
str := str + "[" + intString(j) + "]\t";
for i in 1:arrayLength(mtv) loop
str := str + "(" + intString(i) + "->" + intString(mtv[i]) + ")";
end for;
str := str + "\n";
end for;
str := str + "\n" + StringUtil.headline_3("(array) mode index -> variable cref");
for j in 1:arrayLength(modes.mode_to_cref) loop
mtc := modes.mode_to_cref[j];
str := str + "[" + intString(j) + "]\t";
for i in 1:arrayLength(mtc) loop
str := str + "(" + intString(i) + "->" + ComponentRef.toString(mtc[i]) + ")";
end for;
str := str + "\n";
end for;
end toString;
end CausalizeModes;
uniontype Matrix
record FULL
array<ComponentRef> equation_names;
array<list<ComponentRef>> occurences;
array<UnorderedMap<ComponentRef, Dependency>> dependencies;
array<UnorderedMap<ComponentRef, Solvability>> solvabilities;
array<UnorderedSet<ComponentRef>> repetitions;
Mapping mapping;
end FULL;
record PSEUDO_ARRAY_ADJACENCY_MATRIX // ToDo: add optional solvability map for tearing
array<list<Integer>> m "eqn -> list<var>";
array<list<Integer>> mT "var -> list<eqn>";
Mapping mapping "index mapping scalar <-> array";
CausalizeModes modes "for-loop reconstruction information";
MatrixStrictness st "strictness with which it was created";
end PSEUDO_ARRAY_ADJACENCY_MATRIX;
record EMPTY_ADJACENCY_MATRIX
MatrixStrictness st;
end EMPTY_ADJACENCY_MATRIX;
function create
input VariablePointers vars;
input EquationPointers eqns;
input MatrixStrictness st = MatrixStrictness.FULL;
output Matrix adj;
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
algorithm
try
(adj, funcTree) := createPseudo(vars, eqns, st, funcTree);
else
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed to create adjacency matrix for system:\n"
+ VariablePointers.toString(vars, "System") + "\n"
+ EquationPointers.toString(eqns, "System")});
fail();
end try;
end create;
function update
"Updates specified rows of the adjacency matrix.
Updates everything by default and if the index
list is equal to {-1}.
Note: take care for pseudo array matrices! this will not update any changes
in mapping or causalize modes because it assumes same structure.
Use expand() to change structure!"
input output Matrix adj;
input VariablePointers vars;
input EquationPointers eqns;
input list<Integer> idx_lst = {-1};
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
algorithm
(adj, funcTree) := match (adj, idx_lst)
local
array<list<Integer>> m, mT;
Mapping mapping;
CausalizeModes modes;
case (PSEUDO_ARRAY_ADJACENCY_MATRIX(), {-1}) then create(vars, eqns, adj.st);
case (PSEUDO_ARRAY_ADJACENCY_MATRIX(), _) algorithm
(m, mT, _) := updatePseudo(adj.m, adj.st, adj.mapping, adj.modes, vars, eqns, idx_lst, funcTree);
adj.m := m;
adj.mT := mT;
then (adj, funcTree);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of unknown adjacency matrix type."});
then fail();
end match;
end update;
function expand
input output Matrix adj "adjancency matrix to be expanded";
input output VariablePointers vars "variable array to be expanded";
input output EquationPointers eqns "equation array to be expanded";
input list<Pointer<Variable>> new_vars "new variables to be added";
input list<Pointer<Equation>> new_eqns "new equations to be added";
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
algorithm
(adj, vars, eqns, funcTree) := match adj
local
array<list<Integer>> m, mT;
Mapping mapping;
CausalizeModes modes;
// if nothing is added, do nothing
case _ guard(listEmpty(new_vars) and listEmpty(new_eqns)) then (adj, vars, eqns, funcTree);
case PSEUDO_ARRAY_ADJACENCY_MATRIX() algorithm
(m, mT, mapping, modes, vars, eqns, _) := expandPseudo(adj.m, adj.st, adj.mapping, adj.modes, vars, eqns, new_vars, new_eqns, funcTree);
adj.m := m;
adj.mT := mT;
adj.mapping := mapping;
adj.modes := modes;
then (adj, vars, eqns, funcTree);
case EMPTY_ADJACENCY_MATRIX() algorithm
vars := VariablePointers.addList(new_vars, vars);
eqns := EquationPointers.addList(new_eqns, eqns);
(adj, funcTree) := create(vars, eqns, adj.st, funcTree);
then (adj, vars, eqns, funcTree);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of unknown adjacency matrix type."});
then fail();
end match;
end expand;
function expandPseudo
input output array<list<Integer>> m "adjancency matrix to be expanded";
output array<list<Integer>> mT "transposed adjacency matrix";
input MatrixStrictness st;
input output Mapping mapping;
input output CausalizeModes modes;
input output VariablePointers vars "variable array to be expanded";
input output EquationPointers eqns "equation array to be expanded";
input list<Pointer<Variable>> new_vars "new variables to expand";
input list<Pointer<Equation>> new_eqns "new equations to expand";
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
protected
Pointer<Differentiate.DifferentiationArguments> diffArgs_ptr;
Integer new_size, old_size = EquationPointers.size(eqns);
list<Integer> idx_lst;
UnorderedMap<ComponentRef, Integer> sub_map "only representing the new variables with shifted indices";
Variable var;
Integer eqn_idx_arr;
Integer neqn_scal = sum(array(Equation.size(eqn) for eqn in new_eqns));
Integer nvar_scal = sum(array(BVariable.size(var) for var in new_vars));
Integer neqn_arr = listLength(new_eqns);
Integer nvar_arr = listLength(new_vars);
algorithm
if Util.isSome(funcTree) then
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default(NBDifferentiate.DifferentiationType.TIME, Util.getOption(funcTree)));
else
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default());
end if;
// #############################################
// Step 1: add vars and eqs to meta info
// #############################################
m := expandMatrix(m, neqn_scal);
mapping := Mapping.expand(mapping, new_eqns, new_vars, neqn_scal, nvar_scal, neqn_arr, nvar_arr);
modes := CausalizeModes.expand(modes, mapping);
// #############################################
// Step 2: add variables and update eqns
// #############################################
vars := VariablePointers.addList(new_vars, vars);
// create sub map
sub_map := UnorderedMap.new<Integer>(ComponentRef.hashStrip, ComponentRef.isEqualStrip, Util.nextPrime(listLength(new_vars)));
// copy the index for all new variables into the sub map
for var_ptr in new_vars loop
var := Pointer.access(var_ptr);
UnorderedMap.add(var.name, UnorderedMap.getSafe(var.name, vars.map, sourceInfo()), sub_map);
end for;
// update the equation rows using only the sub_map
eqn_idx_arr := 1;
for eqn_ptr in EquationPointers.toList(eqns) loop
updateRow(eqn_ptr, diffArgs_ptr, st, sub_map, m, mapping, modes, eqn_idx_arr, funcTree);
eqn_idx_arr := eqn_idx_arr + 1;
end for;
// #############################################
// Step 3: add equations and new rows
// #############################################
eqns := EquationPointers.addList(new_eqns, eqns);
new_size := EquationPointers.size(eqns);
if new_size > old_size then
// create index list for all new equations and use updating routine to fill them
idx_lst := List.intRange2(old_size + 1, new_size);
(m, mT, _) := updatePseudo(m, st, mapping, modes, vars, eqns, idx_lst, funcTree); //update causalize modes!
else
// just transpose the matrix, no equations have been added
mT := transposeScalar(m, VariablePointers.scalarSize(vars));
end if;
end expandPseudo;
function toString
input Matrix adj;
input output String str = "";
algorithm
str := StringUtil.headline_2(str + "AdjacencyMatrix") + "\n";
str := match adj
local
array<String> names, types;
Integer length1, length2;
case FULL() algorithm
types := listArray(list(dimsString(Type.arrayDims(ComponentRef.getSubscriptedType(name))) for name in adj.equation_names));
names := listArray(list(ComponentRef.toString(name) for name in adj.equation_names));
length1 := max(stringLength(ty) for ty in types) + 1;
length2 := max(stringLength(name) for name in names) + 3;
for i in 1:arrayLength(names) loop
str := str + arrayGet(types, i) + " " + StringUtil.repeat(".", length1 - stringLength(arrayGet(types, i))) + " "
+ arrayGet(names, i) + " " + StringUtil.repeat(".", length2 - stringLength(arrayGet(names, i)))
+ " " + List.toString(adj.occurences[i], function fullString(dep_map = adj.dependencies[i],
sol_map = adj.solvabilities[i], rep_set = adj.repetitions[i])) + "\n";
end for;
str := str + Mapping.toString(adj.mapping) + "\n";
then str;
case PSEUDO_ARRAY_ADJACENCY_MATRIX() algorithm
if arrayLength(adj.m) > 0 then
str := str + StringUtil.headline_4("Normal Adjacency Matrix (row = equation)");
str := str + toStringSingle(adj.m);
end if;
str := str + "\n";
if arrayLength(adj.mT) > 0 then
str := str + StringUtil.headline_4("Transposed Adjacency Matrix (row = variable)");
str := str + toStringSingle(adj.mT);
end if;
str := str + "\n" + Mapping.toString(adj.mapping);
then str;
case EMPTY_ADJACENCY_MATRIX() then str + StringUtil.headline_4("Empty Adjacency Matrix") + "\n";
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of unknown adjacency matrix type."});
then fail();
end match;
end toString;
function solvabilityString
input Matrix adj;
input output String str = "";
algorithm
str := match adj
local
list<ComponentRef> XX, II, NM, NP, LV, LP, LC, QQ;
list<String> xx = {}, ii = {}, nm = {}, np = {}, lv = {}, lp = {}, lc = {}, qq = {};
array<String> names, types, XX_, II_, NM_, NP_, LV_, LP_, LC_, QQ_;
Integer length1, length2, length_xx, length_ii, length_nm, length_np, length_lv, length_lp, length_lc, length_qq;
case FULL() algorithm
str := StringUtil.headline_2(str + " Solvability Adjacency Matrix") + "\n";
types := listArray(list(dimsString(Type.arrayDims(ComponentRef.getSubscriptedType(name))) for name in adj.equation_names));
names := listArray(list(ComponentRef.toString(name) for name in adj.equation_names));
for i in arrayLength(names):-1:1 loop
(XX, II, NM, NP, LV, LP, LC, QQ) := Solvability.categorize(adj.occurences[i], adj.solvabilities[i]);
xx := List.toString(XX, ComponentRef.toString, "XX ", "{", ",", "}", false) :: xx;
ii := List.toString(II, ComponentRef.toString, "II ", "{", ",", "}", false) :: ii;
nm := List.toString(NM, ComponentRef.toString, "N- ", "{", ",", "}", false) :: nm;
np := List.toString(NP, ComponentRef.toString, "N+ ", "{", ",", "}", false) :: np;
lv := List.toString(LV, ComponentRef.toString, "LV ", "{", ",", "}", false) :: lv;
lp := List.toString(LP, ComponentRef.toString, "LP ", "{", ",", "}", false) :: lp;
lc := List.toString(LC, ComponentRef.toString, "LC ", "{", ",", "}", false) :: lc;
qq := List.toString(QQ, ComponentRef.toString, "|| ", "{", ",", "}", false) :: qq;
end for;
XX_ := listArray(xx);
II_ := listArray(ii);
NM_ := listArray(nm);
NP_ := listArray(np);
LV_ := listArray(lv);
LP_ := listArray(lp);
LC_ := listArray(lc);
QQ_ := listArray(qq);
length1 := max(stringLength(ty) for ty in types) + 1;
length2 := max(stringLength(name) for name in names) + 3;
length_xx := max(stringLength(s) for s in XX_);
length_ii := max(stringLength(s) for s in II_);
length_nm := max(stringLength(s) for s in NM_);
length_np := max(stringLength(s) for s in NP_);
length_lv := max(stringLength(s) for s in LV_);
length_lp := max(stringLength(s) for s in LP_);
length_lc := max(stringLength(s) for s in LC_);
length_qq := max(stringLength(s) for s in QQ_);
for i in 1:arrayLength(names) loop
str := str + arrayGet(types, i) + " " + StringUtil.repeat(".", length1 - stringLength(arrayGet(types, i))) + " "
+ arrayGet(names, i) + " " + StringUtil.repeat(".", length2 - stringLength(arrayGet(names, i)))
+ arrayGet(LC_, i) + " " + StringUtil.repeat(".", length_lc - stringLength(arrayGet(LC_, i)))
+ arrayGet(LP_, i) + " " + StringUtil.repeat(".", length_lp - stringLength(arrayGet(LP_, i)))
+ arrayGet(LV_, i) + " " + StringUtil.repeat(".", length_lv - stringLength(arrayGet(LV_, i)))
+ arrayGet(NP_, i) + " " + StringUtil.repeat(".", length_np - stringLength(arrayGet(NP_, i)))
+ arrayGet(NM_, i) + " " + StringUtil.repeat(".", length_nm - stringLength(arrayGet(NM_, i)))
+ arrayGet(II_, i) + " " + StringUtil.repeat(".", length_ii - stringLength(arrayGet(II_, i)))
+ arrayGet(XX_, i) + " " + StringUtil.repeat(".", length_xx - stringLength(arrayGet(XX_, i)))
+ arrayGet(QQ_, i) + " " + StringUtil.repeat(".", length_qq - stringLength(arrayGet(QQ_, i))) + "\n";
end for;
then str;
else toString(adj, str);
end match;
end solvabilityString;
function dependencyString
input Matrix adj;
input output String str = "";
algorithm
str := match adj
local
list<ComponentRef> F, R, E, A, S, K;
list<String> f = {}, r = {}, e = {}, a = {}, s = {}, k = {};
array<String> names, types, F_, R_, E_, A_, S_, K_;
Integer length1, length2, lengthf, lengthr, lengthe, lengtha, lengths, lengthk;
case FULL() algorithm
str := StringUtil.headline_2(str + " Dependency Adjacency Matrix") + "\n";
types := listArray(list(dimsString(Type.arrayDims(ComponentRef.getSubscriptedType(name))) for name in adj.equation_names));
names := listArray(list(ComponentRef.toString(name) for name in adj.equation_names));
for i in arrayLength(names):-1:1 loop
(F, R, E, A, S, K) := Dependency.categorize(adj.occurences[i], adj.dependencies[i], adj.repetitions[i]);
f := List.toString(F, ComponentRef.toString, "[!]", "{", ",", "}", false) :: f;
r := List.toString(R, ComponentRef.toString, "[-]", "{", ",", "}", false) :: r;
e := List.toString(E, ComponentRef.toString, "[+]", "{", ",", "}", false) :: e;
a := List.toString(A, ComponentRef.toString, "[:]", "{", ",", "}", false) :: a;
s := List.toString(S, ComponentRef.toString, "[.]", "{", ",", "}", false) :: s;
k := List.toString(K, ComponentRef.toString, "[o]", "{", ",", "}", false) :: k;
end for;
F_ := listArray(f);
R_ := listArray(r);
E_ := listArray(e);
A_ := listArray(a);
S_ := listArray(s);
K_ := listArray(k);
length1 := max(stringLength(ty) for ty in types) + 1;
length2 := max(stringLength(name) for name in names) + 3;
lengthf := max(stringLength(st) for st in F_);
lengthr := max(stringLength(st) for st in R_);
lengthe := max(stringLength(st) for st in E_);
lengtha := max(stringLength(st) for st in A_);
lengths := max(stringLength(st) for st in S_);
lengthk := max(stringLength(st) for st in K_);
for i in 1:arrayLength(names) loop
str := str + arrayGet(types, i) + " " + StringUtil.repeat(".", length1 - stringLength(arrayGet(types, i))) + " "
+ arrayGet(names, i) + " " + StringUtil.repeat(".", length2 - stringLength(arrayGet(names, i)))
+ arrayGet(K_, i) + " " + StringUtil.repeat(".", lengthk - stringLength(arrayGet(K_, i)))
+ arrayGet(S_, i) + " " + StringUtil.repeat(".", lengths - stringLength(arrayGet(S_, i)))
+ arrayGet(A_, i) + " " + StringUtil.repeat(".", lengtha - stringLength(arrayGet(A_, i)))
+ arrayGet(E_, i) + " " + StringUtil.repeat(".", lengthe - stringLength(arrayGet(E_, i)))
+ arrayGet(R_, i) + " " + StringUtil.repeat(".", lengthr - stringLength(arrayGet(R_, i)))
+ arrayGet(F_, i) + " " + StringUtil.repeat(".", lengthf - stringLength(arrayGet(F_, i))) + "\n";
end for;
then str;
else toString(adj, str);
end match;
end dependencyString;
protected
function fullString
input ComponentRef cref;
input UnorderedMap<ComponentRef, Dependency> dep_map;
input UnorderedMap<ComponentRef, Solvability> sol_map;
input UnorderedSet<ComponentRef> rep_set;
output String str = ComponentRef.toString(cref) + "[";
algorithm
str := str + Solvability.toString(UnorderedMap.getSafe(cref, sol_map, sourceInfo()))
+ "|" + Dependency.toString(UnorderedMap.getSafe(cref, dep_map, sourceInfo()));
if UnorderedSet.contains(cref, rep_set) then str := str + "+"; end if;
str := str + "]";
end fullString;
function dimsString
input list<Dimension> dims;
output String str;
algorithm
str := match dims
case {} then "{1}";
else List.toString(dims, Dimension.toString);
end match;
end dimsString;
public
function getMappingOpt
input Matrix adj;
output Option<Mapping> mapping;
algorithm
mapping := match adj
case PSEUDO_ARRAY_ADJACENCY_MATRIX() then SOME(adj.mapping);
else NONE();
end match;
end getMappingOpt;
function nonZeroCount
input Matrix adj;
output Integer count;
algorithm
count := match adj
case PSEUDO_ARRAY_ADJACENCY_MATRIX() then BackendUtil.countElem(adj.m);
case EMPTY_ADJACENCY_MATRIX() then 0;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of unknown matrix type."});
then fail();
end match;
end nonZeroCount;
function expandMatrix
input output array<list<Integer>> m;
input Integer shift;
algorithm
m := Array.expandToSize(arrayLength(m) + shift, m, {});
end expandMatrix;
function transposeScalar
input array<list<Integer>> m "original matrix";
input Integer size "size of the transposed matrix (does not have to be square!)";
output array<list<Integer>> mT "transposed matrix";
algorithm
mT := arrayCreate(size, {});
// loop over all elements and store them in reverse
for row in 1:arrayLength(m) loop
for idx in m[row] loop
try
if idx > 0 then
mT[idx] := row :: mT[idx];
else
mT[intAbs(idx)] := -row :: mT[intAbs(idx)];
end if;
else
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for variable index " + intString(idx) + ".
The variables have to be dense (without empty spaces) for this to work!"});
end try;
end for;
end for;
// sort the transposed matrix
// bigger to lower such that negative entries are at the and
for row in 1:arrayLength(mT) loop
mT[row] := List.sort(mT[row], intLt);
end for;
end transposeScalar;
protected
function toStringSingle
input array<list<Integer>> m;
output String str = "";
algorithm
for row in 1:arrayLength(m) loop
str := str + "\t(" + intString(row) + ")\t" + List.toString(m[row], intString) + "\n";
end for;
end toStringSingle;
function createFull
input VariablePointers vars;
input EquationPointers eqns;
input MatrixStrictness st = MatrixStrictness.FULL;
output Matrix adj;
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
protected
Integer index, size = EquationPointers.size(eqns);
array<ComponentRef> equation_names;
array<list<ComponentRef>> occurences;
array<UnorderedMap<ComponentRef, Dependency>> dependencies;
array<UnorderedMap<ComponentRef, Solvability>> solvabilities;
array<UnorderedSet<ComponentRef>> repetitions;
UnorderedSet<ComponentRef> occ_set, rep_set;
UnorderedMap<ComponentRef, Dependency> dep_map;
UnorderedMap<ComponentRef, Solvability> sol_map;
Mapping mapping;
algorithm
// only create matrix if there are any variables or equations
if ExpandableArray.getNumberOfElements(vars.varArr) > 0 or ExpandableArray.getNumberOfElements(eqns.eqArr) > 0 then
// create empty arrays for the structures
equation_names := arrayCreate(size, ComponentRef.EMPTY());
occurences := arrayCreate(size, {});
dependencies := arrayCreate(size, UnorderedMap.new<Dependency>(ComponentRef.hash, ComponentRef.isEqual));
solvabilities := arrayCreate(size, UnorderedMap.new<Solvability>(ComponentRef.hash, ComponentRef.isEqual));
repetitions := arrayCreate(size, UnorderedSet.new(ComponentRef.hash, ComponentRef.isEqual));
// loop over each equation and create the corresponding maps and sets
for eqn_ptr in listReverse(EquationPointers.toList(eqns)) loop
index := UnorderedMap.getSafe(Equation.getEqnName(eqn_ptr), eqns.map, sourceInfo());
dep_map := UnorderedMap.new<Dependency>(ComponentRef.hash, ComponentRef.isEqual);
sol_map := UnorderedMap.new<Solvability>(ComponentRef.hash, ComponentRef.isEqual);
rep_set := UnorderedSet.new(ComponentRef.hash, ComponentRef.isEqual);
occ_set := collectDependenciesEquation(Pointer.access(eqn_ptr), vars.map, dep_map, sol_map, rep_set);
equation_names[index] := Equation.getEqnName(eqn_ptr);
occurences[index] := UnorderedSet.toList(occ_set);
dependencies[index] := dep_map;
solvabilities[index] := sol_map;
repetitions[index] := rep_set;
end for;
// create the index mapping and the matrix
mapping := Mapping.create(eqns, vars);
adj := FULL(equation_names, occurences, dependencies, solvabilities, repetitions, mapping);
else
adj := EMPTY_ADJACENCY_MATRIX(st);
end if;
end createFull;
function createPseudo
input VariablePointers vars;
input EquationPointers eqns;
input MatrixStrictness st = MatrixStrictness.FULL;
output Matrix adj;
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
protected
Pointer<Differentiate.DifferentiationArguments> diffArgs_ptr;
Differentiate.DifferentiationArguments diffArgs;
array<list<Integer>> m, mT;
Integer eqn_scalar_size, var_scalar_size, eqn_idx_arr;
array<array<Integer>> mode_to_var "scal_eqn: mode idx -> var";
array<array<ComponentRef>> mode_to_cref "arr_eqn: mode idx -> cref to solve for";
Mapping mapping "scalar <-> array index mapping";
CausalizeModes modes;
algorithm
adj := createFull(vars, eqns, st, funcTree);
//print(EquationPointers.toString(eqns) + "\n");
//print(solvabilityString(adj, "Full") + "\n");
//print(dependencyString(adj, "Full") + "\n");
//print(toString(adj, "Full") + "\n");
if ExpandableArray.getNumberOfElements(vars.varArr) > 0 or ExpandableArray.getNumberOfElements(eqns.eqArr) > 0 then
if Util.isSome(funcTree) then
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default(NBDifferentiate.DifferentiationType.TIME, Util.getOption(funcTree)));
else
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default());
end if;
// create mapping
mapping := Mapping.create(eqns, vars);
eqn_scalar_size := arrayLength(mapping.eqn_StA);
var_scalar_size := arrayLength(mapping.var_StA);
// create empty for-loop reconstruction information
modes := CausalizeModes.empty(eqn_scalar_size, EquationPointers.size(eqns));
// create empty adjacency matrix and traverse equations to fill it
m := arrayCreate(eqn_scalar_size, {});
eqn_idx_arr := 1;
for eqn_ptr in EquationPointers.toList(eqns) loop
try
updateRow(eqn_ptr, diffArgs_ptr, st, vars.map, m, mapping, modes, eqn_idx_arr, funcTree);
else
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for:\n" + Equation.pointerToString(eqn_ptr)});
fail();
end try;
eqn_idx_arr := eqn_idx_arr + 1;
end for;
// also sorts the matrix
mT := transposeScalar(m, var_scalar_size);
if Util.isSome(funcTree) then
diffArgs := Pointer.access(diffArgs_ptr);
funcTree := SOME(diffArgs.funcTree);
end if;
adj := PSEUDO_ARRAY_ADJACENCY_MATRIX(m, mT, mapping, modes, st);
else
adj := EMPTY_ADJACENCY_MATRIX(st);
end if;
end createPseudo;
function updatePseudo
input output array<list<Integer>> m;
output array<list<Integer>> mT;
input MatrixStrictness st;
input Mapping mapping;
input CausalizeModes modes;
input VariablePointers vars;
input EquationPointers eqns;
input list<Integer> idx_lst;
input output Option<FunctionTree> funcTree = NONE() "only needed for LINEAR without existing derivatives";
protected
Pointer<Differentiate.DifferentiationArguments> diffArgs_ptr;
Differentiate.DifferentiationArguments diffArgs;
algorithm
if Util.isSome(funcTree) then
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default(NBDifferentiate.DifferentiationType.TIME, Util.getOption(funcTree)));
else
diffArgs_ptr := Pointer.create(Differentiate.DifferentiationArguments.default());
end if;
// clean up the matrix and causalize modes of equations to be updated
cleanMatrix(m, mapping, idx_lst);
CausalizeModes.clean(modes, mapping, idx_lst);
for i in idx_lst loop
updateRow(EquationPointers.getEqnAt(eqns, i), diffArgs_ptr, st, vars.map, m, mapping, modes, i, funcTree);
end for;
// also sorts the matrix
mT := transposeScalar(m, VariablePointers.scalarSize(vars));
if Util.isSome(funcTree) then
diffArgs := Pointer.access(diffArgs_ptr);
funcTree := SOME(diffArgs.funcTree);
end if;
end updatePseudo;
function updateRow
"updates a row and adds all occurences of variables in the input map
updates multiple rows for multi-dimensional equations."
input Pointer<Equation> eqn_ptr;
input Pointer<Differentiate.DifferentiationArguments> diffArgs_ptr;
input MatrixStrictness st;
input UnorderedMap<ComponentRef, Integer> map "hash table to check for relevance";
input array<list<Integer>> m;
input Mapping mapping;
input CausalizeModes modes "mutable";