-
Notifications
You must be signed in to change notification settings - Fork 297
/
NBDifferentiate.mo
1780 lines (1593 loc) · 80.9 KB
/
NBDifferentiate.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 NBDifferentiate
"file: NBDifferentiate.mo
package: NBDifferentiate
description: This file contains the functions to differentiate equations and
expressions symbolically.
"
public
// OF imports
import Absyn;
import AbsynUtil;
import BaseAvlTree;
import AvlSetPath;
import DAE;
// NF imports
import Algorithm = NFAlgorithm;
import BuiltinFuncs = NFBuiltinFuncs;
import Call = NFCall;
import Class = NFClass;
import ComponentRef = NFComponentRef;
import Expression = NFExpression;
import NFInstNode.{InstNode, CachedData};
import NFFlatten.{FunctionTree, FunctionTreeImpl};
import NFFunction.Function;
import FunctionDerivative = NFFunctionDerivative;
import Operator = NFOperator;
import Prefixes = NFPrefixes;
import Sections = NFSections;
import SimplifyExp = NFSimplifyExp;
import Statement = NFStatement;
import Type = NFType;
import NFPrefixes.Variability;
import Variable = NFVariable;
// Backend imports
import NBEquation.{Equation, EquationAttributes, EquationPointer, EquationPointers, IfEquationBody, WhenEquationBody, WhenStatement};
import NBVariable.{VariablePointer};
import BVariable = NBVariable;
import StrongComponent = NBStrongComponent;
// Util imports
import Array;
import BackendUtil = NBBackendUtil;
import Error;
import UnorderedMap;
import Slice = NBSlice;
// ================================
// TYPES AND UNIONTYPES
// ================================
type DifferentiationType = enumeration(TIME, SIMPLE, FUNCTION, JACOBIAN);
uniontype DifferentiationArguments
record DIFFERENTIATION_ARGUMENTS
ComponentRef diffCref "The input will be differentiated w.r.t. this cref (only SIMPLE).";
list<Pointer<Variable>> new_vars "contains all new variables that need to be added to the system";
Option<UnorderedMap<ComponentRef,ComponentRef>> jacobianHT "seed and temporary cref hashtable x --> $SEED.MATRIX.x, y --> $pDer.MATRIX.y";
DifferentiationType diffType "Differentiation use case (time, simple, function, jacobian)";
FunctionTree funcTree "Function tree containing all functions and their known derivatives";
Boolean scalarized "true if the variables are scalarized";
end DIFFERENTIATION_ARGUMENTS;
function default
input DifferentiationType ty = DifferentiationType.TIME;
input FunctionTree funcTree = FunctionTreeImpl.EMPTY();
output DifferentiationArguments diffArgs = DIFFERENTIATION_ARGUMENTS(
diffCref = ComponentRef.EMPTY(),
new_vars = {},
jacobianHT = NONE(),
diffType = ty,
funcTree = funcTree,
scalarized = false
);
end default;
end DifferentiationArguments;
// ================================
// FUNCTIONS
// ================================
function differentiateStrongComponentList
"author: kabdelhak
Differentiates a list of strong components."
input output list<StrongComponent> comps;
input output DifferentiationArguments diffArguments;
input Pointer<Integer> idx;
input String context;
input String name;
protected
Pointer<DifferentiationArguments> diffArguments_ptr = Pointer.create(diffArguments);
algorithm
comps := List.map(comps, function differentiateStrongComponent(diffArguments_ptr = diffArguments_ptr, idx = idx, context = context, name = name));
diffArguments := Pointer.access(diffArguments_ptr);
end differentiateStrongComponentList;
function differentiateStrongComponent
input output StrongComponent comp;
input Pointer<DifferentiationArguments> diffArguments_ptr;
input Pointer<Integer> idx;
input String context;
input String name;
algorithm
comp := match comp
local
Pointer<Variable> new_var;
Pointer<Equation> new_eqn;
list<Pointer<Variable>> new_vars;
list<Pointer<Equation>> new_eqns;
ComponentRef new_cref;
Slice<VariablePointer> new_var_slice;
Slice<EquationPointer> new_eqn_slice;
DifferentiationArguments diffArguments;
case StrongComponent.SINGLE_COMPONENT() algorithm
new_var := differentiateVariablePointer(comp.var, diffArguments_ptr);
new_eqn := differentiateEquationPointer(comp.eqn, diffArguments_ptr, name);
Equation.createName(new_eqn, idx, context);
then StrongComponent.SINGLE_COMPONENT(new_var, new_eqn, comp.status);
case StrongComponent.MULTI_COMPONENT() algorithm
new_vars := list(differentiateVariablePointer(var, diffArguments_ptr) for var in comp.vars);
new_eqn := differentiateEquationPointer(comp.eqn, diffArguments_ptr, name);
Equation.createName(new_eqn, idx, context);
then StrongComponent.MULTI_COMPONENT(new_vars, new_eqn, comp.status);
case StrongComponent.SLICED_COMPONENT() algorithm
(Expression.CREF(cref = new_cref), diffArguments) := differentiateComponentRef(Expression.fromCref(comp.var_cref), Pointer.access(diffArguments_ptr));
Pointer.update(diffArguments_ptr, diffArguments);
new_var_slice := Slice.apply(comp.var, function differentiateVariablePointer(diffArguments_ptr = diffArguments_ptr));
new_eqn_slice := Slice.apply(comp.eqn, function differentiateEquationPointer(diffArguments_ptr = diffArguments_ptr, name = name));
Slice.applyMutable(new_eqn_slice, function Equation.createName(idx = idx, context = context));
then StrongComponent.SLICED_COMPONENT(new_cref, new_var_slice, new_eqn_slice, comp.status);
case StrongComponent.GENERIC_COMPONENT() algorithm
(Expression.CREF(cref = new_cref), diffArguments) := differentiateComponentRef(Expression.fromCref(comp.var_cref), Pointer.access(diffArguments_ptr));
Pointer.update(diffArguments_ptr, diffArguments);
new_eqn := differentiateEquationPointer(Slice.getT(comp.eqn), diffArguments_ptr, name);
Equation.createName(new_eqn, idx, context);
then StrongComponent.GENERIC_COMPONENT(new_cref, Slice.SLICE(new_eqn, comp.eqn.indices));
case StrongComponent.ENTWINED_COMPONENT() algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " not implemented for entwined equation:\n" + StrongComponent.toString(comp)});
then fail();
case StrongComponent.ALGEBRAIC_LOOP() algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " not implemented for algebraic loop:\n" + StrongComponent.toString(comp)});
then fail();
case StrongComponent.ALIAS() then differentiateStrongComponent(comp.original, diffArguments_ptr, idx, context, name);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " not implemented for unknown strong component:\n" + StrongComponent.toString(comp)});
then fail();
end match;
end differentiateStrongComponent;
function differentiateEquationPointerList
"author: kabdelhak
Differentiates a list of equations wrapped in pointers."
input output list<Pointer<Equation>> equations;
input output DifferentiationArguments diffArguments;
input Pointer<Integer> idx;
input String context;
input String name;
protected
Pointer<DifferentiationArguments> diffArguments_ptr = Pointer.create(diffArguments);
algorithm
equations := List.map(equations, function differentiateEquationPointer(diffArguments_ptr = diffArguments_ptr, name = name));
for eqn in equations loop
Equation.createName(eqn, idx, context);
end for;
diffArguments := Pointer.access(diffArguments_ptr);
end differentiateEquationPointerList;
function differentiateEquationPointer
input Pointer<Equation> eq_ptr;
input Pointer<DifferentiationArguments> diffArguments_ptr;
input String name = "";
output Pointer<Equation> derivative_ptr;
protected
Equation eq, diffedEq;
DifferentiationArguments old_diffArguments, new_diffArguments;
algorithm
eq := Pointer.access(eq_ptr);
old_diffArguments := Pointer.access(diffArguments_ptr);
derivative_ptr := match Equation.getAttributes(eq)
// we differentiate w.r.t time and there already is a derivative saved
case EquationAttributes.EQUATION_ATTRIBUTES(derivative = SOME(derivative_ptr))
guard(old_diffArguments.diffType == DifferentiationType.TIME)
then derivative_ptr;
// else differentiate the equation
else algorithm
(diffedEq, new_diffArguments) := differentiateEquation(eq, old_diffArguments, name);
derivative_ptr := Pointer.create(diffedEq);
// save the derivative if we derive w.r.t. time
if new_diffArguments.diffType == DifferentiationType.TIME then
Pointer.update(eq_ptr, Equation.setDerivative(eq, derivative_ptr));
end if;
if not referenceEq(new_diffArguments, old_diffArguments) then
Pointer.update(diffArguments_ptr, new_diffArguments);
end if;
then derivative_ptr;
end match;
end differentiateEquationPointer;
function differentiateEquation
input output Equation eq;
input output DifferentiationArguments diffArguments;
input String name = "";
algorithm
if Flags.isSet(Flags.DEBUG_DIFFERENTIATION) and not stringEqual(name, "") then
print("### debugDifferentiation | " + name + " ###\n");
print("[BEFORE] " + Equation.toString(eq) + "\n");
end if;
(eq, diffArguments) := match eq
local
Equation res;
Expression lhs, rhs;
ComponentRef lhs_cref, rhs_cref;
list<Equation> forBody = {};
IfEquationBody ifBody;
WhenEquationBody whenBody;
Pointer<DifferentiationArguments> diffArguments_ptr;
EquationAttributes attr;
Algorithm alg;
// ToDo: Element source stuff (see old backend)
case Equation.SCALAR_EQUATION() algorithm
(lhs, diffArguments) := differentiateExpression(eq.lhs, diffArguments);
(rhs, diffArguments) := differentiateExpression(eq.rhs, diffArguments);
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.SCALAR_EQUATION(eq.ty, lhs, rhs, eq.source, attr), diffArguments);
case Equation.ARRAY_EQUATION() algorithm
(lhs, diffArguments) := differentiateExpression(eq.lhs, diffArguments);
(rhs, diffArguments) := differentiateExpression(eq.rhs, diffArguments);
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.ARRAY_EQUATION(eq.ty, lhs, rhs, eq.source, attr, eq.recordSize), diffArguments);
case Equation.RECORD_EQUATION() algorithm
(lhs, diffArguments) := differentiateExpression(eq.lhs, diffArguments);
(rhs, diffArguments) := differentiateExpression(eq.rhs, diffArguments);
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.RECORD_EQUATION(eq.ty, lhs, rhs, eq.source, attr, eq.recordSize), diffArguments);
case Equation.IF_EQUATION() algorithm
(ifBody, diffArguments_ptr) := differentiateIfEquationBody(eq.body, Pointer.create(diffArguments));
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.IF_EQUATION(eq.size, ifBody, eq.source, attr), Pointer.access(diffArguments_ptr));
case Equation.FOR_EQUATION() algorithm
for body_eqn in eq.body loop
(body_eqn, diffArguments) := differentiateEquation(body_eqn, diffArguments);
forBody := body_eqn :: forBody;
end for;
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.FOR_EQUATION(eq.size, eq.iter, listReverse(forBody), eq.source, attr), diffArguments);
case Equation.WHEN_EQUATION() algorithm
(whenBody, diffArguments) := differentiateWhenEquationBody(eq.body, diffArguments);
attr := differentiateEquationAttributes(eq.attr, diffArguments);
then (Equation.WHEN_EQUATION(eq.size, whenBody, eq.source, attr), diffArguments);
case Equation.ALGORITHM() algorithm
(alg, diffArguments) := differentiateAlgorithm(eq.alg, diffArguments);
then (Equation.ALGORITHM(eq.size, alg, eq.source, eq.expand, eq.attr), diffArguments);
else algorithm
// maybe add failtrace here and allow failing
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Equation.toString(eq)});
then fail();
end match;
/* ToDo
record AUX_EQUATION
"Auxiliary equations are generated when auxiliary variables are generated
that are known to always be solved in this specific equation. E.G. $CSE
The variable binding contains the equation, but this equation is also
allowed to have a body for special cases."
Pointer<Variable> auxiliary "Corresponding auxiliary variable";
Option<Equation> body "Optional body equation"; // -> Expression
end AUX_EQUATION;
record DUMMY_EQUATION
end DUMMY_EQUATION;
*/
if Flags.isSet(Flags.DEBUG_DIFFERENTIATION) and not stringEqual(name, "") then
eq := Equation.simplify(eq, name, "\t");
print("[AFTER ] " + Equation.toString(eq) + "\n\n");
else
eq := Equation.simplify(eq, name);
end if;
end differentiateEquation;
function differentiateIfEquationBody
input output IfEquationBody body;
input output Pointer<DifferentiationArguments> diffArguments_ptr;
protected
list<Pointer<Equation>> then_eqns;
IfEquationBody else_if;
algorithm
// ToDo: this is a little ugly
// 1. why are the then_eqns Pointers? no need for that
// 2. we could just traverse it regularly without creating a pointer for diffArguments
then_eqns := List.map(body.then_eqns, function differentiateEquationPointer(diffArguments_ptr = diffArguments_ptr, name = ""));
if isSome(body.else_if) then
(else_if, diffArguments_ptr) := differentiateIfEquationBody(Util.getOption(body.else_if), diffArguments_ptr);
body := IfEquationBody.IF_EQUATION_BODY(body.condition, then_eqns, SOME(else_if));
else
body := IfEquationBody.IF_EQUATION_BODY(body.condition, then_eqns, NONE());
end if;
end differentiateIfEquationBody;
function differentiateWhenEquationBody
input output WhenEquationBody body;
input output DifferentiationArguments diffArguments;
protected
list<WhenStatement> when_stmts;
WhenEquationBody else_when;
algorithm
(when_stmts, diffArguments) := List.mapFold(body.when_stmts, function differentiateWhenStatement(), diffArguments);
if isSome(body.else_when) then
(else_when, diffArguments) := differentiateWhenEquationBody(Util.getOption(body.else_when), diffArguments);
body := WhenEquationBody.WHEN_EQUATION_BODY(body.condition, when_stmts, SOME(else_when));
else
body := WhenEquationBody.WHEN_EQUATION_BODY(body.condition, when_stmts, NONE());
end if;
end differentiateWhenEquationBody;
function differentiateWhenStatement
input output WhenStatement stmt;
input output DifferentiationArguments diffArguments;
algorithm
(stmt, diffArguments) := match stmt
local
Expression lhs, rhs;
// Only differentiate assignments
case WhenStatement.ASSIGN() algorithm
(lhs, diffArguments) := differentiateExpression(stmt.lhs, diffArguments);
(rhs, diffArguments) := differentiateExpression(stmt.rhs, diffArguments);
then (WhenStatement.ASSIGN(lhs, rhs, stmt.source), diffArguments);
else (stmt, diffArguments);
end match;
end differentiateWhenStatement;
function differentiateExpressionDump
"wrapper function for differentiation to allow dumping before and afterwards"
input output Expression exp;
input output DifferentiationArguments diffArguments;
input String name = "";
input String indent = "";
algorithm
if Flags.isSet(Flags.DEBUG_DIFFERENTIATION) then
print(indent + "### debugDifferentiation | " + name + " ###\n");
print(indent + "[BEFORE] " + Expression.toString(exp) + "\n");
exp := differentiateExpression(exp, diffArguments);
print(indent + "[AFTER ] " + Expression.toString(exp) + "\n\n");
else
exp := differentiateExpression(exp, diffArguments);
end if;
end differentiateExpressionDump;
function differentiateExpression
input output Expression exp;
input output DifferentiationArguments diffArguments;
algorithm
(exp, diffArguments) := match exp
local
Expression elem1, elem2;
list<Expression> new_elements = {};
list<list<Expression>> new_matrix_elements = {};
array<Expression> arr;
// differentiation of constant expressions results in zero
case Expression.INTEGER() then (Expression.INTEGER(0), diffArguments);
case Expression.REAL() then (Expression.REAL(0.0), diffArguments);
// leave boolean and string expressions as is
case Expression.STRING() then (exp, diffArguments);
case Expression.BOOLEAN() then (exp, diffArguments);
// differentiate cref
case Expression.CREF() then differentiateComponentRef(exp, diffArguments);
// [a, b, c, ...]' = [a', b', c', ...]
case Expression.ARRAY() algorithm
(arr, diffArguments) := Array.mapFold(exp.elements, differentiateExpression, diffArguments);
exp.elements := arr;
then (exp, diffArguments);
// |a, b, c|' |a', b', c'|
// |d, e, f| = |d', e', f'|
// |g, h, i| |g', h', i'|
case Expression.MATRIX() algorithm
for element_lst in exp.elements loop
new_elements := {};
for element in element_lst loop
(element, diffArguments) := differentiateExpression(element, diffArguments);
new_elements := element :: new_elements;
end for;
new_matrix_elements := listReverse(new_elements) :: new_matrix_elements;
end for;
then (Expression.MATRIX(listReverse(new_matrix_elements)), diffArguments);
// (a, b, c, ...)' = (a', b', c', ...)
case Expression.TUPLE() algorithm
for element in exp.elements loop
(element, diffArguments) := differentiateExpression(element, diffArguments);
new_elements := element :: new_elements;
end for;
then (Expression.TUPLE(exp.ty, listReverse(new_elements)), diffArguments);
// REC(a, b, c, ...)' = REC(a', b', c', ...)
case Expression.RECORD() algorithm
for element in exp.elements loop
(element, diffArguments) := differentiateExpression(element, diffArguments);
new_elements := element :: new_elements;
end for;
then (Expression.RECORD(exp.path, exp.ty, listReverse(new_elements)), diffArguments);
case Expression.CALL() then differentiateCall(exp, diffArguments);
// (if c then a else b)' = if c then a' else b'
case Expression.IF() algorithm
(elem1, diffArguments) := differentiateExpression(exp.trueBranch, diffArguments);
(elem2, diffArguments) := differentiateExpression(exp.falseBranch, diffArguments);
then (Expression.IF(exp.ty, exp.condition, elem1, elem2), diffArguments);
// e.g. (fg)' = fg' + f'g (more rules in differentiateBinary)
case Expression.BINARY() then differentiateBinary(exp, diffArguments);
// e.g. (fgh)' = f'gh + fg'h + fgh' (more rules in differentiateMultary)
case Expression.MULTARY() then differentiateMultary(exp, diffArguments);
// (-x)' = -(x')
case Expression.UNARY() algorithm
(elem1, diffArguments) := differentiateExpression(exp.exp, diffArguments);
then (Expression.UNARY(exp.operator, elem1), diffArguments);
// ((Real) x)' = (Real) x'
case Expression.CAST() algorithm
(elem1, diffArguments) := differentiateExpression(exp.exp, diffArguments);
then (Expression.CAST(exp.ty, elem1), diffArguments);
// BOX(x)' = BOX(x')
case Expression.BOX() algorithm
(elem1, diffArguments) := differentiateExpression(exp.exp, diffArguments);
then (Expression.BOX(elem1), diffArguments);
// UNBOX(x)' = UNBOX(x')
case Expression.UNBOX() algorithm
(elem1, diffArguments) := differentiateExpression(exp.exp, diffArguments);
then (Expression.UNBOX(elem1, exp.ty), diffArguments);
// (x(1))' = x'(1)
case Expression.SUBSCRIPTED_EXP() algorithm
(elem1, diffArguments) := differentiateExpression(exp.exp, diffArguments);
then (Expression.SUBSCRIPTED_EXP(elem1, exp.subscripts, exp.ty, exp.split), diffArguments);
// (..., a_i ,...)' = (..., a'_i, ...)
case Expression.TUPLE_ELEMENT() algorithm
(elem1, diffArguments) := differentiateExpression(exp.tupleExp, diffArguments);
then (Expression.TUPLE_ELEMENT(elem1, exp.index, exp.ty), diffArguments);
// REC(i, ...)' = REC(i', ...)
// ToDo: does this suffice? Check with old backend RSUB()!
case Expression.RECORD_ELEMENT() algorithm
(elem1, diffArguments) := differentiateExpression(exp.recordExp, diffArguments);
then (Expression.RECORD_ELEMENT(elem1, exp.index, exp.fieldName, exp.ty), diffArguments);
// Binary expressions, conditions and placeholders are not differentiated and left as they are
case Expression.LBINARY() then (exp, diffArguments);
case Expression.LUNARY() then (exp, diffArguments);
case Expression.RELATION() then (exp, diffArguments);
case Expression.SIZE() then (exp, diffArguments);
case Expression.RANGE() then (exp, diffArguments);
case Expression.END() then (exp, diffArguments);
case Expression.EMPTY() then (exp, diffArguments);
case Expression.ENUM_LITERAL() then (exp, diffArguments);
case Expression.TYPENAME() then (exp, diffArguments);
else algorithm
// maybe add failtrace here and allow failing
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp)});
then fail();
end match;
/* ToDo:
record PARTIAL_FUNCTION_APPLICATION
ComponentRef fn;
list<Expression> args;
list<String> argNames;
Type ty;
end PARTIAL_FUNCTION_APPLICATION;
*/
end differentiateExpression;
function differentiateComponentRef
input output Expression exp "Has to be Expression.CREF()";
input output DifferentiationArguments diffArguments;
protected
Pointer<Variable> var_ptr, der_ptr;
ComponentRef derCref, strippedCref;
algorithm
// extract var pointer first to have following code more readable
var_ptr := match exp
// function body expressions, empty and wild crefs are not lowered (maybe do it?)
case _ guard(diffArguments.diffType == DifferentiationType.FUNCTION) then Pointer.create(NBVariable.DUMMY_VARIABLE);
case Expression.CREF(cref = ComponentRef.EMPTY()) then Pointer.create(NBVariable.DUMMY_VARIABLE);
case Expression.CREF(cref = ComponentRef.WILD()) then Pointer.create(NBVariable.DUMMY_VARIABLE);
case Expression.CREF() then BVariable.getVarPointer(exp.cref);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp)});
then fail();
end match;
(exp, diffArguments) := match (exp, diffArguments.diffType, diffArguments.jacobianHT)
local
Expression res;
UnorderedMap<ComponentRef,ComponentRef> jacobianHT;
// -------------------------------------
// EMPTY and WILD crefs do nothing
// -------------------------------------
case (Expression.CREF(cref = ComponentRef.EMPTY()), _, _) then (exp, diffArguments);
case (Expression.CREF(cref = ComponentRef.WILD()), _, _) then (exp, diffArguments);
// -------------------------------------
// Special rules for Type: FUNCTION
// (needs to be first because var_ptr is DUMMY)
// -------------------------------------
// Types: (FUNCTION)
// Any variable that is in the HT will be differentiated accordingly. 0 otherwise
case (Expression.CREF(), DifferentiationType.FUNCTION, SOME(jacobianHT)) algorithm
strippedCref := ComponentRef.stripSubscriptsAll(exp.cref);
if UnorderedMap.contains(strippedCref, jacobianHT) then
// get the derivative and reapply subscripts
derCref := UnorderedMap.getOrFail(strippedCref, jacobianHT);
derCref := ComponentRef.setSubscriptsList(listReverse(ComponentRef.subscriptsAll(exp.cref)), derCref);
res := Expression.fromCref(derCref);
else
res := Expression.makeZero(exp.ty);
end if;
then (res, diffArguments);
// -------------------------------------
// Generic Rules
// -------------------------------------
// Types: (TIME)
// differentiate time cref => 1
case (Expression.CREF(), DifferentiationType.TIME, _)
guard(ComponentRef.isTime(exp.cref))
then (Expression.makeOne(exp.ty), diffArguments);
// Types: not (TIME)
// differentiate time cref => 0
case (Expression.CREF(), _, _)
guard(ComponentRef.isTime(exp.cref))
then (Expression.makeZero(exp.ty), diffArguments);
// Types: (ALL)
// differentiate start cref => 0
case (Expression.CREF(), _, _)
guard(BVariable.isStart(var_ptr))
then (Expression.makeZero(exp.ty), diffArguments);
// ToDo: Records, Arrays, WILD (?)
// Types: (SIMPLE)
// D(x)/dx => 1
case (Expression.CREF(), DifferentiationType.SIMPLE, _)
guard(ComponentRef.isEqual(exp.cref, diffArguments.diffCref)) algorithm
then (Expression.makeOne(exp.ty), diffArguments);
// Types: (SIMPLE)
// D(y)/dx => 0
case (Expression.CREF(), DifferentiationType.SIMPLE, _) algorithm
then (Expression.makeZero(exp.ty), diffArguments);
// Types: (ALL)
// Known variables, except for top level inputs have a 0-derivative
case (Expression.CREF(), _, _)
guard(BVariable.isParamOrConst(var_ptr) and
not (ComponentRef.isTopLevel(exp.cref) and BVariable.isInput(var_ptr)))
then (Expression.makeZero(exp.ty), diffArguments);
// -------------------------------------
// Special rules for Type: TIME
// -------------------------------------
// Types: (TIME)
// D(discrete)/d(x) = 0
case (Expression.CREF(), DifferentiationType.TIME, _)
guard(BVariable.isDiscrete(var_ptr) or BVariable.isDiscreteState(var_ptr))
then (Expression.makeZero(exp.ty), diffArguments);
// Types: (TIME)
// DUMMY_STATES => DUMMY_DER
case (Expression.CREF(), DifferentiationType.TIME, _)
guard(BVariable.isDummyState(var_ptr))
then (Expression.fromCref(BVariable.getDummyDerCref(exp.cref)), diffArguments);
// Types: (TIME)
// D(x)/dtime --> der(x) --> $DER.x
// STATE => STATE_DER
case (Expression.CREF(), DifferentiationType.TIME, _)
guard(BVariable.isState(var_ptr))
then (Expression.fromCref(BVariable.getDerCref(exp.cref)), diffArguments);
// Types: (TIME)
// D(y)/dtime --> der(y) --> $DER.y
// ALGEBRAIC => STATE_DER
// make y a state and add new STATE_DER
case (Expression.CREF(), DifferentiationType.TIME, _)
guard(BVariable.isContinuous(var_ptr))
algorithm
// create derivative
(derCref, der_ptr) := BVariable.makeDerVar(exp.cref);
// add derivative to new_vars
diffArguments.new_vars := der_ptr :: diffArguments.new_vars;
// update algebraic variable to be a state
BVariable.makeStateVar(var_ptr, der_ptr);
then (Expression.fromCref(derCref), diffArguments);
// -------------------------------------
// Special rules for Type: JACOBIAN
// -------------------------------------
// Types: (JACOBIAN)
// cref in jacobianHT => get $SEED or $pDER variable from hash table
case (Expression.CREF(), DifferentiationType.JACOBIAN, SOME(jacobianHT))
guard(diffArguments.scalarized)
algorithm
if UnorderedMap.contains(exp.cref, jacobianHT) then
res := Expression.fromCref(UnorderedMap.getOrFail(exp.cref, jacobianHT));
else
// Everything that is not in jacobianHT gets differentiated to zero
res := Expression.makeZero(exp.ty);
end if;
then (res, diffArguments);
// Types: (JACOBIAN)
// cref in jacobianHT => get $SEED or $pDER variable from hash table
case (Expression.CREF(), DifferentiationType.JACOBIAN, SOME(jacobianHT))
guard(not diffArguments.scalarized)
algorithm
strippedCref := ComponentRef.stripSubscriptsAll(exp.cref);
if UnorderedMap.contains(strippedCref, jacobianHT) then
// get the derivative an reapply subscripts
derCref := UnorderedMap.getOrFail(strippedCref, jacobianHT);
derCref := ComponentRef.setSubscriptsList(listReverse(ComponentRef.subscriptsAll(exp.cref)), derCref);
res := Expression.fromCref(derCref);
else
res := Expression.makeZero(exp.ty);
end if;
then (res, diffArguments);
else algorithm
// maybe add failtrace here and allow failing
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp)});
then fail();
end match;
end differentiateComponentRef;
function differentiateVariablePointer
input Pointer<Variable> var_ptr;
input Pointer<DifferentiationArguments> diffArguments_ptr;
output Pointer<Variable> diff_ptr;
protected
DifferentiationArguments diffArguments = Pointer.access(diffArguments_ptr);
Variable var = Pointer.access(var_ptr);
Expression crefExp;
algorithm
(crefExp, diffArguments) := differentiateComponentRef(Expression.fromCref(var.name), diffArguments);
diff_ptr := match crefExp
case Expression.CREF(cref = ComponentRef.EMPTY()) then Pointer.create(NBVariable.DUMMY_VARIABLE);
case Expression.CREF(cref = ComponentRef.WILD()) then Pointer.create(NBVariable.DUMMY_VARIABLE);
case Expression.CREF() then BVariable.getVarPointer(crefExp.cref);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for " + Variable.toString(var)
+ " because the result is expected to be a variable but turned out to be " + Expression.toString(crefExp) + "."});
then fail();
end match;
Pointer.update(diffArguments_ptr, diffArguments);
end differentiateVariablePointer;
function differentiateCall
"Differentiate builtin function calls
1. if the function is builtin -> use hardcoded logic
2. if the function is not builtin -> check if there is a 'fitting' derivative defined.
- 'fitting' means that all the zeroDerivative annotations have to hold
2.1 fitting function found -> use it
2.2 fitting function not found -> differentiate the body of the function
ToDo: respect the 'order' of the derivative when differentiating!"
input output Expression exp "Has to be Expression.CALL()";
input output DifferentiationArguments diffArguments;
protected
constant Boolean debug = false;
algorithm
if debug then
print("\nDifferentiate Exp-Call: "+ Expression.toString(exp) + "\n");
end if;
(exp, diffArguments) := match exp
local
Expression ret;
Call call, der_call;
Option<Function> func_opt, der_func_opt;
list<Function> derivatives;
Function func, der_func;
list<Expression> arguments = {};
Operator addOp, mulOp;
list<tuple<Expression, InstNode>> arguments_inputs;
Expression arg;
InstNode inp;
Boolean isCont, isReal;
// interface map. If the map contains a variable it has a zero derivative
// if the value is "true" it has to be stripped from the interface
// (it is possible that a variable has a zero derivative, but still appears in the interface)
UnorderedMap<String, Boolean> interface_map = UnorderedMap.new<Boolean>(stringHashDjb2, stringEqual);
// builtin functions
case Expression.CALL(call = call as Call.TYPED_CALL()) guard(Function.isBuiltin(call.fn)) algorithm
ret := differentiateBuiltinCall(AbsynUtil.pathString(Function.nameConsiderBuiltin(call.fn)), exp, diffArguments);
then (ret, diffArguments);
// user defined functions
case Expression.CALL(call = call as Call.TYPED_CALL()) algorithm
func_opt := FunctionTreeImpl.getOpt(diffArguments.funcTree, call.fn.path);
if Util.isSome(func_opt) then
// The function is in the function tree
SOME(func) := func_opt;
// build interface map to check if a function fits
// save all inputs that would end up in a zero derivative in a map
arguments_inputs := List.zip(call.arguments, func.inputs);
for tpl in arguments_inputs loop
(arg, inp) := tpl;
// do not check for continuous if it is for functions (differentiating a function inside a function)
// crefs are not lowered there! assume it is continuous
isCont := (diffArguments.diffType == DifferentiationType.FUNCTION) or BackendUtil.isContinuous(arg);
isReal := Type.isReal(Type.arrayElementType(Expression.typeOf(arg))); // ToDo also records
if not (isCont and isReal) then
// add to map; if it is not Real also already set to true (always removed from interface)
UnorderedMap.add(InstNode.name(inp), not isReal, interface_map);
end if;
end for;
// try to get a fitting function from derivatives -> if none is found, differentiate
der_func_opt := Function.getDerivative(func, interface_map);
if Util.isSome(der_func_opt) then
SOME(der_func) := der_func_opt;
else
(der_func, diffArguments) := differentiateFunction(func, interface_map, diffArguments);
end if;
for tpl in listReverse(arguments_inputs) loop
(arg, inp) := tpl;
// only keep the arguments which are not in the map or have value false
if not UnorderedMap.getOrDefault(InstNode.name(inp), interface_map, false) then
arguments := arg :: arguments;
end if;
end for;
// differentiate type arguments and append to original ones
(arguments, diffArguments) := List.mapFold(arguments, differentiateExpression, diffArguments);
arguments := listAppend(call.arguments, arguments);
ret := Expression.CALL(Call.makeTypedCall(der_func, arguments, call.var, call.purity));
else
// The function is not in the function tree and not builtin -> error
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName()
+ " failed because the function is not a builtin function and could not be found in the function tree: "
+ Expression.toString(exp)});
fail();
end if;
then (ret, diffArguments);
// If the call was not typed correctly by the frontend
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp)});
then fail();
end match;
if debug then
print("Differentiate-ExpCall-result: " + Expression.toString(exp) + "\n");
end if;
end differentiateCall;
protected function differentiateBuiltinCall
"This function differentiates built-in call expressions with respect to a given variable.
Also creates and multiplies inner derivatives."
input String name;
input output Expression exp;
input output DifferentiationArguments diffArguments;
protected
// these need to be adapted to size and type of exp
Operator.SizeClassification sizeClass = NFOperator.SizeClassification.SCALAR;
Operator addOp = Operator.fromClassification((NFOperator.MathClassification.ADDITION, sizeClass), Type.REAL());
Operator mulOp = Operator.fromClassification((NFOperator.MathClassification.MULTIPLICATION, sizeClass), Type.REAL());
algorithm
exp := match (exp)
local
Integer i;
Expression ret, ret1, ret2, arg1, arg2, arg3, diffArg1, diffArg2, diffArg3;
list<Expression> rest;
Type ty;
DifferentiationType diffType;
// DELAY
// d/dz delay(x, delta) = (dt/dz - d delta/dz) * delay(der(x), delta)
case (Expression.CALL()) guard(name == "delay")
algorithm
{arg1, arg2, arg3} := Call.arguments(exp.call);
// if z = t then dt/dz = 1 else dt/dz = 0
ret1 := Expression.REAL(if diffArguments.diffType == DifferentiationType.TIME then 1.0 else 0.0);
// d delta/dz
(ret2, diffArguments) := differentiateExpression(arg2, diffArguments);
// dt/dz - d delta/dz
ret2 := SimplifyExp.simplifyDump(Expression.MULTARY({ret1}, {ret2}, addOp), true, getInstanceName());
if Expression.isZero(ret2) then
ret := Expression.makeZero(Expression.typeOf(arg1));
else
diffType := diffArguments.diffType;
diffArguments.diffType := DifferentiationType.TIME;
(ret1, diffArguments) := differentiateExpression(arg1, diffArguments);
diffArguments.diffType := diffType;
exp.call := Call.setArguments(exp.call, {ret1, arg2, arg3});
ret := Expression.MULTARY({ret2, exp}, {}, mulOp);
end if;
then ret;
// SMOOTH
case (Expression.CALL()) guard(name == "smooth")
algorithm
{arg1, arg2} := Call.arguments(exp.call);
ret := match arg1
case Expression.INTEGER(i) guard(i > 0) algorithm
(ret2, diffArguments) := differentiateExpression(arg2, diffArguments);
exp.call := Call.setArguments(exp.call, {Expression.INTEGER(i-1), ret2});
then exp;
case Expression.INTEGER(i) algorithm
(ret2, diffArguments) := differentiateExpression(arg2, diffArguments);
exp := Expression.CALL(Call.makeTypedCall(
fn = NFBuiltinFuncs.NO_EVENT,
args = {ret2},
variability = Expression.variability(ret2),
purity = NFPrefixes.Purity.PURE
));
then exp;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp) + "."});
then fail();
end match;
then ret;
// NO_EVENT
case (Expression.CALL()) guard(name == "noEvent")
algorithm
{arg1} := Call.arguments(exp.call);
(ret1, diffArguments) := differentiateExpression(arg1, diffArguments);
exp.call := Call.setArguments(exp.call, {ret1});
then exp;
// HOMOTOPY
case (Expression.CALL()) guard(name == "homotopy")
algorithm
{arg1, arg2} := Call.arguments(exp.call);
(ret1, diffArguments) := differentiateExpression(arg1, diffArguments);
(ret2, diffArguments) := differentiateExpression(arg2, diffArguments);
exp.call := Call.setArguments(exp.call, {ret1, ret2});
then exp;
// FILL
case (Expression.CALL()) guard(name == "fill")
algorithm
// only differentiate 1st input
arg1 :: rest := Call.arguments(exp.call);
(ret1, diffArguments) := differentiateExpression(arg1, diffArguments);
exp.call := Call.setArguments(exp.call, ret1 :: rest);
then exp;
// SEMI LINEAR
// d sL(x, m1, m2)/dt = sL(x, dm1/dt, dm2/dt) + dx/dt * if (x>=0) then m1 else m2
case (Expression.CALL()) guard(name == "semiLinear")
algorithm
{arg1, arg2, arg3} := Call.arguments(exp.call);
// dx/dt, dm1/dt, dm2/dt
(diffArg1, diffArguments) := differentiateExpression(arg1, diffArguments);
(diffArg2, diffArguments) := differentiateExpression(arg2, diffArguments);
(diffArg3, diffArguments) := differentiateExpression(arg3, diffArguments);
// sL(x, dm1/dt, dm2/dt)
exp.call := Call.setArguments(exp.call, {arg1, diffArg2, diffArg3});
ret := exp;
// only add second part if derivative is nonzero
if not Expression.isZero(diffArg1) then
ty := Expression.typeOf(diffArg1);
// x >= 0
ret1 := Expression.RELATION(arg1, Operator.makeGreaterEq(ty), Expression.makeZero(ty));
// if (x>=0) then m1 else m2
ret1 := Expression.IF(ty, ret1, arg2, arg3);
// dx/dt * if (x>=0) then m1 else m2
ret2 := Expression.MULTARY({diffArg1, ret1}, {}, mulOp);
// sL(x, dm1/dt, dm2/dt) + dx/dt * if (x>=0) then m1 else m2
ret := Expression.MULTARY({ret, ret2}, {}, addOp);
end if;
then ret;
// Builtin function call with one argument
// df(y)/dx = df/dy * dy/dx
case (Expression.CALL()) guard(listLength(Call.arguments(exp.call)) == 1)
algorithm
// differentiate the call
{arg1} := Call.arguments(exp.call);
(ret, diffArguments) := differentiateBuiltinCall1Arg(name, arg1, diffArguments);
if not Expression.isZero(ret) then
// differentiate the argument (inner derivative)
diffArg1 := differentiateExpression(arg1, diffArguments);
ret := Expression.MULTARY({ret, diffArg1}, {}, mulOp);
end if;
then ret;
// Builtin function call with two arguments
// df(y,z)/dx = df/dy * dy/dx + df/dz * dz/dx
case (Expression.CALL()) guard(listLength(Call.arguments(exp.call)) == 2)
algorithm
// differentiate the call
{arg1, arg2} := Call.arguments(exp.call);
(ret1, ret2) := differentiateBuiltinCall2Arg(name, arg1, arg2); // df/dy and df/dz
diffArg1 := differentiateExpression(arg1, diffArguments); // dy/dx
diffArg2 := differentiateExpression(arg2, diffArguments); // dz/dx
ret1 := Expression.MULTARY({ret1, diffArg1}, {}, mulOp); // df/dy * dy/dx
ret2 := Expression.MULTARY({ret2, diffArg2}, {}, mulOp); // df/dz * dz/dx
ret := Expression.MULTARY({ret1,ret2}, {}, addOp); // df/dy * dy/dx + df/dz * dz/dx
then ret;
// try some simple known cases
case (Expression.CALL()) algorithm
ret := match Call.functionNameLast(exp.call)
case "sample" then Expression.BOOLEAN(false);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for: " + Expression.toString(exp)});
then fail();
end match;
then ret;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of non-call expression: " + Expression.toString(exp)});
then fail();
end match;
end differentiateBuiltinCall;
function differentiateBuiltinCall1Arg
"differentiate a builtin call with one argument."
input String name;
input Expression arg;