Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2966

  • Changed signature of GetSymbolicExressionTreeIntervals methods
  • Changed PrepareInterpreterState (removed optinal parameters, takes Dictionary<string, Interval> as input and no dataset anymore)
  • Added optional parameter (rows) to GetVariableBoundaries method (allows to use just parts from dataset as input e.g. training/test indices)
File size: 10.3 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.Problems.DataAnalysis;
31using HeuristicLab.Problems.DataAnalysis.Symbolic;
32
33namespace HeuristicLab.Algorithms.DataAnalysis.Symbolic {
34  [StorableClass]
35  [Item("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.")]
36  public sealed class IntervalInterpreter : ParameterizedNamedItem, IStatefulItem {
37
38    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
39    private static int InstructionCount = 0;
40
41    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
42      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
43    }
44
45    public int EvaluatedSolutions {
46      get { return EvaluatedSolutionsParameter.Value.Value; }
47      set { EvaluatedSolutionsParameter.Value.Value = value; }
48    }
49
50    private IntervalInterpreter(bool deserializing) : base(deserializing) { }
51    private IntervalInterpreter(IntervalInterpreter original, Cloner cloner)
52        : base(original, cloner) { }
53
54    public IntervalInterpreter()
55        : base("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.") { }
56
57    public override IDeepCloneable Clone(Cloner cloner) {
58      return new IntervalInterpreter(this, cloner);
59    }
60
61    private readonly object syncRoot = new object();
62
63    #region IStatefulItem Members
64    public void InitializeState() {
65      EvaluatedSolutions = 0;
66    }
67    public void ClearState() { }
68    #endregion
69
70    private static void ResetInstrucitonCount() {
71      InstructionCount = 0;
72    }
73
74
75    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
76      lock (syncRoot) {
77        EvaluatedSolutions++;
78        ResetInstrucitonCount();
79      }
80      var intervalBoundaries = DatasetUtil.GetVariableBoundaries(dataset, rows);
81      var instructions = PrepareInterpreterState(tree, intervalBoundaries);
82      var x = Evaluate(instructions);
83
84      return x;
85    }
86
87    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
88      out Dictionary<ISymbolicExpressionTreeNode, Interval> intervals, IEnumerable<int> rows = null) {
89      lock (syncRoot) {
90        EvaluatedSolutions++;
91        ResetInstrucitonCount();
92      }
93      var intervalBoundaries = DatasetUtil.GetVariableBoundaries(dataset, rows);
94      intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
95      var instructions = PrepareInterpreterState(tree, intervalBoundaries);
96      var x = Evaluate(instructions, intervals);
97
98      return x;
99    }
100
101    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, Dictionary<string, Interval> customIntervals) {
102      lock (syncRoot) {
103        EvaluatedSolutions++;
104        ResetInstrucitonCount();
105      }
106      var instructions = PrepareInterpreterState(tree, customIntervals);
107      var x = Evaluate(instructions);
108
109      return x;
110    }
111
112
113    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree,
114      Dictionary<string, Interval> customIntervals, out Dictionary<ISymbolicExpressionTreeNode, Interval> intervals) {
115      lock (syncRoot) {
116        EvaluatedSolutions++;
117        ResetInstrucitonCount();
118      }
119      intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
120      var instructions = PrepareInterpreterState(tree, customIntervals);
121      var x = Evaluate(instructions, intervals);
122
123      return x;
124    }
125
126
127    private static Instruction[] PrepareInterpreterState(ISymbolicExpressionTree tree, Dictionary<string, Interval> customIntervals) {
128      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
129
130      if (customIntervals == null)
131        throw new ArgumentException("No interval ranges are present!", nameof(customIntervals));
132
133      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
134        if (!customIntervals.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
135      }
136
137      foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
138        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
139        instr.data = customIntervals[variableTreeNode.VariableName];
140      }
141      return code;
142    }
143
144    private Interval Evaluate(Instruction[] instructions, Dictionary<ISymbolicExpressionTreeNode,
145      Interval> intervals = null) {
146      Instruction currentInstr = instructions[InstructionCount++];
147      Interval intermediate = null;
148
149      switch (currentInstr.opCode) {
150        //Elementary arithmetic rules
151        case OpCodes.Add: {
152            intermediate = Evaluate(instructions, intervals);
153            for (int i = 1; i < currentInstr.nArguments; i++) {
154              intermediate = Interval.Add(intermediate, Evaluate(instructions, intervals));
155            }
156            break;
157          }
158        case OpCodes.Sub: {
159            intermediate = Evaluate(instructions, intervals);
160            for (int i = 1; i < currentInstr.nArguments; i++) {
161              intermediate = Interval.Subtract(intermediate, Evaluate(instructions, intervals));
162            }
163            break;
164          }
165        case OpCodes.Mul: {
166            intermediate = Evaluate(instructions, intervals);
167            for (int i = 1; i < currentInstr.nArguments; i++) {
168              intermediate = Interval.Multiply(intermediate, Evaluate(instructions, intervals));
169            }
170            break;
171          }
172        case OpCodes.Div: {
173            intermediate = Evaluate(instructions, intervals);
174            for (int i = 1; i < currentInstr.nArguments; i++) {
175              intermediate = Interval.Divide(intermediate, Evaluate(instructions, intervals));
176            }
177            break;
178          }
179        //Trigonometric functions
180        case OpCodes.Sin: {
181            intermediate = Interval.Sine(Evaluate(instructions, intervals));
182            break;
183          }
184        case OpCodes.Cos: {
185            intermediate = Interval.Cosine(Evaluate(instructions, intervals));
186            break;
187          }
188        case OpCodes.Tan: {
189            intermediate = Interval.Tangens(Evaluate(instructions, intervals));
190            break;
191          }
192        //Exponential functions
193        case OpCodes.Log: {
194            intermediate = Interval.Logarithm(Evaluate(instructions, intervals));
195            break;
196          }
197        case OpCodes.Exp: {
198            intermediate = Interval.Exponential(Evaluate(instructions, intervals));
199            break;
200          }
201        case OpCodes.Power: {
202            intermediate = Evaluate(instructions, intervals);
203            for (int i = 1; i < currentInstr.nArguments; i++) {
204              intermediate = Interval.Power(intermediate, Evaluate(instructions, intervals));
205            }
206            break;
207          }
208        case OpCodes.Square: {
209            intermediate = Interval.Square(Evaluate(instructions, intervals));
210            break;
211          }
212        case OpCodes.Root: {
213            intermediate = Evaluate(instructions, intervals);
214            for (int i = 1; i < currentInstr.nArguments; i++) {
215              intermediate = Interval.Root(intermediate, Evaluate(instructions, intervals));
216            }
217            break;
218          }
219        case OpCodes.SquareRoot: {
220            intermediate = Interval.SquareRoot(Evaluate(instructions, intervals));
221            break;
222          }
223        //Variables, Constants, ...
224        case OpCodes.Variable: {
225            intervals.Add(currentInstr.dynamicNode, (Interval)currentInstr.data);
226            return (Interval)currentInstr.data;
227          }
228        case OpCodes.Constant: {
229            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
230            var inter = new Interval(constTreeNode.Value, constTreeNode.Value);
231            intervals.Add(currentInstr.dynamicNode, inter);
232            return inter;
233          }
234        default:
235          throw new NotSupportedException("Tree contains an unknown symbol.");
236      }
237
238      if (intervals != null)
239        intervals.Add(currentInstr.dynamicNode, intermediate);
240      return intermediate;
241    }
242
243    public static bool IsCompatible(ISymbolicExpressionTree tree) {
244      var containsUnknownSyumbol = (
245        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
246        where
247          !(n.Symbol is StartSymbol) &&
248          !(n.Symbol is Addition) &&
249          !(n.Symbol is Subtraction) &&
250          !(n.Symbol is Multiplication) &&
251          !(n.Symbol is Division) &&
252          !(n.Symbol is Sine) &&
253          !(n.Symbol is Cosine) &&
254          !(n.Symbol is Tangent) &&
255          !(n.Symbol is Logarithm) &&
256          !(n.Symbol is Exponential) &&
257          !(n.Symbol is Power) &&
258          !(n.Symbol is Square) &&
259          !(n.Symbol is Root) &&
260          !(n.Symbol is SquareRoot) &&
261          !(n.Symbol is Problems.DataAnalysis.Symbolic.Variable) &&
262          !(n.Symbol is Constant)
263        select n).Any();
264      return !containsUnknownSyumbol;
265    }
266  }
267}
Note: See TracBrowser for help on using the repository browser.