Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2965_CancelablePersistence/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/IntervalInterpreter.cs @ 16433

Last change on this file since 16433 was 16433, checked in by pfleck, 5 years ago

#2965 Merged recent trunk changes.
Enabled the prepared hooks that allows to cancel the save file using the recently introduced cancelable progressbars (in FileManager).

File size: 11.8 KB
RevLine 
[16330]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;
[16303]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;
[16367]30using HeuristicLab.Parameters;
[16303]31
[16377]32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[16303]33  [StorableClass]
[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]
[16328]49    private IntervalInterpreter(bool deserializing) : base(deserializing) { }
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
[16404]71    public Interval GetSymbolicExressionTreeInterval(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
[16403]72      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
[16404]73      return GetSymbolicExressionTreeInterval(tree, variableRanges);
[16330]74    }
75
76    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
[16404]77      out Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals, IEnumerable<int> rows = null) {
[16403]78      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
[16404]79      return GetSymbolicExressionTreeIntervals(tree, variableRanges, out nodeIntervals);
[16328]80    }
81
[16404]82    public Interval GetSymbolicExressionTreeInterval(ISymbolicExpressionTree tree, Dictionary<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
[16383]90      return outputInterval;
[16328]91    }
92
[16364]93
94    public Interval GetSymbolicExressionTreeIntervals(ISymbolicExpressionTree tree,
[16404]95      Dictionary<string, Interval> variableRanges, out Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals) {
[16330]96      lock (syncRoot) {
97        EvaluatedSolutions++;
98      }
[16376]99      int instructionCount = 0;
[16404]100      var intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
101      var instructions = PrepareInterpreterState(tree, variableRanges);
[16383]102      var outputInterval = Evaluate(instructions, ref instructionCount, intervals);
[16328]103
[16404]104      nodeIntervals = intervals;
105
[16383]106      return outputInterval;
[16328]107    }
108
[16364]109
[16404]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));
[16328]113
[16404]114      //Check if all variables used in the tree are present in the dataset
[16364]115      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
[16404]116        if (!variableRanges.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
[16364]117      }
[16330]118
[16404]119      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
[16364]120      foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
121        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
[16404]122        instr.data = variableRanges[variableTreeNode.VariableName];
[16303]123      }
[16330]124      return code;
[16303]125    }
126
[16404]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++;
[16374]132      Interval result = null;
[16331]133
[16303]134      switch (currentInstr.opCode) {
[16383]135        //Variables, Constants, ...
136        case OpCodes.Variable: {
137            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
[16404]138            var weightInterval = new Interval(variableTreeNode.Weight, variableTreeNode.Weight);
139            var variableInterval = (Interval)currentInstr.data;
[16383]140
[16404]141            result = Interval.Multiply(variableInterval, weightInterval);
[16403]142            break;
[16383]143          }
144        case OpCodes.Constant: {
145            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
[16403]146            result = new Interval(constTreeNode.Value, constTreeNode.Value);
147            break;
[16383]148          }
[16303]149        //Elementary arithmetic rules
150        case OpCodes.Add: {
[16404]151            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]152            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]153              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]154              result = Interval.Add(result, argumentInterval);
[16303]155            }
[16331]156            break;
[16303]157          }
158        case OpCodes.Sub: {
[16404]159            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]160            if (currentInstr.nArguments == 1)
161              result = Interval.Multiply(new Interval(-1, -1), result);
[16404]162
[16303]163            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]164              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]165              result = Interval.Subtract(result, argumentInterval);
[16303]166            }
[16331]167            break;
[16303]168          }
169        case OpCodes.Mul: {
[16404]170            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]171            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]172              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]173              result = Interval.Multiply(result, argumentInterval);
[16303]174            }
[16331]175            break;
[16303]176          }
177        case OpCodes.Div: {
[16404]178            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
179            if (currentInstr.nArguments == 1)
180              result = Interval.Divide(new Interval(1, 1), result);
[16383]181
[16303]182            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]183              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]184              result = Interval.Divide(result, argumentInterval);
[16303]185            }
[16331]186            break;
[16303]187          }
188        //Trigonometric functions
189        case OpCodes.Sin: {
[16404]190            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]191            result = Interval.Sine(argumentInterval);
[16331]192            break;
[16303]193          }
194        case OpCodes.Cos: {
[16404]195            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]196            result = Interval.Cosine(argumentInterval);
[16331]197            break;
[16303]198          }
199        case OpCodes.Tan: {
[16404]200            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]201            result = Interval.Tangens(argumentInterval);
[16331]202            break;
[16303]203          }
204        //Exponential functions
205        case OpCodes.Log: {
[16404]206            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]207            result = Interval.Logarithm(argumentInterval);
[16331]208            break;
[16303]209          }
210        case OpCodes.Exp: {
[16404]211            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]212            result = Interval.Exponential(argumentInterval);
[16331]213            break;
[16303]214          }
215        case OpCodes.Power: {
[16404]216            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]217            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]218              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]219              result = Interval.Power(result, argumentInterval);
[16303]220            }
[16331]221            break;
[16303]222          }
[16323]223        case OpCodes.Square: {
[16404]224            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]225            result = Interval.Square(argumentInterval);
[16331]226            break;
[16323]227          }
[16303]228        case OpCodes.Root: {
[16404]229            result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16303]230            for (int i = 1; i < currentInstr.nArguments; i++) {
[16404]231              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]232              result = Interval.Root(result, argumentInterval);
[16303]233            }
[16331]234            break;
[16303]235          }
[16323]236        case OpCodes.SquareRoot: {
[16404]237            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
[16383]238            result = Interval.SquareRoot(argumentInterval);
[16331]239            break;
[16323]240          }
[16303]241        default:
[16383]242          throw new NotSupportedException($"The tree contains the unknown symbol {currentInstr.dynamicNode.Symbol}");
[16303]243      }
[16331]244
[16404]245      if (nodeIntervals != null)
246        nodeIntervals.Add(currentInstr.dynamicNode, result);
[16383]247
[16374]248      return result;
[16303]249    }
[16330]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    }
[16303]274  }
275}
Note: See TracBrowser for help on using the repository browser.