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