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

Last change on this file since 16403 was 16403, checked in by chaider, 16 months ago

#2966 Changed variable names

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