Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2974_Constants_Optimization/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/IntervalInterpreter.cs @ 17905

Last change on this file since 17905 was 17193, checked in by mkommend, 5 years ago

#2974: Merged trunk changes into branch.

File size: 13.0 KB
RevLine 
[16330]1#region License Information
2/* HeuristicLab
[17193]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[16330]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;
[16303]23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[16676]29using HEAL.Attic;
[16367]30using HeuristicLab.Parameters;
[16303]31
[16377]32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[16676]33  [StorableType("DE6C1E1E-D7C1-4070-847E-63B68562B10C")]
[16330]34  [Item("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.")]
[16328]35  public sealed class IntervalInterpreter : ParameterizedNamedItem, IStatefulItem {
36
[16303]37    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
[16330]38
[16303]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
[16367]48    [StorableConstructor]
[16676]49    private IntervalInterpreter(StorableConstructorFlag _) : base(_) { }
[16328]50    private IntervalInterpreter(IntervalInterpreter original, Cloner cloner)
[16303]51        : base(original, cloner) { }
52
[16323]53    public IntervalInterpreter()
[16367]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    }
[16303]57
58    public override IDeepCloneable Clone(Cloner cloner) {
[16323]59      return new IntervalInterpreter(this, cloner);
[16303]60    }
61
[16330]62    private readonly object syncRoot = new object();
63
[16328]64    #region IStatefulItem Members
65    public void InitializeState() {
66      EvaluatedSolutions = 0;
67    }
68    public void ClearState() { }
69    #endregion
70
[17193]71    public Interval GetSymbolicExpressionTreeInterval(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
[16403]72      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
[17193]73      return GetSymbolicExpressionTreeInterval(tree, variableRanges);
[16330]74    }
75
[17193]76    public Interval GetSymbolicExpressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
77      out IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals, IEnumerable<int> rows = null) {
[16403]78      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
[17193]79      return GetSymbolicExpressionTreeIntervals(tree, variableRanges, out nodeIntervals);
[16328]80    }
81
[17193]82    public Interval GetSymbolicExpressionTreeInterval(ISymbolicExpressionTree tree, IDictionary<string, Interval> variableRanges) {
[16364]83      lock (syncRoot) {
[16330]84        EvaluatedSolutions++;
85      }
[16376]86      int instructionCount = 0;
[16404]87      var instructions = PrepareInterpreterState(tree, variableRanges);
[16383]88      var outputInterval = Evaluate(instructions, ref instructionCount);
[16328]89
[16676]90      // because of numerical errors the bounds might be incorrect
91      if (outputInterval.LowerBound <= outputInterval.UpperBound)
92        return outputInterval;
93      else
94        return new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
[16328]95    }
96
[16364]97
[17193]98    public Interval GetSymbolicExpressionTreeIntervals(ISymbolicExpressionTree tree,
99      IDictionary<string, Interval> variableRanges, out IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals) {
[16330]100      lock (syncRoot) {
101        EvaluatedSolutions++;
102      }
[16376]103      int instructionCount = 0;
[16404]104      var intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
105      var instructions = PrepareInterpreterState(tree, variableRanges);
[16383]106      var outputInterval = Evaluate(instructions, ref instructionCount, intervals);
[16328]107
[16676]108      // fix incorrect intervals if necessary (could occur because of numerical errors)
109      nodeIntervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
[17193]110      foreach (var kvp in intervals) {
[16676]111        var interval = kvp.Value;
112        if (interval.IsInfiniteOrUndefined || interval.LowerBound <= interval.UpperBound)
113          nodeIntervals.Add(kvp.Key, interval);
114        else
115          nodeIntervals.Add(kvp.Key, new Interval(interval.UpperBound, interval.LowerBound));
116      }
[16404]117
[16676]118      // because of numerical errors the bounds might be incorrect
119      if (outputInterval.IsInfiniteOrUndefined || outputInterval.LowerBound <= outputInterval.UpperBound)
120        return outputInterval;
121      else
122        return new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
[16328]123    }
124
[16364]125
[17193]126    private static Instruction[] PrepareInterpreterState(ISymbolicExpressionTree tree, IDictionary<string, Interval> variableRanges) {
[16404]127      if (variableRanges == null)
128        throw new ArgumentNullException("No variablew ranges are present!", nameof(variableRanges));
[16328]129
[16404]130      //Check if all variables used in the tree are present in the dataset
[16364]131      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
[16404]132        if (!variableRanges.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
[16364]133      }
[16330]134
[16404]135      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
[16364]136      foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
137        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
[16404]138        instr.data = variableRanges[variableTreeNode.VariableName];
[16303]139      }
[16330]140      return code;
[16303]141    }
142
[17193]143    private Interval Evaluate(Instruction[] instructions, ref int instructionCounter, IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals = null) {
[16404]144      Instruction currentInstr = instructions[instructionCounter];
145      //Use ref parameter, because the tree will be iterated through recursively from the left-side branch to the right side
146      //Update instructionCounter, whenever Evaluate is called
147      instructionCounter++;
[16374]148      Interval result = null;
[16331]149
[16303]150      switch (currentInstr.opCode) {
[16383]151        //Variables, Constants, ...
152        case OpCodes.Variable: {
153            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
[16404]154            var weightInterval = new Interval(variableTreeNode.Weight, variableTreeNode.Weight);
155            var variableInterval = (Interval)currentInstr.data;
[16383]156
[16404]157            result = Interval.Multiply(variableInterval, weightInterval);
[16403]158            break;
[16383]159          }
160        case OpCodes.Constant: {
161            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
[16403]162            result = new Interval(constTreeNode.Value, constTreeNode.Value);
163            break;
[16383]164          }
[16303]165        //Elementary arithmetic rules
166        case OpCodes.Add: {
[16404]167            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]168            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]169              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]170              result = Interval.Add(result, argumentInterval);
[16303]171            }
[16331]172            break;
[16303]173          }
174        case OpCodes.Sub: {
[16404]175            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]176            if (currentInstr.nArguments == 1)
177              result = Interval.Multiply(new Interval(-1, -1), result);
[16404]178
[16303]179            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]180              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]181              result = Interval.Subtract(result, argumentInterval);
[16303]182            }
[16331]183            break;
[16303]184          }
185        case OpCodes.Mul: {
[16404]186            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]187            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]188              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]189              result = Interval.Multiply(result, argumentInterval);
[16303]190            }
[16331]191            break;
[16303]192          }
193        case OpCodes.Div: {
[16404]194            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
195            if (currentInstr.nArguments == 1)
196              result = Interval.Divide(new Interval(1, 1), result);
[16383]197
[16303]198            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]199              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]200              result = Interval.Divide(result, argumentInterval);
[16303]201            }
[16331]202            break;
[16303]203          }
204        //Trigonometric functions
205        case OpCodes.Sin: {
[16404]206            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]207            result = Interval.Sine(argumentInterval);
[16331]208            break;
[16303]209          }
210        case OpCodes.Cos: {
[16404]211            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]212            result = Interval.Cosine(argumentInterval);
[16331]213            break;
[16303]214          }
215        case OpCodes.Tan: {
[16404]216            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]217            result = Interval.Tangens(argumentInterval);
[16331]218            break;
[16303]219          }
[17193]220        case OpCodes.Tanh: {
221            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
222            result = Interval.HyperbolicTangent(argumentInterval);
223            break;
224          }
[16303]225        //Exponential functions
226        case OpCodes.Log: {
[16404]227            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]228            result = Interval.Logarithm(argumentInterval);
[16331]229            break;
[16303]230          }
231        case OpCodes.Exp: {
[16404]232            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]233            result = Interval.Exponential(argumentInterval);
[16331]234            break;
[16303]235          }
236        case OpCodes.Power: {
[16404]237            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]238            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]239              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]240              result = Interval.Power(result, argumentInterval);
[16303]241            }
[16331]242            break;
[16303]243          }
[16323]244        case OpCodes.Square: {
[16404]245            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]246            result = Interval.Square(argumentInterval);
[16331]247            break;
[16323]248          }
[16303]249        case OpCodes.Root: {
[16404]250            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]251            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]252              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]253              result = Interval.Root(result, argumentInterval);
[16303]254            }
[16331]255            break;
[16303]256          }
[16323]257        case OpCodes.SquareRoot: {
[16404]258            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]259            result = Interval.SquareRoot(argumentInterval);
[16331]260            break;
[16323]261          }
[16303]262        default:
[16383]263          throw new NotSupportedException($"The tree contains the unknown symbol {currentInstr.dynamicNode.Symbol}");
[16303]264      }
[16331]265
[16404]266      if (nodeIntervals != null)
267        nodeIntervals.Add(currentInstr.dynamicNode, result);
[16383]268
[16374]269      return result;
[16303]270    }
[16330]271
272    public static bool IsCompatible(ISymbolicExpressionTree tree) {
273      var containsUnknownSyumbol = (
274        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
275        where
276          !(n.Symbol is StartSymbol) &&
277          !(n.Symbol is Addition) &&
278          !(n.Symbol is Subtraction) &&
279          !(n.Symbol is Multiplication) &&
280          !(n.Symbol is Division) &&
281          !(n.Symbol is Sine) &&
282          !(n.Symbol is Cosine) &&
283          !(n.Symbol is Tangent) &&
284          !(n.Symbol is Logarithm) &&
285          !(n.Symbol is Exponential) &&
286          !(n.Symbol is Power) &&
287          !(n.Symbol is Square) &&
288          !(n.Symbol is Root) &&
289          !(n.Symbol is SquareRoot) &&
290          !(n.Symbol is Problems.DataAnalysis.Symbolic.Variable) &&
291          !(n.Symbol is Constant)
292        select n).Any();
293      return !containsUnknownSyumbol;
294    }
[16303]295  }
296}
Note: See TracBrowser for help on using the repository browser.