Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2972_PDPRowSelect/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/IntervalInterpreter.cs @ 16724

Last change on this file since 16724 was 16407, checked in by chaider, 6 years ago

#2966: Merged branch changes into trunk.

File size: 11.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Parameters;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableClass]
34  [Item("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.")]
35  public sealed class IntervalInterpreter : ParameterizedNamedItem, IStatefulItem {
36
37    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
38
39    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
40      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
41    }
42
43    public int EvaluatedSolutions {
44      get { return EvaluatedSolutionsParameter.Value.Value; }
45      set { EvaluatedSolutionsParameter.Value.Value = value; }
46    }
47
48    [StorableConstructor]
49    private IntervalInterpreter(bool deserializing) : base(deserializing) { }
50    private IntervalInterpreter(IntervalInterpreter original, Cloner cloner)
51        : base(original, cloner) { }
52
53    public IntervalInterpreter()
54        : base("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.") {
55      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
56    }
57
58    public override IDeepCloneable Clone(Cloner cloner) {
59      return new IntervalInterpreter(this, cloner);
60    }
61
62    private readonly object syncRoot = new object();
63
64    #region IStatefulItem Members
65    public void InitializeState() {
66      EvaluatedSolutions = 0;
67    }
68    public void ClearState() { }
69    #endregion
70
71    public Interval GetSymbolicExressionTreeInterval(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
72      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
73      return GetSymbolicExressionTreeInterval(tree, variableRanges);
74    }
75
76    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
77      out Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals, IEnumerable<int> rows = null) {
78      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
79      return GetSymbolicExressionTreeIntervals(tree, variableRanges, out nodeIntervals);
80    }
81
82    public Interval GetSymbolicExressionTreeInterval(ISymbolicExpressionTree tree, Dictionary<string, Interval> variableRanges) {
83      lock (syncRoot) {
84        EvaluatedSolutions++;
85      }
86      int instructionCount = 0;
87      var instructions = PrepareInterpreterState(tree, variableRanges);
88      var outputInterval = Evaluate(instructions, ref instructionCount);
89
90      return outputInterval;
91    }
92
93
94    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree,
95      Dictionary<string, Interval> variableRanges, out Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals) {
96      lock (syncRoot) {
97        EvaluatedSolutions++;
98      }
99      int instructionCount = 0;
100      var intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
101      var instructions = PrepareInterpreterState(tree, variableRanges);
102      var outputInterval = Evaluate(instructions, ref instructionCount, intervals);
103
104      nodeIntervals = intervals;
105
106      return outputInterval;
107    }
108
109
110    private static Instruction[] PrepareInterpreterState(ISymbolicExpressionTree tree, Dictionary<string, Interval> variableRanges) {
111      if (variableRanges == null)
112        throw new ArgumentNullException("No variablew ranges are present!", nameof(variableRanges));
113
114      //Check if all variables used in the tree are present in the dataset
115      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
116        if (!variableRanges.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
117      }
118
119      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
120      foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
121        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
122        instr.data = variableRanges[variableTreeNode.VariableName];
123      }
124      return code;
125    }
126
127    private Interval Evaluate(Instruction[] instructions, ref int instructionCounter, Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals = null) {
128      Instruction currentInstr = instructions[instructionCounter];
129      //Use ref parameter, because the tree will be iterated through recursively from the left-side branch to the right side
130      //Update instructionCounter, whenever Evaluate is called
131      instructionCounter++;
132      Interval result = null;
133
134      switch (currentInstr.opCode) {
135        //Variables, Constants, ...
136        case OpCodes.Variable: {
137            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
138            var weightInterval = new Interval(variableTreeNode.Weight, variableTreeNode.Weight);
139            var variableInterval = (Interval)currentInstr.data;
140
141            result = Interval.Multiply(variableInterval, weightInterval);
142            break;
143          }
144        case OpCodes.Constant: {
145            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
146            result = new Interval(constTreeNode.Value, constTreeNode.Value);
147            break;
148          }
149        //Elementary arithmetic rules
150        case OpCodes.Add: {
151            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
152            for (int i = 1; i < currentInstr.nArguments; i++) {
153              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
154              result = Interval.Add(result, argumentInterval);
155            }
156            break;
157          }
158        case OpCodes.Sub: {
159            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
160            if (currentInstr.nArguments == 1)
161              result = Interval.Multiply(new Interval(-1, -1), result);
162
163            for (int i = 1; i < currentInstr.nArguments; i++) {
164              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
165              result = Interval.Subtract(result, argumentInterval);
166            }
167            break;
168          }
169        case OpCodes.Mul: {
170            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
171            for (int i = 1; i < currentInstr.nArguments; i++) {
172              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
173              result = Interval.Multiply(result, argumentInterval);
174            }
175            break;
176          }
177        case OpCodes.Div: {
178            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
179            if (currentInstr.nArguments == 1)
180              result = Interval.Divide(new Interval(1, 1), result);
181
182            for (int i = 1; i < currentInstr.nArguments; i++) {
183              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
184              result = Interval.Divide(result, argumentInterval);
185            }
186            break;
187          }
188        //Trigonometric functions
189        case OpCodes.Sin: {
190            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
191            result = Interval.Sine(argumentInterval);
192            break;
193          }
194        case OpCodes.Cos: {
195            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
196            result = Interval.Cosine(argumentInterval);
197            break;
198          }
199        case OpCodes.Tan: {
200            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
201            result = Interval.Tangens(argumentInterval);
202            break;
203          }
204        //Exponential functions
205        case OpCodes.Log: {
206            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
207            result = Interval.Logarithm(argumentInterval);
208            break;
209          }
210        case OpCodes.Exp: {
211            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
212            result = Interval.Exponential(argumentInterval);
213            break;
214          }
215        case OpCodes.Power: {
216            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
217            for (int i = 1; i < currentInstr.nArguments; i++) {
218              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
219              result = Interval.Power(result, argumentInterval);
220            }
221            break;
222          }
223        case OpCodes.Square: {
224            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
225            result = Interval.Square(argumentInterval);
226            break;
227          }
228        case OpCodes.Root: {
229            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
230            for (int i = 1; i < currentInstr.nArguments; i++) {
231              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
232              result = Interval.Root(result, argumentInterval);
233            }
234            break;
235          }
236        case OpCodes.SquareRoot: {
237            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
238            result = Interval.SquareRoot(argumentInterval);
239            break;
240          }
241        default:
242          throw new NotSupportedException($"The tree contains the unknown symbol {currentInstr.dynamicNode.Symbol}");
243      }
244
245      if (nodeIntervals != null)
246        nodeIntervals.Add(currentInstr.dynamicNode, result);
247
248      return result;
249    }
250
251    public static bool IsCompatible(ISymbolicExpressionTree tree) {
252      var containsUnknownSyumbol = (
253        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
254        where
255          !(n.Symbol is StartSymbol) &&
256          !(n.Symbol is Addition) &&
257          !(n.Symbol is Subtraction) &&
258          !(n.Symbol is Multiplication) &&
259          !(n.Symbol is Division) &&
260          !(n.Symbol is Sine) &&
261          !(n.Symbol is Cosine) &&
262          !(n.Symbol is Tangent) &&
263          !(n.Symbol is Logarithm) &&
264          !(n.Symbol is Exponential) &&
265          !(n.Symbol is Power) &&
266          !(n.Symbol is Square) &&
267          !(n.Symbol is Root) &&
268          !(n.Symbol is SquareRoot) &&
269          !(n.Symbol is Problems.DataAnalysis.Symbolic.Variable) &&
270          !(n.Symbol is Constant)
271        select n).Any();
272      return !containsUnknownSyumbol;
273    }
274  }
275}
Note: See TracBrowser for help on using the repository browser.