Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2966_interval_calculation/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/IntervalInterpreter.cs @ 16393

Last change on this file since 16393 was 16393, checked in by chaider, 5 years ago

#2966 Checked null references

File size: 11.5 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 GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
72      var intervalBoundaries = DatasetUtil.GetVariableRanges(dataset, rows);
73      return GetSymbolicExressionTreeIntervals(tree, intervalBoundaries);
74    }
75
76    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
77      out Dictionary<ISymbolicExpressionTreeNode, Interval> intervals, IEnumerable<int> rows = null) {
78      var intervalBoundaries = DatasetUtil.GetVariableRanges(dataset, rows);
79      return GetSymbolicExressionTreeIntervals(tree, intervalBoundaries, out intervals);
80    }
81
82    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, Dictionary<string, Interval> customIntervals) {
83      lock (syncRoot) {
84        EvaluatedSolutions++;
85      }
86      int instructionCount = 0;
87      var instructions = PrepareInterpreterState(tree, customIntervals);
88      var outputInterval = Evaluate(instructions, ref instructionCount);
89
90      return outputInterval;
91    }
92
93
94    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree,
95      Dictionary<string, Interval> customIntervals, out Dictionary<ISymbolicExpressionTreeNode, Interval> intervals) {
96      lock (syncRoot) {
97        EvaluatedSolutions++;
98      }
99      int instructionCount = 0;
100      intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
101      var instructions = PrepareInterpreterState(tree, customIntervals);
102      var outputInterval = Evaluate(instructions, ref instructionCount, intervals);
103
104      return outputInterval;
105    }
106
107
108    private static Instruction[] PrepareInterpreterState(ISymbolicExpressionTree tree, Dictionary<string, Interval> customIntervals) {
109      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
110
111      if (customIntervals == null)
112        throw new ArgumentException("No interval ranges are present!", nameof(customIntervals));
113
114      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
115        if (!customIntervals.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
116      }
117
118      foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
119        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
120        instr.data = customIntervals[variableTreeNode.VariableName];
121      }
122      return code;
123    }
124
125    private Interval Evaluate(Instruction[] instructions, ref int instructionCount, Dictionary<ISymbolicExpressionTreeNode, Interval> intervals = null) {
126      Instruction currentInstr = instructions[instructionCount++];
127      Interval result = null;
128
129      switch (currentInstr.opCode) {
130        //Variables, Constants, ...
131        case OpCodes.Variable: {
132            if (intervals != null)
133              intervals.Add(currentInstr.dynamicNode, (Interval)currentInstr.data);
134            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
135            var variableWeight = variableTreeNode.Weight;
136
137            return Interval.Multiply((Interval)currentInstr.data, new Interval(variableWeight, variableWeight));
138          }
139        case OpCodes.Constant: {
140            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
141            var inter = new Interval(constTreeNode.Value, constTreeNode.Value);
142            if (intervals != null)
143              intervals.Add(currentInstr.dynamicNode, inter);
144            return inter;
145          }
146        //Elementary arithmetic rules
147        case OpCodes.Add: {
148            result = Evaluate(instructions, ref instructionCount, intervals);
149            for (int i = 1; i < currentInstr.nArguments; i++) {
150              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
151              result = Interval.Add(result, argumentInterval);
152            }
153            break;
154          }
155        case OpCodes.Sub: {
156            result = Evaluate(instructions, ref instructionCount, intervals);
157            if (currentInstr.nArguments == 1)
158              result = Interval.Multiply(new Interval(-1, -1), result);
159           
160            for (int i = 1; i < currentInstr.nArguments; i++) {
161              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
162              result = Interval.Subtract(result, argumentInterval);
163            }
164            break;
165          }
166        case OpCodes.Mul: {
167            result = Evaluate(instructions, ref instructionCount, intervals);
168            for (int i = 1; i < currentInstr.nArguments; i++) {
169              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
170              result = Interval.Multiply(result, argumentInterval);
171            }
172            break;
173          }
174        case OpCodes.Div: {
175            result = Evaluate(instructions, ref instructionCount, intervals);
176            if(currentInstr.nArguments == 1)
177              result = Interval.Divide(new Interval(1,1),result);
178
179            for (int i = 1; i < currentInstr.nArguments; i++) {
180              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
181              result = Interval.Divide(result, argumentInterval);
182            }
183            break;
184          }
185        //Trigonometric functions
186        case OpCodes.Sin: {
187            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
188            result = Interval.Sine(argumentInterval);
189            break;
190          }
191        case OpCodes.Cos: {
192            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
193            result = Interval.Cosine(argumentInterval);
194            break;
195          }
196        case OpCodes.Tan: {
197            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
198            result = Interval.Tangens(argumentInterval);
199            break;
200          }
201        //Exponential functions
202        case OpCodes.Log: {
203            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
204            result = Interval.Logarithm(argumentInterval);
205            break;
206          }
207        case OpCodes.Exp: {
208            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
209            result = Interval.Exponential(argumentInterval);
210            break;
211          }
212        case OpCodes.Power: {
213            result = Evaluate(instructions, ref instructionCount, intervals);
214            for (int i = 1; i < currentInstr.nArguments; i++) {
215              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
216              result = Interval.Power(result, argumentInterval);
217            }
218            break;
219          }
220        case OpCodes.Square: {
221            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
222            result = Interval.Square(argumentInterval);
223            break;
224          }
225        case OpCodes.Root: {
226            result = Evaluate(instructions, ref instructionCount, intervals);
227            for (int i = 1; i < currentInstr.nArguments; i++) {
228              var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
229              result = Interval.Root(result, argumentInterval);
230            }
231            break;
232          }
233        case OpCodes.SquareRoot: {
234            var argumentInterval = Evaluate(instructions, ref instructionCount, intervals);
235            result = Interval.SquareRoot(argumentInterval);
236            break;
237          }
238        default:
239          throw new NotSupportedException($"The tree contains the unknown symbol {currentInstr.dynamicNode.Symbol}");
240      }
241
242      if (intervals != null)
243        intervals.Add(currentInstr.dynamicNode, result);
244
245      return result;
246    }
247
248    public static bool IsCompatible(ISymbolicExpressionTree tree) {
249      var containsUnknownSyumbol = (
250        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
251        where
252          !(n.Symbol is StartSymbol) &&
253          !(n.Symbol is Addition) &&
254          !(n.Symbol is Subtraction) &&
255          !(n.Symbol is Multiplication) &&
256          !(n.Symbol is Division) &&
257          !(n.Symbol is Sine) &&
258          !(n.Symbol is Cosine) &&
259          !(n.Symbol is Tangent) &&
260          !(n.Symbol is Logarithm) &&
261          !(n.Symbol is Exponential) &&
262          !(n.Symbol is Power) &&
263          !(n.Symbol is Square) &&
264          !(n.Symbol is Root) &&
265          !(n.Symbol is SquareRoot) &&
266          !(n.Symbol is Problems.DataAnalysis.Symbolic.Variable) &&
267          !(n.Symbol is Constant)
268        select n).Any();
269      return !containsUnknownSyumbol;
270    }
271  }
272}
Note: See TracBrowser for help on using the repository browser.