source: branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/Interpreter.cs @ 17240

Last change on this file since 17240 was 17240, checked in by gkronber, 3 years ago

#2994: some minor improvements

File size: 53.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using HeuristicLab.Common;
6using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
7
8namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
9  public abstract class Interpreter<T> where T : IAlgebraicType<T> {
10    public struct Instruction {
11      public byte opcode;
12      public ushort narg;
13      public int childIndex;
14      public double dblVal;
15      public object data; // any kind of data you want to store in instructions
16      public T value;
17    }
18
19    public T Evaluate(Instruction[] code) {
20      for (int i = code.Length - 1; i >= 0; --i) {
21        var instr = code[i];
22        var c = instr.childIndex;
23        var n = instr.narg;
24
25        switch (instr.opcode) {
26          case OpCodes.Variable: {
27              LoadVariable(instr);
28              break;
29            }
30          case OpCodes.Constant: { break; }  // we initialize constants in Compile. The value never changes afterwards
31          case OpCodes.Add: {
32              instr.value.Assign(code[c].value);
33              for (int j = 1; j < n; ++j) {
34                instr.value.Add(code[c + j].value);
35              }
36              break;
37            }
38
39          case OpCodes.Sub: {
40              if (n == 1) {
41                instr.value.AssignNeg(code[c].value);
42              } else {
43                instr.value.Assign(code[c].value);
44                for (int j = 1; j < n; ++j) {
45                  instr.value.Sub(code[c + j].value);
46                }
47              }
48              break;
49            }
50
51          case OpCodes.Mul: {
52              instr.value.Assign(code[c].value);
53              for (int j = 1; j < n; ++j) {
54                instr.value.Mul(code[c + j].value);
55              }
56              break;
57            }
58
59          case OpCodes.Div: {
60              if (n == 1) {
61                instr.value.AssignInv(code[c].value);
62              } else {
63                instr.value.Assign(code[c].value);
64                for (int j = 1; j < n; ++j) {
65                  instr.value.Div(code[c + j].value);
66                }
67              }
68              break;
69            }
70          case OpCodes.Square: {
71              instr.value.AssignIntPower(code[c].value, 2);
72              break;
73            }
74          case OpCodes.SquareRoot: {
75              instr.value.AssignIntRoot(code[c].value, 2);
76              break;
77            }
78          case OpCodes.Cube: {
79              instr.value.AssignIntPower(code[c].value, 3);
80              break;
81            }
82          case OpCodes.CubeRoot: {
83              instr.value.AssignIntRoot(code[c].value, 3);
84              break;
85            }
86          case OpCodes.Exp: {
87              instr.value.AssignExp(code[c].value);
88              break;
89            }
90          case OpCodes.Log: {
91              instr.value.AssignLog(code[c].value);
92              break;
93            }
94          case OpCodes.Sin: {
95              instr.value.AssignSin(code[c].value);
96              break;
97            }
98          case OpCodes.Cos: {
99              instr.value.AssignCos(code[c].value);
100              break;
101            }
102          case OpCodes.Absolute: {
103              instr.value.AssignAbs(code[c].value);
104              break;
105            }
106          case OpCodes.AnalyticQuotient: {
107              instr.value.Assign(code[c].value);
108              for (int j = 1; j < n; ++j) {
109                var t = instr.value.One;
110                t.Add(code[c + j].value.Clone().IntPower(2));
111                instr.value.Div(t.IntRoot(2));
112              }
113              break;
114            }
115          case OpCodes.Tanh: {
116              instr.value.AssignTanh(code[c].value);
117              break;
118            }
119
120          default: throw new ArgumentException($"Unknown opcode {instr.opcode}");
121        }
122      }
123      return code[0].value;
124    }
125
126    protected Instruction[] Compile(ISymbolicExpressionTree tree) {
127      var root = tree.Root.GetSubtree(0).GetSubtree(0);
128      var code = new Instruction[root.GetLength()];
129      if (root.SubtreeCount > ushort.MaxValue) throw new ArgumentException("Number of subtrees is too big (>65.535)");
130      int c = 1, i = 0;
131      foreach (var node in root.IterateNodesBreadth()) {
132        if (node.SubtreeCount > ushort.MaxValue) throw new ArgumentException("Number of subtrees is too big (>65.535)");
133        code[i] = new Instruction {
134          opcode = OpCodes.MapSymbolToOpCode(node),
135          narg = (ushort)node.SubtreeCount,
136          childIndex = c
137        };
138        if (node is VariableTreeNode variable) {
139          InitializeTerminalInstruction(ref code[i], variable);
140        } else if (node is ConstantTreeNode constant) {
141          InitializeTerminalInstruction(ref code[i], constant);
142        } else {
143          InitializeInternalInstruction(ref code[i], node);
144        }
145        c += node.SubtreeCount;
146        ++i;
147      }
148      return code;
149    }
150
151    protected abstract void InitializeTerminalInstruction(ref Instruction instruction, ConstantTreeNode constant);
152    protected abstract void InitializeTerminalInstruction(ref Instruction instruction, VariableTreeNode variable);
153    protected abstract void InitializeInternalInstruction(ref Instruction instruction, ISymbolicExpressionTreeNode node);
154
155    protected abstract void LoadVariable(Instruction a);
156
157  }
158
159
160  public sealed class VectorEvaluator : Interpreter<AlgebraicDoubleVector> {
161    private const int BATCHSIZE = 128;
162    [ThreadStatic]
163    private Dictionary<string, double[]> cachedData;
164
165    [ThreadStatic]
166    private IDataset dataset;
167
168    [ThreadStatic]
169    private int rowIndex;
170
171    [ThreadStatic]
172    private int[] rows;
173
174    private void InitCache(IDataset dataset) {
175      this.dataset = dataset;
176      cachedData = new Dictionary<string, double[]>();
177      foreach (var v in dataset.DoubleVariables) {
178        cachedData[v] = dataset.GetReadOnlyDoubleValues(v).ToArray();
179      }
180    }
181
182    public double[] Evaluate(ISymbolicExpressionTree tree, IDataset dataset, int[] rows) {
183      if (cachedData == null || this.dataset != dataset) {
184        InitCache(dataset);
185      }
186
187      this.rows = rows;
188      var code = Compile(tree);
189      var remainingRows = rows.Length % BATCHSIZE;
190      var roundedTotal = rows.Length - remainingRows;
191
192      var result = new double[rows.Length];
193
194      for (rowIndex = 0; rowIndex < roundedTotal; rowIndex += BATCHSIZE) {
195        Evaluate(code);
196        code[0].value.CopyTo(result, rowIndex, BATCHSIZE);
197      }
198
199      if (remainingRows > 0) {
200        Evaluate(code);
201        code[0].value.CopyTo(result, roundedTotal, remainingRows);
202      }
203
204      return result;
205    }
206
207    protected override void InitializeTerminalInstruction(ref Instruction instruction, ConstantTreeNode constant) {
208      instruction.dblVal = constant.Value;
209      instruction.value = new AlgebraicDoubleVector(BATCHSIZE);
210      instruction.value.AssignConstant(instruction.dblVal);
211    }
212
213    protected override void InitializeTerminalInstruction(ref Instruction instruction, VariableTreeNode variable) {
214      instruction.dblVal = variable.Weight;
215      instruction.value = new AlgebraicDoubleVector(BATCHSIZE);
216      if (cachedData.ContainsKey(variable.VariableName)) {
217        instruction.data = cachedData[variable.VariableName];
218      } else {
219        instruction.data = dataset.GetDoubleValues(variable.VariableName).ToArray();
220        cachedData[variable.VariableName] = (double[])instruction.data;
221      }
222    }
223
224    protected override void InitializeInternalInstruction(ref Instruction instruction, ISymbolicExpressionTreeNode node) {
225      instruction.value = new AlgebraicDoubleVector(BATCHSIZE);
226    }
227
228    protected override void LoadVariable(Instruction a) {
229      var data = (double[])a.data;
230      for (int i = rowIndex; i < rows.Length && i - rowIndex < BATCHSIZE; i++) a.value[i - rowIndex] = data[rows[i]];
231      a.value.Scale(a.dblVal);
232    }
233  }
234
235  public sealed class VectorAutoDiffEvaluator : Interpreter<MultivariateDual<AlgebraicDoubleVector>> {
236    private const int BATCHSIZE = 128;
237    [ThreadStatic]
238    private Dictionary<string, double[]> cachedData;
239
240    [ThreadStatic]
241    private IDataset dataset;
242
243    [ThreadStatic]
244    private int rowIndex;
245
246    [ThreadStatic]
247    private int[] rows;
248
249    [ThreadStatic]
250    private Dictionary<ISymbolicExpressionTreeNode, int> node2paramIdx;
251
252    private void InitCache(IDataset dataset) {
253      this.dataset = dataset;
254      cachedData = new Dictionary<string, double[]>();
255      foreach (var v in dataset.DoubleVariables) {
256        cachedData[v] = dataset.GetDoubleValues(v).ToArray();
257      }
258    }
259
260    /// <summary>
261    ///
262    /// </summary>
263    /// <param name="tree"></param>
264    /// <param name="dataset"></param>
265    /// <param name="rows"></param>
266    /// <param name="parameterNodes"></param>
267    /// <param name="fi">Function output. Must be allocated by the caller.</param>
268    /// <param name="jac">Jacobian matrix. Must be allocated by the caller.</param>
269    public void Evaluate(ISymbolicExpressionTree tree, IDataset dataset, int[] rows, ISymbolicExpressionTreeNode[] parameterNodes, double[] fi, double[,] jac) {
270      if (cachedData == null || this.dataset != dataset) {
271        InitCache(dataset);
272      }
273
274      int nParams = parameterNodes.Length;
275      node2paramIdx = new Dictionary<ISymbolicExpressionTreeNode, int>();
276      for (int i = 0; i < parameterNodes.Length; i++) node2paramIdx.Add(parameterNodes[i], i);
277
278      var code = Compile(tree);
279
280      var remainingRows = rows.Length % BATCHSIZE;
281      var roundedTotal = rows.Length - remainingRows;
282
283      this.rows = rows;
284
285      for (rowIndex = 0; rowIndex < roundedTotal; rowIndex += BATCHSIZE) {
286        Evaluate(code);
287        code[0].value.Value.CopyTo(fi, rowIndex, BATCHSIZE);
288
289        // TRANSPOSE into JAC
290        var g = code[0].value.Gradient;
291        for (int j = 0; j < nParams; ++j) {
292          if (g.Elements.TryGetValue(j, out AlgebraicDoubleVector v)) {
293            v.CopyColumnTo(jac, j, rowIndex, BATCHSIZE);
294          } else {
295            for (int r = 0; r < BATCHSIZE; r++) jac[rowIndex + r, j] = 0.0;
296          }
297        }
298      }
299
300      if (remainingRows > 0) {
301        Evaluate(code);
302        code[0].value.Value.CopyTo(fi, roundedTotal, remainingRows);
303
304        var g = code[0].value.Gradient;
305        for (int j = 0; j < nParams; ++j)
306          if (g.Elements.TryGetValue(j, out AlgebraicDoubleVector v)) {
307            v.CopyColumnTo(jac, j, roundedTotal, remainingRows);
308          } else {
309            for (int r = 0; r < remainingRows; r++) jac[roundedTotal + r, j] = 0.0;
310          }
311      }
312    }
313
314    protected override void InitializeInternalInstruction(ref Instruction instruction, ISymbolicExpressionTreeNode node) {
315      var zero = new AlgebraicDoubleVector(BATCHSIZE);
316      instruction.value = new MultivariateDual<AlgebraicDoubleVector>(zero);
317    }
318
319    protected override void InitializeTerminalInstruction(ref Instruction instruction, ConstantTreeNode constant) {
320      var g_arr = new double[BATCHSIZE];
321      if (node2paramIdx.TryGetValue(constant, out var paramIdx)) {
322        for (int i = 0; i < BATCHSIZE; i++) g_arr[i] = 1.0;
323        var g = new AlgebraicDoubleVector(g_arr);
324        instruction.value = new MultivariateDual<AlgebraicDoubleVector>(new AlgebraicDoubleVector(BATCHSIZE), paramIdx, g); // only a single column for the gradient
325      } else {
326        instruction.value = new MultivariateDual<AlgebraicDoubleVector>(new AlgebraicDoubleVector(BATCHSIZE));
327      }
328
329      instruction.dblVal = constant.Value;
330      instruction.value.Value.AssignConstant(instruction.dblVal);
331    }
332
333    protected override void InitializeTerminalInstruction(ref Instruction instruction, VariableTreeNode variable) {
334      double[] data;
335      if (cachedData.ContainsKey(variable.VariableName)) {
336        data = cachedData[variable.VariableName];
337      } else {
338        data = dataset.GetReadOnlyDoubleValues(variable.VariableName).ToArray();
339        cachedData[variable.VariableName] = (double[])instruction.data;
340      }
341
342      var paramIdx = -1;
343      if (node2paramIdx.ContainsKey(variable)) {
344        paramIdx = node2paramIdx[variable];
345        var f = new AlgebraicDoubleVector(BATCHSIZE);
346        var g = new AlgebraicDoubleVector(BATCHSIZE);
347        instruction.value = new MultivariateDual<AlgebraicDoubleVector>(f, paramIdx, g);
348      } else {
349        var f = new AlgebraicDoubleVector(BATCHSIZE);
350        instruction.value = new MultivariateDual<AlgebraicDoubleVector>(f);
351      }
352
353      instruction.dblVal = variable.Weight;
354      instruction.data = new object[] { data, paramIdx };
355    }
356
357    protected override void LoadVariable(Instruction a) {
358      var paramIdx = (int)((object[])a.data)[1];
359      var data = (double[])((object[])a.data)[0];
360
361      for (int i = rowIndex; i < rows.Length && i - rowIndex < BATCHSIZE; i++) a.value.Value[i - rowIndex] = data[rows[i]];
362      a.value.Scale(a.dblVal);
363
364      if (paramIdx >= 0) {
365        // update gradient with variable values
366        var g = a.value.Gradient.Elements[paramIdx];
367        for (int i = rowIndex; i < rows.Length && i - rowIndex < BATCHSIZE; i++) {
368          g[i - rowIndex] = data[rows[i]];
369        }
370      }
371    }
372  }
373
374
375  public sealed class IntervalEvaluator : Interpreter<AlgebraicInterval> {
376    [ThreadStatic]
377    private IDictionary<string, Interval> intervals;
378
379    public Interval Evaluate(ISymbolicExpressionTree tree, IDictionary<string, Interval> intervals) {
380      this.intervals = intervals;
381      var code = Compile(tree);
382      Evaluate(code);
383      return new Interval(code[0].value.LowerBound.Value.Value, code[0].value.UpperBound.Value.Value);
384    }
385
386    public Interval Evaluate(ISymbolicExpressionTree tree, IDictionary<string, Interval> intervals, ISymbolicExpressionTreeNode[] paramNodes, out double[] lowerGradient, out double[] upperGradient) {
387      this.intervals = intervals;
388      var code = Compile(tree);
389      Evaluate(code);
390      lowerGradient = new double[paramNodes.Length];
391      upperGradient = new double[paramNodes.Length];
392      var l = code[0].value.LowerBound;
393      var u = code[0].value.UpperBound;
394      for (int i = 0; i < paramNodes.Length; ++i) {
395        if (paramNodes[i] == null) continue;
396        if (l.Gradient.Elements.TryGetValue(paramNodes[i], out AlgebraicDouble value)) lowerGradient[i] = value;
397        if (u.Gradient.Elements.TryGetValue(paramNodes[i], out value)) upperGradient[i] = value;
398      }
399      return new Interval(code[0].value.LowerBound.Value.Value, code[0].value.UpperBound.Value.Value);
400    }
401
402    protected override void InitializeInternalInstruction(ref Instruction instruction, ISymbolicExpressionTreeNode node) {
403      instruction.value = new AlgebraicInterval(0, 0);
404    }
405
406
407    protected override void InitializeTerminalInstruction(ref Instruction instruction, ConstantTreeNode constant) {
408      instruction.dblVal = constant.Value;
409      instruction.value = new AlgebraicInterval(
410        new MultivariateDual<AlgebraicDouble>(constant.Value, constant, 1.0),
411        new MultivariateDual<AlgebraicDouble>(constant.Value, constant, 1.0) // use node as key
412        );
413    }
414
415    protected override void InitializeTerminalInstruction(ref Instruction instruction, VariableTreeNode variable) {
416      instruction.dblVal = variable.Weight;
417      instruction.value = new AlgebraicInterval(
418        low: new MultivariateDual<AlgebraicDouble>(intervals[variable.VariableName].LowerBound, variable, intervals[variable.VariableName].LowerBound),  // bounds change by variable value d/dc (c I(var)) = I(var)
419        high: new MultivariateDual<AlgebraicDouble>(intervals[variable.VariableName].UpperBound, variable, intervals[variable.VariableName].UpperBound)
420        );
421    }
422
423    protected override void LoadVariable(Instruction a) {
424      // nothing to do
425    }
426  }
427
428  public interface IAlgebraicType<T> {
429    T Zero { get; }
430    T One { get; }
431
432    T AssignAbs(T a); // set this to assign abs(a)
433    T Assign(T a); // assign this to same value as a (copy!)
434    T AssignNeg(T a); // set this to negative(a)
435    T AssignInv(T a); // set this to inv(a);
436    T Scale(double s); // scale this with s
437    T Add(T a); // add a to this
438    T Sub(T a); // subtract a from this
439    T Mul(T a); // multiply this with a
440    T Div(T a); // divide this by a
441    T AssignLog(T a); // set this to log a
442    T AssignExp(T a); // set this to exp(a)
443    T AssignSin(T a); // set this to sin(a)
444    T AssignCos(T a); // set this to cos(a)
445    T AssignTanh(T a); // set this to tanh(a)
446    T AssignIntPower(T a, int p);
447    T AssignIntRoot(T a, int r);
448    T AssignSgn(T a); // set this to sign(a)
449    T Clone();
450  }
451
452  public static class Algebraic {
453    public static T Abs<T>(this T a) where T : IAlgebraicType<T> { a.AssignAbs(a.Clone()); return a; }
454    public static T Neg<T>(this T a) where T : IAlgebraicType<T> { a.AssignNeg(a.Clone()); return a; }
455    public static T Inv<T>(this T a) where T : IAlgebraicType<T> { a.AssignInv(a.Clone()); return a; }
456    public static T Log<T>(this T a) where T : IAlgebraicType<T> { a.AssignLog(a.Clone()); return a; }
457    public static T Exp<T>(this T a) where T : IAlgebraicType<T> { a.AssignExp(a.Clone()); return a; }
458    public static T Sin<T>(this T a) where T : IAlgebraicType<T> { a.AssignSin(a.Clone()); return a; }
459    public static T Cos<T>(this T a) where T : IAlgebraicType<T> { a.AssignCos(a.Clone()); return a; }
460    public static T Sgn<T>(this T a) where T : IAlgebraicType<T> { a.AssignSgn(a.Clone()); return a; }
461    public static T IntPower<T>(this T a, int p) where T : IAlgebraicType<T> { a.AssignIntPower(a.Clone(), p); return a; }
462    public static T IntRoot<T>(this T a, int r) where T : IAlgebraicType<T> { a.AssignIntRoot(a.Clone(), r); return a; }
463
464    public static T Max<T>(T a, T b) where T : IAlgebraicType<T> {
465      // ((a + b) + abs(b - a)) / 2
466      return a.Clone().Add(b).Add(b.Clone().Sub(a).Abs()).Scale(1.0 / 2.0);
467    }
468    public static T Min<T>(T a, T b) where T : IAlgebraicType<T> {
469      // ((a + b) - abs(a - b)) / 2
470      return a.Clone().Add(b).Sub(a.Clone().Sub(b).Abs()).Scale(1.0 / 2.0);
471    }
472  }
473
474
475  // algebraic type wrapper for a double value
476  [DebuggerDisplay("{Value}")]
477  public sealed class AlgebraicDouble : IAlgebraicType<AlgebraicDouble> {
478    public static implicit operator AlgebraicDouble(double value) { return new AlgebraicDouble(value); }
479    public static implicit operator double(AlgebraicDouble value) { return value.Value; }
480    public double Value;
481
482    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
483    public AlgebraicDouble Zero => new AlgebraicDouble(0.0);
484    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
485    public AlgebraicDouble One => new AlgebraicDouble(1.0);
486
487    public bool IsInfinity => IsNegativeInfinity || IsPositiveInfinity;
488    public bool IsNegativeInfinity => double.IsNegativeInfinity(Value);
489    public bool IsPositiveInfinity => double.IsPositiveInfinity(Value);
490    public AlgebraicDouble() { }
491    public AlgebraicDouble(double value) { this.Value = value; }
492    public AlgebraicDouble Assign(AlgebraicDouble a) { Value = a.Value; return this; }
493    public AlgebraicDouble Add(AlgebraicDouble a) { Value += a.Value; return this; }
494    public AlgebraicDouble Sub(AlgebraicDouble a) { Value -= a.Value; return this; }
495    public AlgebraicDouble Mul(AlgebraicDouble a) { Value *= a.Value; return this; }
496    public AlgebraicDouble Div(AlgebraicDouble a) { Value /= a.Value; return this; }
497    public AlgebraicDouble Scale(double s) { Value *= s; return this; }
498    public AlgebraicDouble AssignInv(AlgebraicDouble a) { Value = 1.0 / a.Value; return this; }
499    public AlgebraicDouble AssignNeg(AlgebraicDouble a) { Value = -a.Value; return this; }
500    public AlgebraicDouble AssignSin(AlgebraicDouble a) { Value = Math.Sin(a.Value); return this; }
501    public AlgebraicDouble AssignCos(AlgebraicDouble a) { Value = Math.Cos(a.Value); return this; }
502    public AlgebraicDouble AssignTanh(AlgebraicDouble a) { Value = Math.Tanh(a.Value); return this; }
503    public AlgebraicDouble AssignLog(AlgebraicDouble a) { Value = Math.Log(a.Value); return this; }
504    public AlgebraicDouble AssignExp(AlgebraicDouble a) { Value = Math.Exp(a.Value); return this; }
505    public AlgebraicDouble AssignIntPower(AlgebraicDouble a, int p) { Value = Math.Pow(a.Value, p); return this; }
506    public AlgebraicDouble AssignIntRoot(AlgebraicDouble a, int r) { Value = IntRoot(a.Value, r); return this; }
507
508    // helper
509    private static double IntRoot(double value, int r) {
510      if (r % 2 == 0) return Math.Pow(value, 1.0 / r);
511      else return value < 0 ? -Math.Pow(-value, 1.0 / r) : Math.Pow(value, 1.0 / r);
512    }
513
514    public AlgebraicDouble AssignAbs(AlgebraicDouble a) { Value = Math.Abs(a.Value); return this; }
515    public AlgebraicDouble AssignSgn(AlgebraicDouble a) { Value = double.IsNaN(a.Value) ? double.NaN : Math.Sign(a.Value); return this; }
516    public AlgebraicDouble Clone() { return new AlgebraicDouble(Value); }
517
518    public override string ToString() {
519      return Value.ToString();
520    }
521  }
522
523  // a simple vector as an algebraic type
524  [DebuggerDisplay("DoubleVector(len={Length}): {string.}")]
525  public class AlgebraicDoubleVector : IAlgebraicType<AlgebraicDoubleVector> {
526    private double[] arr;
527    public double this[int idx] { get { return arr[idx]; } set { arr[idx] = value; } }
528    public int Length => arr.Length;
529
530    public AlgebraicDoubleVector(int length) { arr = new double[length]; }
531
532    public AlgebraicDoubleVector() { }
533
534    /// <summary>
535    ///
536    /// </summary>
537    /// <param name="arr">array is not copied</param>
538    public AlgebraicDoubleVector(double[] arr) { this.arr = arr; }
539
540    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
541    public AlgebraicDoubleVector Zero => new AlgebraicDoubleVector(new double[this.Length]); // must return vector of same length as this (therefore Zero is not static)
542    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
543    public AlgebraicDoubleVector One => new AlgebraicDoubleVector(new double[this.Length]).AssignConstant(1.0); // must return vector of same length as this (therefore Zero is not static)
544    public AlgebraicDoubleVector Assign(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = a.arr[i]; } return this; }
545    public AlgebraicDoubleVector Add(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] += a.arr[i]; } return this; }
546    public AlgebraicDoubleVector Sub(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] -= a.arr[i]; } return this; }
547    public AlgebraicDoubleVector Mul(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] *= a.arr[i]; } return this; }
548    public AlgebraicDoubleVector Div(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] /= a.arr[i]; } return this; }
549    public AlgebraicDoubleVector AssignNeg(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = -a.arr[i]; } return this; }
550    public AlgebraicDoubleVector AssignInv(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = 1.0 / a.arr[i]; } return this; }
551    public AlgebraicDoubleVector Scale(double s) { for (int i = 0; i < arr.Length; ++i) { arr[i] *= s; } return this; }
552    public AlgebraicDoubleVector AssignLog(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Log(a.arr[i]); } return this; }
553    public AlgebraicDoubleVector AssignSin(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Sin(a.arr[i]); } return this; }
554    public AlgebraicDoubleVector AssignExp(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Exp(a.arr[i]); } return this; }
555    public AlgebraicDoubleVector AssignCos(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Cos(a.arr[i]); } return this; }
556    public AlgebraicDoubleVector AssignTanh(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Tanh(a.arr[i]); } return this; }
557    public AlgebraicDoubleVector AssignIntPower(AlgebraicDoubleVector a, int p) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Pow(a.arr[i], p); } return this; }
558    public AlgebraicDoubleVector AssignIntRoot(AlgebraicDoubleVector a, int r) { for (int i = 0; i < arr.Length; ++i) { arr[i] = IntRoot(a.arr[i], r); } return this; }
559
560    // helper
561    private double IntRoot(double v, int r) {
562      if (r % 2 == 0) return Math.Pow(v, 1.0 / r);
563      else return v < 0 ? -Math.Pow(-v, 1.0 / r) : Math.Pow(v, 1.0 / r);
564    }
565
566    public AlgebraicDoubleVector AssignAbs(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Abs(a.arr[i]); } return this; }
567    public AlgebraicDoubleVector AssignSgn(AlgebraicDoubleVector a) { for (int i = 0; i < arr.Length; ++i) { arr[i] = Math.Sign(a.arr[i]); } return this; }
568
569    public AlgebraicDoubleVector Clone() {
570      var v = new AlgebraicDoubleVector(this.arr.Length);
571      Array.Copy(arr, v.arr, v.arr.Length);
572      return v;
573    }
574
575    public AlgebraicDoubleVector AssignConstant(double constantValue) {
576      for (int i = 0; i < arr.Length; ++i) {
577        arr[i] = constantValue;
578      }
579      return this;
580    }
581
582    public void CopyTo(double[] dest, int idx, int length) {
583      Array.Copy(arr, 0, dest, idx, length);
584    }
585
586    public void CopyFrom(double[] data, int rowIndex) {
587      Array.Copy(data, rowIndex, arr, 0, Math.Min(arr.Length, data.Length - rowIndex));
588    }
589    public void CopyRowTo(double[,] dest, int row) {
590      for (int j = 0; j < arr.Length; ++j) dest[row, j] = arr[j];
591    }
592
593    internal void CopyColumnTo(double[,] dest, int column, int row, int len) {
594      for (int j = 0; j < len; ++j) dest[row + j, column] = arr[j];
595    }
596
597    public override string ToString() {
598      return "{" + string.Join(", ", arr.Take(Math.Max(5, arr.Length))) + (arr.Length > 5 ? "..." : string.Empty) + "}";
599    }
600  }
601
602
603  /*
604  // vectors of algebraic types
605  public sealed class AlgebraicVector<T> : IAlgebraicType<AlgebraicVector<T>> where T : IAlgebraicType<T>, new() {
606    private T[] elems;
607
608    public T this[int idx] { get { return elems[idx]; } set { elems[idx] = value; } }
609
610    public int Length => elems.Length;
611
612    private AlgebraicVector() { }
613
614    public AlgebraicVector(int len) { elems = new T[len]; }
615
616    /// <summary>
617    ///
618    /// </summary>
619    /// <param name="elems">The array is copied (element-wise clone)</param>
620    public AlgebraicVector(T[] elems) {
621      this.elems = new T[elems.Length];
622      for (int i = 0; i < elems.Length; ++i) { this.elems[i] = elems[i].Clone(); }
623    }
624
625    /// <summary>
626    ///
627    /// </summary>
628    /// <param name="elems">Array is not copied!</param>
629    /// <returns></returns>
630    public AlgebraicVector<T> FromArray(T[] elems) {
631      var v = new AlgebraicVector<T>();
632      v.elems = elems;
633      return v;
634    }
635
636    public void CopyTo(T[] dest) {
637      if (dest.Length != elems.Length) throw new InvalidOperationException("arr lengths do not match in Vector<T>.Copy");
638      Array.Copy(elems, dest, dest.Length);
639    }
640
641    public AlgebraicVector<T> Clone() { return new AlgebraicVector<T>(elems); }
642
643
644    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
645    public AlgebraicVector<T> Zero => new AlgebraicVector<T>(Length);
646    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
647    public AlgebraicVector<T> One { get { var v = new AlgebraicVector<T>(Length); for (int i = 0; i < elems.Length; ++i) elems[i] = new T().One; return v; } }
648    public AlgebraicVector<T> Assign(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].Assign(a.elems[i]); } return this; }
649    public AlgebraicVector<T> Add(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].Add(a.elems[i]); } return this; }
650    public AlgebraicVector<T> Sub(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].Sub(a.elems[i]); } return this; }
651    public AlgebraicVector<T> Mul(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].Mul(a.elems[i]); } return this; }
652    public AlgebraicVector<T> Div(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].Div(a.elems[i]); } return this; }
653    public AlgebraicVector<T> AssignNeg(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignNeg(a.elems[i]); } return this; }
654    public AlgebraicVector<T> Scale(double s) { for (int i = 0; i < elems.Length; ++i) { elems[i].Scale(s); } return this; }
655    public AlgebraicVector<T> Scale(T s) { for (int i = 0; i < elems.Length; ++i) { elems[i].Mul(s); } return this; }
656    public AlgebraicVector<T> AssignInv(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignInv(a.elems[i]); } return this; }
657    public AlgebraicVector<T> AssignLog(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignLog(a.elems[i]); } return this; }
658    public AlgebraicVector<T> AssignExp(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignExp(a.elems[i]); } return this; }
659    public AlgebraicVector<T> AssignSin(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignSin(a.elems[i]); } return this; }
660    public AlgebraicVector<T> AssignCos(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignCos(a.elems[i]); } return this; }
661    public AlgebraicVector<T> AssignIntPower(AlgebraicVector<T> a, int p) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignIntPower(a.elems[i], p); } return this; }
662    public AlgebraicVector<T> AssignIntRoot(AlgebraicVector<T> a, int r) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignIntRoot(a.elems[i], r); } return this; }
663    public AlgebraicVector<T> AssignAbs(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignAbs(a.elems[i]); } return this; }
664    public AlgebraicVector<T> AssignSgn(AlgebraicVector<T> a) { for (int i = 0; i < elems.Length; ++i) { elems[i].AssignSgn(a.elems[i]); } return this; }
665  }
666
667  */
668
669
670  /// <summary>
671  /// A sparse vector of algebraic types. Elements are accessed via a key of type K
672  /// </summary>
673  /// <typeparam name="K">Key type</typeparam>
674  /// <typeparam name="T">Element type</typeparam>
675  [DebuggerDisplay("SparseVector: {ToString()}")]
676  public sealed class AlgebraicSparseVector<K, T> : IAlgebraicType<AlgebraicSparseVector<K, T>> where T : IAlgebraicType<T> {
677    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
678    private Dictionary<K, T> elems;
679    public IReadOnlyDictionary<K, T> Elements => elems;
680
681
682    public AlgebraicSparseVector(AlgebraicSparseVector<K, T> original) {
683      elems = original.elems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Clone());
684    }
685
686    /// <summary>
687    ///
688    /// </summary>
689    /// <param name="keys"></param>
690    /// <param name="values">values are cloned</param>
691    public AlgebraicSparseVector(K[] keys, T[] values) {
692      if (keys.Length != values.Length) throw new ArgumentException("lengths of keys and values doesn't match in SparseVector");
693      elems = new Dictionary<K, T>(keys.Length);
694      for (int i = 0; i < keys.Length; ++i) {
695        elems.Add(keys[i], values[i].Clone());
696      }
697    }
698
699    public AlgebraicSparseVector() {
700      this.elems = new Dictionary<K, T>();
701    }
702
703    // keep only elements from a
704    private void AssignFromSource(AlgebraicSparseVector<K, T> a, Func<T, T, T> mapAssign) {
705      // remove elems from this which don't occur in a
706      List<K> keysToRemove = new List<K>();
707      foreach (var kvp in elems) {
708        if (!a.elems.ContainsKey(kvp.Key)) keysToRemove.Add(kvp.Key);
709      }
710      foreach (var o in keysToRemove) elems.Remove(o); // -> zero
711
712      foreach (var kvp in a.elems) {
713        if (elems.TryGetValue(kvp.Key, out T value))
714          mapAssign(kvp.Value, value);
715        else
716          elems.Add(kvp.Key, mapAssign(kvp.Value, kvp.Value.Zero));
717      }
718    }
719
720    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
721    public AlgebraicSparseVector<K, T> Zero => new AlgebraicSparseVector<K, T>();
722    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
723    public AlgebraicSparseVector<K, T> One => throw new NotSupportedException();
724
725    public AlgebraicSparseVector<K, T> Scale(T s) { foreach (var kvp in elems) { kvp.Value.Mul(s); } return this; }
726    public AlgebraicSparseVector<K, T> Scale(double s) { foreach (var kvp in elems) { kvp.Value.Scale(s); } return this; }
727
728    public AlgebraicSparseVector<K, T> Assign(AlgebraicSparseVector<K, T> a) { elems.Clear(); AssignFromSource(a, (src, dest) => dest.Assign(src)); return this; }
729    public AlgebraicSparseVector<K, T> AssignInv(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignInv(src)); return this; }
730    public AlgebraicSparseVector<K, T> AssignNeg(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignNeg(src)); return this; }
731    public AlgebraicSparseVector<K, T> AssignLog(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignLog(src)); return this; }
732    public AlgebraicSparseVector<K, T> AssignExp(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignExp(src)); return this; }
733    public AlgebraicSparseVector<K, T> AssignIntPower(AlgebraicSparseVector<K, T> a, int p) { AssignFromSource(a, (src, dest) => dest.AssignIntPower(src, p)); return this; }
734    public AlgebraicSparseVector<K, T> AssignIntRoot(AlgebraicSparseVector<K, T> a, int r) { AssignFromSource(a, (src, dest) => dest.AssignIntRoot(src, r)); return this; }
735    public AlgebraicSparseVector<K, T> AssignSin(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignSin(src)); return this; }
736    public AlgebraicSparseVector<K, T> AssignCos(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignCos(src)); return this; }
737    public AlgebraicSparseVector<K, T> AssignTanh(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignTanh(src)); return this; }
738    public AlgebraicSparseVector<K, T> AssignAbs(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignAbs(src)); return this; }
739    public AlgebraicSparseVector<K, T> AssignSgn(AlgebraicSparseVector<K, T> a) { AssignFromSource(a, (src, dest) => dest.AssignSgn(src)); return this; }
740    public AlgebraicSparseVector<K, T> Add(AlgebraicSparseVector<K, T> a) {
741      foreach (var kvp in a.elems) {
742        if (elems.TryGetValue(kvp.Key, out T value))
743          value.Add(kvp.Value);
744        else
745          elems.Add(kvp.Key, kvp.Value.Clone()); // 0 + a
746      }
747      return this;
748    }
749
750    public AlgebraicSparseVector<K, T> Sub(AlgebraicSparseVector<K, T> a) {
751      foreach (var kvp in a.elems) {
752        if (elems.TryGetValue(kvp.Key, out T value))
753          value.Sub(kvp.Value);
754        else
755          elems.Add(kvp.Key, kvp.Value.Zero.Sub(kvp.Value)); // 0 - a
756      }
757      return this;
758    }
759
760    public AlgebraicSparseVector<K, T> Mul(AlgebraicSparseVector<K, T> a) {
761      var keys = elems.Keys.ToArray();
762      foreach (var k in keys) if (!a.elems.ContainsKey(k)) elems.Remove(k); // 0 * a => 0
763      foreach (var kvp in a.elems) {
764        if (elems.TryGetValue(kvp.Key, out T value))
765          value.Mul(kvp.Value); // this * a
766      }
767      return this;
768    }
769
770    public AlgebraicSparseVector<K, T> Div(AlgebraicSparseVector<K, T> a) {
771      return Mul(a.Clone().Inv());
772    }
773
774    public AlgebraicSparseVector<K, T> Clone() {
775      return new AlgebraicSparseVector<K, T>(this);
776    }
777
778    public override string ToString() {
779      return "[" + string.Join(" ", elems.Select(kvp => kvp.Key + ": " + kvp.Value)) + "]";
780    }
781  }
782
783  // this is our own implementation of interval arithmetic
784  // for a well worked out definition of interval operations for IEEE reals see:
785  // Stahl: Interval Methods for Bounding the Range of Polynomials and Solving Systems of Nonlinear Equations, Dissertation, JKU, 1995
786  [DebuggerDisplay("[{low.Value}..{high.Value}]")]
787  public class AlgebraicInterval : IAlgebraicType<AlgebraicInterval> {
788    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
789    private MultivariateDual<AlgebraicDouble> low;
790    public MultivariateDual<AlgebraicDouble> LowerBound => low.Clone();
791
792    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
793    private MultivariateDual<AlgebraicDouble> high;
794    public MultivariateDual<AlgebraicDouble> UpperBound => high.Clone();
795
796
797    public AlgebraicInterval() : this(double.NegativeInfinity, double.PositiveInfinity) { }
798
799    public AlgebraicInterval(MultivariateDual<AlgebraicDouble> low, MultivariateDual<AlgebraicDouble> high) {
800      this.low = low.Clone();
801      this.high = high.Clone();
802    }
803
804    public AlgebraicInterval(double low, double high) {
805      this.low = new MultivariateDual<AlgebraicDouble>(new AlgebraicDouble(low));
806      this.high = new MultivariateDual<AlgebraicDouble>(new AlgebraicDouble(high));
807    }
808
809    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
810    public AlgebraicInterval Zero => new AlgebraicInterval(0.0, 0.0);
811    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
812    public AlgebraicInterval One => new AlgebraicInterval(1.0, 1.0);
813
814    public AlgebraicInterval Add(AlgebraicInterval a) {
815      low.Add(a.low);
816      high.Add(a.high);
817      return this;
818    }
819
820    public AlgebraicInterval Mul(AlgebraicInterval a) {
821      var v1 = low.Clone().Mul(a.low);
822      var v2 = low.Clone().Mul(a.high);
823      var v3 = high.Clone().Mul(a.low);
824      var v4 = high.Clone().Mul(a.high);
825
826      low = Min(Min(v1, v2), Min(v3, v4));
827      high = Max(Max(v1, v2), Max(v3, v4));
828
829      return this;
830    }
831
832    // algebraic min() / max() do not work for infinities
833    // detect and handle infinite values explicitly
834    private static MultivariateDual<AlgebraicDouble> Min(MultivariateDual<AlgebraicDouble> a, MultivariateDual<AlgebraicDouble> b) {
835      if (a.Value.IsInfinity || b.Value.IsInfinity) return a.Value < b.Value ? a : b; // NOTE: this is not differentiable but for infinite values we do not care
836      else return Algebraic.Min(a, b); // differentiable statement
837    }
838    private static MultivariateDual<AlgebraicDouble> Max(MultivariateDual<AlgebraicDouble> a, MultivariateDual<AlgebraicDouble> b) {
839      if (a.Value.IsInfinity || b.Value.IsInfinity) return a.Value >= b.Value ? a : b; // NOTE: this is not differentiable but for infinite values we do not care
840      else return Algebraic.Max(a, b); // differentiable statement
841    }
842
843    public AlgebraicInterval Assign(AlgebraicInterval a) {
844      low = a.low;
845      high = a.high;
846      return this;
847    }
848
849    public AlgebraicInterval AssignCos(AlgebraicInterval a) {
850      return AssignSin(a.Clone().Add(new AlgebraicInterval(Math.PI / 2, Math.PI / 2)));
851    }
852
853    public AlgebraicInterval Div(AlgebraicInterval a) {
854      if (a.Contains(0.0)) {
855        if (a.low.Value.Value == 0 && a.high.Value.Value == 0) {
856          if (this.low.Value >= 0) {
857            // pos / 0
858          } else if (this.high.Value <= 0) {
859            // neg / 0
860          } else {
861            low = new MultivariateDual<AlgebraicDouble>(double.NegativeInfinity);
862            high = new MultivariateDual<AlgebraicDouble>(double.PositiveInfinity);
863          }
864        } else if (a.low.Value.Value >= 0) {
865          // a is positive
866          Mul(new AlgebraicInterval(a.Clone().high.Inv(), new MultivariateDual<AlgebraicDouble>(double.PositiveInfinity)));
867        } else if (a.high.Value <= 0) {
868          // a is negative
869          Mul(new AlgebraicInterval(new MultivariateDual<AlgebraicDouble>(double.NegativeInfinity), a.low.Clone().Inv()));
870        } else {
871          // a is interval over zero
872          low = new MultivariateDual<AlgebraicDouble>(double.NegativeInfinity);
873          high = new MultivariateDual<AlgebraicDouble>(double.PositiveInfinity);
874        }
875      } else {
876        Mul(new AlgebraicInterval(a.high.Clone().Inv(), a.low.Clone().Inv())); // inverting leads to inverse roles of high and low
877      }
878      return this;
879    }
880
881    public AlgebraicInterval AssignExp(AlgebraicInterval a) {
882      low.AssignExp(a.low);
883      high.AssignExp(a.high);
884      return this;
885    }
886
887    // tanh is a bijective function
888    public AlgebraicInterval AssignTanh(AlgebraicInterval a) {
889      low.AssignTanh(a.low);
890      high.AssignTanh(a.high);
891      return this;
892    }
893
894    public AlgebraicInterval AssignIntPower(AlgebraicInterval a, int p) {
895      if (p < 0) {  // x^-3 == 1/(x^3)
896        AssignIntPower(a, -p);
897        return AssignInv(this);
898      } else if (p == 0) {
899        if (a.Contains(0.0)) {
900          // => 0^0 = 0 ; might not be relevant
901          low = new MultivariateDual<AlgebraicDouble>(0.0);
902          high = new MultivariateDual<AlgebraicDouble>(1.0);
903          return this;
904        } else {
905          // => 1
906          low = new MultivariateDual<AlgebraicDouble>(1.0);
907          high = new MultivariateDual<AlgebraicDouble>(1.0);
908          return this;
909        }
910      } else if (p == 1) return this;
911      else if (p % 2 == 0) {
912        // p is even => interval must be positive
913        if (a.Contains(0.0)) {
914          low = new MultivariateDual<AlgebraicDouble>(0.0);
915          high = Algebraic.Max(a.low.IntPower(p), a.high.IntPower(p));
916        } else {
917          var lowPower = a.low.IntPower(p);
918          var highPower = a.high.IntPower(p);
919          low = Algebraic.Min(lowPower, highPower);
920          high = Algebraic.Max(lowPower, highPower);
921        }
922      } else {
923        // p is uneven
924        if (a.Contains(0.0)) {
925          low.AssignIntPower(a.low, p);
926          high.AssignIntPower(a.high, p);
927        } else {
928          var lowPower = a.low.IntPower(p);
929          var highPower = a.high.IntPower(p);
930          low = Algebraic.Min(lowPower, highPower);
931          high = Algebraic.Max(lowPower, highPower);
932        }
933      }
934      return this;
935    }
936
937    public AlgebraicInterval AssignIntRoot(AlgebraicInterval a, int r) {
938      if (r == 0) { low = new MultivariateDual<AlgebraicDouble>(double.NaN); high = new MultivariateDual<AlgebraicDouble>(double.NaN); return this; }
939      if (r == 1) return this;
940      if (r < 0) {
941        // x^ (-1/2) = 1 / (x^(1/2))
942        AssignIntRoot(a, -r);
943        return AssignInv(this);
944      } else {
945        // root only defined for positive arguments for even roots
946        if (r % 2 == 0 && a.LowerBound.Value.Value < 0) {
947          low = new MultivariateDual<AlgebraicDouble>(double.NaN);
948          high = new MultivariateDual<AlgebraicDouble>(double.NaN);
949          return this;
950        } else {
951          low.AssignIntRoot(a.low, r);
952          high.AssignIntRoot(a.high, r);
953          return this;
954        }
955      }
956    }
957
958    public AlgebraicInterval AssignInv(AlgebraicInterval a) {
959      low = new MultivariateDual<AlgebraicDouble>(1.0);
960      high = new MultivariateDual<AlgebraicDouble>(1.0);
961      return Div(a);
962    }
963
964    public AlgebraicInterval AssignLog(AlgebraicInterval a) {
965      low.AssignLog(a.low);
966      high.AssignLog(a.high);
967      return this;
968    }
969
970    public AlgebraicInterval AssignNeg(AlgebraicInterval a) {
971      low.AssignNeg(a.high);
972      high.AssignNeg(a.low);
973      return this;
974    }
975
976    public AlgebraicInterval Scale(double s) {
977      low.Scale(s);
978      high.Scale(s);
979      if (s < 0) {
980        var t = low;
981        low = high;
982        high = t;
983      }
984      return this;
985    }
986
987    public AlgebraicInterval AssignSin(AlgebraicInterval a) {
988      var lower = a.LowerBound.Value.Value;
989      var size = a.UpperBound.Value.Value - lower;
990      if (size < 0) throw new InvalidProgramException(); // ASSERT interval >= 0;
991
992      if (size >= Math.PI * 2) {
993        low = new MultivariateDual<AlgebraicDouble>(-1.0); // zero gradient
994        high = new MultivariateDual<AlgebraicDouble>(1.0);
995        return this;
996      }
997
998      // assume low and high are in the same quadrant
999      low = Algebraic.Min(a.LowerBound.Clone().Sin(), a.UpperBound.Clone().Sin());
1000      high = Algebraic.Max(a.LowerBound.Clone().Sin(), a.UpperBound.Clone().Sin());
1001
1002      // override min and max if necessary
1003
1004      // shift interval 'a' into the range [-2pi .. 2pi] without changing the size of the interval to simplify the checks
1005      lower = lower % (2 * Math.PI); // lower in [-2pi .. 2pi]     
1006
1007      // handle min = -1 and max = 1 cases explicitly
1008      var pi_2 = Math.PI / 2.0;
1009      var maxima = new double[] { -3 * pi_2, pi_2 };
1010      var minima = new double[] { -pi_2, 3 * pi_2 };
1011
1012      // override min and max if necessary
1013      if (maxima.Any(m => lower < m && lower + size > m)) {
1014        // max = 1
1015        high = new MultivariateDual<AlgebraicDouble>(1.0); // zero gradient
1016      }
1017
1018      if (minima.Any(m => lower < m && lower + size > m)) {
1019        // min = -1;
1020        low = new MultivariateDual<AlgebraicDouble>(-1.0); // zero gradient
1021      }
1022      return this;
1023    }
1024
1025    public AlgebraicInterval Sub(AlgebraicInterval a) {
1026      // [x1,x2] − [y1,y2] = [x1 − y2,x2 − y1]
1027      low.Sub(a.high);
1028      high.Sub(a.low);
1029      return this;
1030    }
1031
1032    public AlgebraicInterval Clone() {
1033      return new AlgebraicInterval(low, high);
1034    }
1035
1036    public bool Contains(double val) {
1037      return LowerBound.Value.Value <= val && val <= UpperBound.Value.Value;
1038    }
1039
1040    public AlgebraicInterval AssignAbs(AlgebraicInterval a) {
1041      if (a.Contains(0.0)) {
1042        var abslow = a.low.Clone().Abs();
1043        var abshigh = a.high.Clone().Abs();
1044        a.high.Assign(Algebraic.Max(abslow, abshigh));
1045        a.low.Assign(new MultivariateDual<AlgebraicDouble>(0.0)); // lost gradient for lower bound
1046      } else {
1047        var abslow = a.low.Clone().Abs();
1048        var abshigh = a.high.Clone().Abs();
1049        a.low.Assign(Algebraic.Min(abslow, abshigh));
1050        a.high.Assign(Algebraic.Max(abslow, abshigh));
1051      }
1052      return this;
1053    }
1054
1055    public AlgebraicInterval AssignSgn(AlgebraicInterval a) {
1056      low.AssignSgn(a.low);
1057      high.AssignSgn(a.high);
1058      return this;
1059    }
1060  }
1061
1062  public class Dual<V> : IAlgebraicType<Dual<V>>
1063    where V : IAlgebraicType<V> {
1064    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1065    private V v;
1066    public V Value => v;
1067
1068    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1069    private V dv;
1070    public V Derivative => dv;
1071
1072    public Dual(V v, V dv) { this.v = v; this.dv = dv; }
1073
1074    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1075    public Dual<V> Zero => new Dual<V>(Value.Zero, Derivative.Zero);
1076    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1077    public Dual<V> One => new Dual<V>(Value.One, Derivative.Zero);
1078
1079    public Dual<V> Assign(Dual<V> a) { v.Assign(a.v); dv.Assign(a.dv); return this; }
1080    public Dual<V> Scale(double s) { v.Scale(s); dv.Scale(s); return this; }
1081    public Dual<V> Add(Dual<V> a) { v.Add(a.v); dv.Add(a.dv); return this; }
1082    public Dual<V> Sub(Dual<V> a) { v.Sub(a.v); dv.Sub(a.dv); return this; }
1083    public Dual<V> AssignNeg(Dual<V> a) { v.AssignNeg(a.v); dv.AssignNeg(a.dv); return this; }
1084    public Dual<V> AssignInv(Dual<V> a) { v.AssignInv(a.v); dv.AssignNeg(a.dv).Mul(v).Mul(v); return this; } // (1/f(x))' = - f(x)' / f(x)^2
1085
1086    // (a(x) * b(x))' = b(x)*a(x)' + b(x)'*a(x);
1087    public Dual<V> Mul(Dual<V> a) {
1088      var t1 = a.dv.Clone().Mul(v);
1089      var t2 = dv.Clone().Mul(a.v);
1090      dv.Assign(t1).Add(t2);
1091
1092      v.Mul(a.v);
1093      return this;
1094    }
1095    public Dual<V> Div(Dual<V> a) { Mul(a.Inv()); return this; }
1096
1097    public Dual<V> AssignExp(Dual<V> a) { v.AssignExp(a.v); dv.Assign(a.dv).Mul(v); return this; } // exp(f(x)) = exp(f(x))*f(x)'
1098    public Dual<V> AssignLog(Dual<V> a) { v.AssignLog(a.v); dv.Assign(a.dv).Div(a.v); return this; }     // log(x)' = 1/f(x) * f(x)'
1099
1100    public Dual<V> AssignIntPower(Dual<V> a, int p) { v.AssignIntPower(a.v, p); dv.Assign(a.dv).Scale(p).Mul(a.v.Clone().IntPower(p - 1)); return this; }
1101    public Dual<V> AssignIntRoot(Dual<V> a, int r) { v.AssignIntRoot(a.v, r); dv.Assign(a.dv).Scale(1.0 / r).Mul(a.v.IntRoot(r - 1)); return this; }
1102
1103    public Dual<V> AssignSin(Dual<V> a) { v.AssignSin(a.v); dv.Assign(a.dv).Mul(a.v.Clone().Cos()); return this; }
1104    public Dual<V> AssignCos(Dual<V> a) { v.AssignCos(a.v); dv.AssignNeg(a.dv).Mul(a.v.Clone().Sin()); return this; }
1105    public Dual<V> AssignTanh(Dual<V> a) { v.AssignTanh(a.v); dv.Assign(a.dv.Mul(v.Clone().IntPower(2).Neg().Add(Value.One))); return this; }
1106
1107    public Dual<V> AssignAbs(Dual<V> a) { v.AssignAbs(a.v); dv.Assign(a.dv).Mul(a.v.Clone().Sgn()); return this; }       // abs(f(x))' = f(x)*f'(x) / |f(x)|     
1108    public Dual<V> AssignSgn(Dual<V> a) { v.AssignSgn(a.v); dv.Assign(a.dv.Zero); return this; }
1109
1110    public Dual<V> Clone() { return new Dual<V>(v.Clone(), dv.Clone()); }
1111
1112  }
1113
1114  /// <summary>
1115  /// An algebraic type which has a value as well as the partial derivatives of the value over multiple variables.
1116  /// </summary>
1117  /// <typeparam name="V"></typeparam>
1118  [DebuggerDisplay("v={Value}; dv={dv}")]
1119  public class MultivariateDual<V> : IAlgebraicType<MultivariateDual<V>> where V : IAlgebraicType<V>, new() {
1120    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1121    private V v;
1122    public V Value => v;
1123
1124    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
1125    private AlgebraicSparseVector<object, V> dv;
1126    public AlgebraicSparseVector<object, V> Gradient => dv; // <key,value> partial derivative identified via the key
1127
1128    private MultivariateDual(MultivariateDual<V> orig) { this.v = orig.v.Clone(); this.dv = orig.dv.Clone(); }
1129
1130    /// <summary>
1131    /// Constructor without partial derivative
1132    /// </summary>
1133    /// <param name="v"></param>
1134    public MultivariateDual(V v) { this.v = v.Clone(); this.dv = new AlgebraicSparseVector<object, V>(); }
1135
1136    /// <summary>
1137    /// Constructor for multiple partial derivatives
1138    /// </summary>
1139    /// <param name="v"></param>
1140    /// <param name="keys"></param>
1141    /// <param name="dv"></param>
1142    public MultivariateDual(V v, object[] keys, V[] dv) { this.v = v.Clone(); this.dv = new AlgebraicSparseVector<object, V>(keys, dv); }
1143
1144    /// <summary>
1145    /// Constructor for a single partial derivative
1146    /// </summary>
1147    /// <param name="v"></param>
1148    /// <param name="key"></param>
1149    /// <param name="dv"></param>
1150    public MultivariateDual(V v, object key, V dv) { this.v = v.Clone(); this.dv = new AlgebraicSparseVector<object, V>(new[] { key }, new[] { dv }); }
1151
1152    /// <summary>
1153    /// Constructor with a given value and gradient. For internal use.
1154    /// </summary>
1155    /// <param name="v">The value (not cloned).</param>
1156    /// <param name="gradient">The gradient (not cloned).</param>
1157    internal MultivariateDual(V v, AlgebraicSparseVector<object, V> gradient) { this.v = v; this.dv = gradient; }
1158
1159    public MultivariateDual<V> Clone() { return new MultivariateDual<V>(this); }
1160
1161    public MultivariateDual<V> Zero => new MultivariateDual<V>(Value.Zero, Gradient.Zero);
1162    public MultivariateDual<V> One => new MultivariateDual<V>(Value.One, Gradient.Zero);
1163
1164    public MultivariateDual<V> Scale(double s) { v.Scale(s); dv.Scale(s); return this; }
1165
1166    public MultivariateDual<V> Add(MultivariateDual<V> a) { v.Add(a.v); dv.Add(a.dv); return this; }
1167    public MultivariateDual<V> Sub(MultivariateDual<V> a) { v.Sub(a.v); dv.Sub(a.dv); return this; }
1168    public MultivariateDual<V> Assign(MultivariateDual<V> a) { v.Assign(a.v); dv.Assign(a.dv); return this; }
1169    public MultivariateDual<V> Mul(MultivariateDual<V> a) {
1170      // (a(x) * b(x))' = b(x)*a(x)' + b(x)'*a(x);
1171      var t1 = a.dv.Clone().Scale(v);
1172      var t2 = dv.Clone().Scale(a.v);
1173      dv.Assign(t1).Add(t2);
1174
1175      v.Mul(a.v);
1176      return this;
1177    }
1178    public MultivariateDual<V> Div(MultivariateDual<V> a) { v.Div(a.v); dv.Mul(a.dv.Inv()); return this; }
1179    public MultivariateDual<V> AssignNeg(MultivariateDual<V> a) { v.AssignNeg(a.v); dv.AssignNeg(a.dv); return this; }
1180    public MultivariateDual<V> AssignInv(MultivariateDual<V> a) { v.AssignInv(a.v); dv.AssignNeg(a.dv).Scale(v).Scale(v); return this; }   // (1/f(x))' = - f(x)' / f(x)^2
1181
1182    public MultivariateDual<V> AssignSin(MultivariateDual<V> a) { v.AssignSin(a.v); dv.Assign(a.dv).Scale(a.v.Clone().Cos()); return this; }
1183    public MultivariateDual<V> AssignCos(MultivariateDual<V> a) { v.AssignCos(a.v); dv.AssignNeg(a.dv).Scale(a.v.Clone().Sin()); return this; }
1184    public MultivariateDual<V> AssignTanh(MultivariateDual<V> a) { v.AssignTanh(a.v); dv.Assign(a.dv.Scale(v.Clone().IntPower(2).Neg().Add(Value.One))); return this; }     // tanh(f(x))' = f(x)'sech²(f(x)) = f(x)'(1 - tanh²(f(x)))
1185
1186    public MultivariateDual<V> AssignIntPower(MultivariateDual<V> a, int p) { v.AssignIntPower(a.v, p); dv.Assign(a.dv).Scale(p).Scale(a.v.Clone().IntPower(p - 1)); return this; }
1187    public MultivariateDual<V> AssignIntRoot(MultivariateDual<V> a, int r) { v.AssignIntRoot(a.v, r); dv.Assign(a.dv).Scale(1.0 / r).Scale(a.v.IntRoot(r - 1)); return this; }
1188
1189    public MultivariateDual<V> AssignExp(MultivariateDual<V> a) { v.AssignExp(a.v); dv.Assign(a.dv).Scale(v); return this; } // exp(f(x)) = exp(f(x))*f(x)'     
1190    public MultivariateDual<V> AssignLog(MultivariateDual<V> a) { v.AssignLog(a.v); dv.Assign(a.dv).Scale(a.v.Clone().Inv()); return this; }     // log(x)' = 1/f(x) * f(x)'
1191
1192    public MultivariateDual<V> AssignAbs(MultivariateDual<V> a) { v.AssignAbs(a.v); dv.Assign(a.dv).Scale(a.v.Clone().Sgn()); return this; }      // abs(f(x))' = f(x)*f'(x) / |f(x)|  doesn't work for intervals     
1193    public MultivariateDual<V> AssignSgn(MultivariateDual<V> a) { v.AssignSgn(a.v); dv = a.dv.Zero; return this; } // sign(f(x))' = 0;     
1194
1195  }
1196}
Note: See TracBrowser for help on using the repository browser.