Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MCTS-SymbReg-2796/HeuristicLab.Algorithms.DataAnalysis/3.4/MctsSymbolicRegression/MctsSymbolicRegressionStatic.cs @ 15440

Last change on this file since 15440 was 15440, checked in by gkronber, 7 years ago

#2796 fixed hashing of expressions and unit tests for expression enumeration

File size: 38.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Diagnostics;
25using System.Linq;
26using System.Text;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Problems.DataAnalysis;
31using HeuristicLab.Problems.DataAnalysis.Symbolic;
32using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression {
36  public static class MctsSymbolicRegressionStatic {
37    // OBJECTIVES:
38    // 1) solve toy problems without numeric constants (to show that structure search is effective / efficient)
39    //    - e.g. Keijzer, Nguyen ... where no numeric constants are involved
40    //    - assumptions:
41    //      - we don't know the necessary operations or functions -> all available functions could be necessary
42    //      - but we do not need to tune numeric constants -> no scaling of input variables x!
43    // 2) Solve toy problems with numeric constants to make the algorithm invariant concerning variable scale.
44    //    This is important for real world applications.
45    //    - e.g. Korns or Vladislavleva problems where numeric constants are involved
46    //    - assumptions:
47    //      - any numeric constant is possible (a-priori we might assume that small abs. constants are more likely)
48    //      - standardization of variables is possible (or might be necessary) as we adjust numeric parameters of the expression anyway
49    //      - to simplify the problem we can restrict the set of functions e.g. we assume which functions are necessary for the problem instance
50    //        -> several steps: (a) polyinomials, (b) rational polynomials, (c) exponential or logarithmic functions, rational functions with exponential and logarithmic parts
51    // 3) efficiency and effectiveness for real-world problems
52    //    - e.g. Tower problem
53    //    - (1) and (2) combined, structure search must be effective in combination with numeric optimization of constants
54    //   
55
56    // TODO: The samples of x1*... or x2*... do not give any information about the relevance of the interaction term x1*x2 in general!
57    //       --> E.g. if x1, x2 ~ N(0, 1) or U(-1, 1) this is trivial to show
58    //       --> Therefore, looking at rollout statistics for arm selection is useless in the general case!
59    //       --> It is necessary to rely on other features for the arm selection.
60    //       --> TODO: Which heuristics can we apply?
61    // TODO: Solve Poly-10
62    // TODO: rename everything as this is not MCTS anymore
63    // TODO: After state unification the recursive backpropagation of results takes a lot of time. How can this be improved?
64    // ~~obsolete TODO: Why is the algorithm so slow for rather greedy policies (e.g. low C value in UCB)?
65    // ~~obsolete TODO: check if we can use a quality measure with range [-1..1] in policies
66    // TODO: unit tests for benchmark problems which contain log / exp / x^-1 but without numeric constants
67    // TODO: check if transformation of y is correct and works (Obj 2)
68    // TODO: The algorithm is not invariant to location and scale of variables.
69    //       Include offset for variables as parameter (for Objective 2)
70    // TODO: why does LM optimization converge so slowly with exp(x), log(x), and 1/x allowed (Obj 2)?
71    // TODO: support e(-x) and possibly (1/-x) (Obj 1)
72    // TODO: is it OK to initialize all constants to 1 (Obj 2)?
73    // TODO: improve memory usage
74    // TODO: support empty test partition
75    // TODO: the algorithm should be invariant to linear transformations of the space (y = f(x') = f( Ax ) ) for invertible transformations A --> unit tests
76    #region static API
77
78    public interface IState {
79      bool Done { get; }
80      ISymbolicRegressionModel BestModel { get; }
81      double BestSolutionTrainingQuality { get; }
82      double BestSolutionTestQuality { get; }
83      IEnumerable<ISymbolicRegressionSolution> ParetoBestModels { get; }
84      int TotalRollouts { get; }
85      int EffectiveRollouts { get; }
86      int FuncEvaluations { get; }
87      int GradEvaluations { get; } // number of gradient evaluations (* num parameters) to get a value representative of the effort comparable to the number of function evaluations
88      // TODO other stats on LM optimizer might be interesting here
89    }
90
91    // created through factory method
92    private class State : IState {
93      private const int MaxParams = 100;
94
95      // state variables used by MCTS
96      internal readonly Automaton automaton;
97      internal IRandom random { get; private set; }
98      internal readonly Tree tree;
99      internal readonly Func<byte[], int, double> evalFun;
100      // MCTS might get stuck. Track statistics on the number of effective rollouts
101      internal int totalRollouts;
102      internal int effectiveRollouts;
103
104
105      // state variables used only internally (for eval function)
106      private readonly IRegressionProblemData problemData;
107      private readonly double[][] x;
108      private readonly double[] y;
109      private readonly double[][] testX;
110      private readonly double[] testY;
111      private readonly double[] scalingFactor;
112      private readonly double[] scalingOffset;
113      private readonly double yStdDev; // for scaling parameters (e.g. stopping condition for LM)
114      private readonly int constOptIterations;
115      private readonly double lambda; // weight of penalty term for regularization
116      private readonly double lowerEstimationLimit, upperEstimationLimit;
117      private readonly bool collectParetoOptimalModels;
118      private readonly List<ISymbolicRegressionSolution> paretoBestModels = new List<ISymbolicRegressionSolution>();
119      private readonly List<double[]> paretoFront = new List<double[]>(); // matching the models
120
121      private readonly ExpressionEvaluator evaluator, testEvaluator;
122
123      internal readonly Dictionary<Tree, List<Tree>> children = new Dictionary<Tree, List<Tree>>();
124      internal readonly Dictionary<Tree, List<Tree>> parents = new Dictionary<Tree, List<Tree>>();
125      internal readonly Dictionary<ulong, Tree> nodes = new Dictionary<ulong, Tree>();
126
127      // values for best solution
128      private double bestR;
129      private byte[] bestCode;
130      private int bestNParams;
131      private double[] bestConsts;
132
133      // stats
134      private int funcEvaluations;
135      private int gradEvaluations;
136
137      // buffers
138      private readonly double[] ones; // vector of ones (as default params)
139      private readonly double[] constsBuf;
140      private readonly double[] predBuf, testPredBuf;
141      private readonly double[][] gradBuf;
142
143      public State(IRegressionProblemData problemData, uint randSeed, int maxVariables, bool scaleVariables,
144        int constOptIterations, double lambda,
145        bool collectParetoOptimalModels = false,
146        double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
147        bool allowProdOfVars = true,
148        bool allowExp = true,
149        bool allowLog = true,
150        bool allowInv = true,
151        bool allowMultipleTerms = false) {
152
153        if (lambda < 0) throw new ArgumentException("Lambda must be larger or equal zero", "lambda");
154
155        this.problemData = problemData;
156        this.constOptIterations = constOptIterations;
157        this.lambda = lambda;
158        this.evalFun = this.Eval;
159        this.lowerEstimationLimit = lowerEstimationLimit;
160        this.upperEstimationLimit = upperEstimationLimit;
161        this.collectParetoOptimalModels = collectParetoOptimalModels;
162
163        random = new MersenneTwister(randSeed);
164
165        // prepare data for evaluation
166        double[][] x;
167        double[] y;
168        double[][] testX;
169        double[] testY;
170        double[] scalingFactor;
171        double[] scalingOffset;
172        // get training and test datasets (scale linearly based on training set if required)
173        GenerateData(problemData, scaleVariables, problemData.TrainingIndices, out x, out y, out scalingFactor, out scalingOffset);
174        GenerateData(problemData, problemData.TestIndices, scalingFactor, scalingOffset, out testX, out testY);
175        this.x = x;
176        this.y = y;
177        this.yStdDev = HeuristicLab.Common.EnumerableStatisticExtensions.StandardDeviation(y);
178        this.testX = testX;
179        this.testY = testY;
180        this.scalingFactor = scalingFactor;
181        this.scalingOffset = scalingOffset;
182        this.evaluator = new ExpressionEvaluator(y.Length, lowerEstimationLimit, upperEstimationLimit);
183        // we need a separate evaluator because the vector length for the test dataset might differ
184        this.testEvaluator = new ExpressionEvaluator(testY.Length, lowerEstimationLimit, upperEstimationLimit);
185
186        this.automaton = new Automaton(x, allowProdOfVars, allowExp, allowLog, allowInv, allowMultipleTerms, maxVariables);
187        this.tree = new Tree() {
188          state = automaton.CurrentState,
189          expr = "",
190          level = 0
191        };
192
193        // reset best solution
194        this.bestR = 0;
195        // code for default solution (constant model)
196        this.bestCode = new byte[] { (byte)OpCodes.LoadConst0, (byte)OpCodes.Exit };
197        this.bestNParams = 0;
198        this.bestConsts = null;
199
200        // init buffers
201        this.ones = Enumerable.Repeat(1.0, MaxParams).ToArray();
202        constsBuf = new double[MaxParams];
203        this.predBuf = new double[y.Length];
204        this.testPredBuf = new double[testY.Length];
205
206        this.gradBuf = Enumerable.Range(0, MaxParams).Select(_ => new double[y.Length]).ToArray();
207      }
208
209      #region IState inferface
210      public bool Done { get { return tree != null && tree.Done; } }
211
212      public double BestSolutionTrainingQuality {
213        get {
214          evaluator.Exec(bestCode, x, bestConsts, predBuf);
215          return Rho(y, predBuf);
216        }
217      }
218
219      public double BestSolutionTestQuality {
220        get {
221          testEvaluator.Exec(bestCode, testX, bestConsts, testPredBuf);
222          return Rho(testY, testPredBuf);
223        }
224      }
225
226      // takes the code of the best solution and creates and equivalent symbolic regression model
227      public ISymbolicRegressionModel BestModel {
228        get {
229          var treeGen = new SymbolicExpressionTreeGenerator(problemData.AllowedInputVariables.ToArray());
230          var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
231
232          var t = new SymbolicExpressionTree(treeGen.Exec(bestCode, bestConsts, bestNParams, scalingFactor, scalingOffset));
233          var model = new SymbolicRegressionModel(problemData.TargetVariable, t, interpreter, lowerEstimationLimit, upperEstimationLimit);
234          model.Scale(problemData); // apply linear scaling
235          return model;
236        }
237      }
238      public IEnumerable<ISymbolicRegressionSolution> ParetoBestModels {
239        get { return paretoBestModels; }
240      }
241
242      public int TotalRollouts { get { return totalRollouts; } }
243      public int EffectiveRollouts { get { return effectiveRollouts; } }
244      public int FuncEvaluations { get { return funcEvaluations; } }
245      public int GradEvaluations { get { return gradEvaluations; } } // number of gradient evaluations (* num parameters) to get a value representative of the effort comparable to the number of function evaluations
246
247      #endregion
248
249
250#if DEBUG
251      public string ExprStr(Automaton automaton) {
252        byte[] code;
253        int nParams;
254        automaton.GetCode(out code, out nParams);
255        var generator = new SymbolicExpressionTreeGenerator(problemData.AllowedInputVariables.ToArray());
256        var @params = Enumerable.Repeat(1.0, nParams).ToArray();
257        var root = generator.Exec(code, @params, nParams, null, null);
258        var formatter = new InfixExpressionFormatter();
259        return formatter.Format(new SymbolicExpressionTree(root));
260      }
261#endif
262
263      private double Eval(byte[] code, int nParams) {
264        double[] optConsts;
265        double q;
266        Eval(code, nParams, out q, out optConsts);
267
268        // single objective best
269        if (q > bestR) {
270          bestR = q;
271          bestNParams = nParams;
272          this.bestCode = new byte[code.Length];
273          this.bestConsts = new double[bestNParams];
274
275          Array.Copy(code, bestCode, code.Length);
276          Array.Copy(optConsts, bestConsts, bestNParams);
277        }
278        if (collectParetoOptimalModels) {
279          // multi-objective best
280          var complexity = // SymbolicDataAnalysisModelComplexityCalculator.CalculateComplexity() TODO: implement Kommenda's tree complexity directly in the evaluator
281            Array.FindIndex(code, (opc) => opc == (byte)OpCodes.Exit);  // use length of expression as surrogate for complexity
282          UpdateParetoFront(q, complexity, code, optConsts, nParams, scalingFactor, scalingOffset);
283        }
284        return q;
285      }
286
287      private void Eval(byte[] code, int nParams, out double rho, out double[] optConsts) {
288        // we make a first pass to determine a valid starting configuration for all constants
289        // constant c in log(c + f(x)) is adjusted to guarantee that x is positive (see expression evaluator)
290        // scale and offset are set to optimal starting configuration
291        // assumes scale is the first param and offset is the last param
292
293        // reset constants
294        Array.Copy(ones, constsBuf, nParams);
295        evaluator.Exec(code, x, constsBuf, predBuf, adjustOffsetForLogAndExp: true);
296        funcEvaluations++;
297
298        if (nParams == 0 || constOptIterations < 0) {
299          // if we don't need to optimize parameters then we are done
300          // changing scale and offset does not influence r²
301          rho = Rho(y, predBuf);
302          optConsts = constsBuf;
303        } else {
304          // optimize constants using the starting point calculated above
305          OptimizeConstsLm(code, constsBuf, nParams, 0.0, nIters: constOptIterations);
306
307          evaluator.Exec(code, x, constsBuf, predBuf);
308          funcEvaluations++;
309
310          rho = Rho(y, predBuf);
311          optConsts = constsBuf;
312        }
313      }
314
315
316
317      #region helpers
318      private static double Rho(IEnumerable<double> x, IEnumerable<double> y) {
319        OnlineCalculatorError error;
320        double r = OnlinePearsonsRCalculator.Calculate(x, y, out error);
321        return error == OnlineCalculatorError.None ? r : 0.0;
322      }
323
324
325      private void OptimizeConstsLm(byte[] code, double[] consts, int nParams, double epsF = 0.0, int nIters = 100) {
326        double[] optConsts = new double[nParams]; // allocate a smaller buffer for constants opt (TODO perf?)
327        Array.Copy(consts, optConsts, nParams);
328
329        // direct usage of LM is recommended in alglib manual for better performance than the lsfit interface (which uses lm internally).
330        alglib.minlmstate state;
331        alglib.minlmreport rep = null;
332        alglib.minlmcreatevj(y.Length + 1, optConsts, out state); // +1 for penalty term
333        // Using the change of the gradient as stopping criterion is recommended in alglib manual.
334        // However, the most recent version of alglib (as of Oct 2017) only supports epsX as stopping criterion
335        alglib.minlmsetcond(state, epsg: 1E-6 * yStdDev, epsf: epsF, epsx: 0.0, maxits: nIters);
336        // alglib.minlmsetgradientcheck(state, 1E-5);
337        alglib.minlmoptimize(state, Func, FuncAndJacobian, null, code);
338        alglib.minlmresults(state, out optConsts, out rep);
339        funcEvaluations += rep.nfunc;
340        gradEvaluations += rep.njac * nParams;
341
342        if (rep.terminationtype < 0) throw new ArgumentException("lm failed: termination type = " + rep.terminationtype);
343
344        // only use optimized constants if successful
345        if (rep.terminationtype >= 0) {
346          Array.Copy(optConsts, consts, optConsts.Length);
347        }
348      }
349
350      private void Func(double[] arg, double[] fi, object obj) {
351        var code = (byte[])obj;
352        int n = predBuf.Length;
353        evaluator.Exec(code, x, arg, predBuf); // gradients are nParams x vLen
354        for (int r = 0; r < n; r++) {
355          var res = predBuf[r] - y[r];
356          fi[r] = res;
357        }
358
359        var penaltyIdx = fi.Length - 1;
360        fi[penaltyIdx] = 0.0;
361        // calc length of parameter vector for regularization
362        var aa = 0.0;
363        for (int i = 0; i < arg.Length; i++) {
364          aa += arg[i] * arg[i];
365        }
366        if (lambda > 0 && aa > 0) {
367          // scale lambda using stdDev(y) to make the parameter independent of the scale of y
368          // scale lambda using n to make parameter independent of the number of training points
369          // take the root because LM squares the result
370          fi[penaltyIdx] = Math.Sqrt(n * lambda / yStdDev * aa);
371        }
372      }
373
374      private void FuncAndJacobian(double[] arg, double[] fi, double[,] jac, object obj) {
375        int n = predBuf.Length;
376        int nParams = arg.Length;
377        var code = (byte[])obj;
378        evaluator.ExecGradient(code, x, arg, predBuf, gradBuf); // gradients are nParams x vLen
379        for (int r = 0; r < n; r++) {
380          var res = predBuf[r] - y[r];
381          fi[r] = res;
382
383          for (int k = 0; k < nParams; k++) {
384            jac[r, k] = gradBuf[k][r];
385          }
386        }
387        // calc length of parameter vector for regularization
388        double aa = 0.0;
389        for (int i = 0; i < arg.Length; i++) {
390          aa += arg[i] * arg[i];
391        }
392
393        var penaltyIdx = fi.Length - 1;
394        if (lambda > 0 && aa > 0) {
395          fi[penaltyIdx] = 0.0;
396          // scale lambda using stdDev(y) to make the parameter independent of the scale of y
397          // scale lambda using n to make parameter independent of the number of training points
398          // take the root because alglib LM squares the result
399          fi[penaltyIdx] = Math.Sqrt(n * lambda / yStdDev * aa);
400
401          for (int i = 0; i < arg.Length; i++) {
402            jac[penaltyIdx, i] = 0.5 / fi[penaltyIdx] * 2 * n * lambda / yStdDev * arg[i];
403          }
404        } else {
405          fi[penaltyIdx] = 0.0;
406          for (int i = 0; i < arg.Length; i++) {
407            jac[penaltyIdx, i] = 0.0;
408          }
409        }
410      }
411
412
413      private void UpdateParetoFront(double q, int complexity, byte[] code, double[] param, int nParam,
414        double[] scalingFactor, double[] scalingOffset) {
415        double[] best = new double[2];
416        double[] cur = new double[2] { q, complexity };
417        bool[] max = new[] { true, false };
418        var isNonDominated = true;
419        foreach (var e in paretoFront) {
420          var domRes = DominationCalculator<int>.Dominates(cur, e, max, true);
421          if (domRes == DominationResult.IsDominated) {
422            isNonDominated = false;
423            break;
424          }
425        }
426        if (isNonDominated) {
427          paretoFront.Add(cur);
428
429          // create model
430          var treeGen = new SymbolicExpressionTreeGenerator(problemData.AllowedInputVariables.ToArray());
431          var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
432
433          var t = new SymbolicExpressionTree(treeGen.Exec(code, param, nParam, scalingFactor, scalingOffset));
434          var model = new SymbolicRegressionModel(problemData.TargetVariable, t, interpreter, lowerEstimationLimit, upperEstimationLimit);
435          model.Scale(problemData); // apply linear scaling
436
437          var sol = model.CreateRegressionSolution(this.problemData);
438          sol.Name = string.Format("{0:N5} {1}", q, complexity);
439
440          paretoBestModels.Add(sol);
441        }
442        for (int i = paretoFront.Count - 2; i >= 0; i--) {
443          var @ref = paretoFront[i];
444          var domRes = DominationCalculator<int>.Dominates(cur, @ref, max, true);
445          if (domRes == DominationResult.Dominates) {
446            paretoFront.RemoveAt(i);
447            paretoBestModels.RemoveAt(i);
448          }
449        }
450      }
451
452      #endregion
453
454
455    }
456
457
458    /// <summary>
459    /// Static method to initialize a state for the algorithm
460    /// </summary>
461    /// <param name="problemData">The problem data</param>
462    /// <param name="randSeed">Random seed.</param>
463    /// <param name="maxVariables">Maximum number of variable references that are allowed in the expression.</param>
464    /// <param name="scaleVariables">Optionally scale input variables to the interval [0..1] (recommended)</param>
465    /// <param name="constOptIterations">Maximum number of iterations for constants optimization (Levenberg-Marquardt)</param>
466    /// <param name="lambda">Penalty factor for regularization (0..inf.), small penalty disabled regularization.</param>
467    /// <param name="policy">Tree search policy (random, ucb, eps-greedy, ...)</param>
468    /// <param name="collectParameterOptimalModels">Optionally collect all Pareto-optimal solutions having minimal length and error.</param>
469    /// <param name="lowerEstimationLimit">Optionally limit the result of the expression to this lower value.</param>
470    /// <param name="upperEstimationLimit">Optionally limit the result of the expression to this upper value.</param>
471    /// <param name="allowProdOfVars">Allow products of expressions.</param>
472    /// <param name="allowExp">Allow expressions with exponentials.</param>
473    /// <param name="allowLog">Allow expressions with logarithms</param>
474    /// <param name="allowInv">Allow expressions with 1/x</param>
475    /// <param name="allowMultipleTerms">Allow expressions which are sums of multiple terms.</param>
476    /// <returns></returns>
477
478    public static IState CreateState(IRegressionProblemData problemData, uint randSeed, int maxVariables = 3,
479      bool scaleVariables = true, int constOptIterations = -1, double lambda = 0.0,
480      bool collectParameterOptimalModels = false,
481      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
482      bool allowProdOfVars = true,
483      bool allowExp = true,
484      bool allowLog = true,
485      bool allowInv = true,
486      bool allowMultipleTerms = false
487      ) {
488      return new State(problemData, randSeed, maxVariables, scaleVariables, constOptIterations, lambda,
489        collectParameterOptimalModels,
490        lowerEstimationLimit, upperEstimationLimit,
491        allowProdOfVars, allowExp, allowLog, allowInv, allowMultipleTerms);
492    }
493
494    // returns the quality of the evaluated solution
495    public static double MakeStep(IState state) {
496      var mctsState = state as State;
497      if (mctsState == null) throw new ArgumentException("state");
498      if (mctsState.Done) throw new NotSupportedException("The tree search has enumerated all possible solutions.");
499
500      return TreeSearch(mctsState);
501    }
502    #endregion
503
504    private static double TreeSearch(State mctsState) {
505      var automaton = mctsState.automaton;
506      var tree = mctsState.tree;
507      var eval = mctsState.evalFun;
508      var rand = mctsState.random;
509      double q = 0;
510      bool success = false;
511      do {
512
513        automaton.Reset();
514        success = TryTreeSearchRec2(rand, tree, automaton, eval, mctsState, out q);
515        mctsState.totalRollouts++;
516      } while (!success && !tree.Done);
517      if (success) {
518        mctsState.effectiveRollouts++;
519
520#if DEBUG
521        Console.WriteLine(mctsState.ExprStr(automaton));
522#endif
523
524        return q;
525      } else return 0.0;
526    }
527
528    // search forward
529    private static bool TryTreeSearchRec2(IRandom rand, Tree tree, Automaton automaton,
530      Func<byte[], int, double> eval,
531      State state,
532      out double q) {
533      // ROLLOUT AND EXPANSION
534      // We are navigating a graph (states might be reached via different paths) instead of a tree.
535      // State equivalence is checked through ExprHash (based on the generated code through the path).
536
537      // We switch between rollout-mode and expansion mode
538      // Rollout-mode means we are navigating an existing path through the tree (using a rollout policy, e.g. UCB)
539      // Expansion mode means we expand the graph, creating new nodes and edges (using an expansion policy, e.g. shortest route to a complete expression)
540      // In expansion mode we might re-enter the graph and switch back to rollout-mode
541      // We do this until we reach a complete expression (final state)
542
543      // Loops in the graph are prevented by checking that the level of a child must be larger than the level of the parent
544      // Sub-graphs which have been completely searched are marked as done.
545      // Roll-out could lead to a state where all follow-states are done. In this case we call the rollout ineffective.
546
547      while (!automaton.IsFinalState(automaton.CurrentState)) {
548        // Console.WriteLine(automaton.stateNames[automaton.CurrentState]);
549        if (state.children.ContainsKey(tree)) {
550          if (state.children[tree].All(ch => ch.Done)) {
551            tree.Done = true;
552            break;
553          }
554          // ROLLOUT INSIDE TREE
555          // UCT selection within tree
556          int selectedIdx = 0;
557          if (state.children[tree].Count > 1) {
558            selectedIdx = SelectInternal(state.children[tree], rand);
559          }
560
561          tree = state.children[tree][selectedIdx];
562
563          // move the automaton forward until reaching the state
564          // all steps where no alternatives could be taken immediately (without expanding the tree)
565          // TODO: simplification of the automaton
566          int[] possibleFollowStates = new int[1000];
567          int nFs;
568          automaton.FollowStates(automaton.CurrentState, ref possibleFollowStates, out nFs);
569          Debug.Assert(possibleFollowStates.Contains(tree.state));
570          automaton.Goto(tree.state);
571        } else {
572          // EXPAND
573          int[] possibleFollowStates = new int[1000];
574          int nFs;
575          string actionString = "";
576          automaton.FollowStates(automaton.CurrentState, ref possibleFollowStates, out nFs);
577
578          if (nFs == 0) {
579            // stuck in a dead end (no final state and no allowed follow states)
580            tree.Done = true;
581            break;
582          }
583          var newChildren = new List<Tree>(nFs);
584          state.children.Add(tree, newChildren);
585          for (int i = 0; i < nFs; i++) {
586            Tree child = null;
587            // for selected states (EvalStates) we introduce state unification (detection of equivalent states)
588            if (automaton.IsEvalState(possibleFollowStates[i])) {
589              var hc = Hashcode(automaton);
590              hc = ((hc << 5) + hc) ^ (ulong)tree.state; // TODO fix unit test for structure enumeration
591              if (!state.nodes.TryGetValue(hc, out child)) {
592                // Console.WriteLine("New expression (hash: {0}, state: {1})", Hashcode(automaton), automaton.stateNames[possibleFollowStates[i]]);
593                child = new Tree() {
594                  state = possibleFollowStates[i],
595                  expr = actionString + automaton.GetActionString(automaton.CurrentState, possibleFollowStates[i]),
596                  level = tree.level + 1
597                };
598                state.nodes.Add(hc, child);
599              }
600              // only allow forward edges (don't add the child if we would go back in the graph)
601              else if (child.level > tree.level) {
602                // Console.WriteLine("Existing expression (hash: {0}, state: {1})", Hashcode(automaton), automaton.stateNames[possibleFollowStates[i]]);
603                // whenever we join paths we need to propagate back the statistics of the existing node through the newly created link
604                // to all parents
605                BackpropagateStatistics(tree, state, child.visits);
606              } else {
607                // Console.WriteLine("Cycle (hash: {0}, state: {1})", Hashcode(automaton), automaton.stateNames[possibleFollowStates[i]]);
608                // prevent cycles
609                Debug.Assert(child.level <= tree.level);
610                child = null;
611              }
612            } else {
613              child = new Tree() {
614                state = possibleFollowStates[i],
615                expr = actionString + automaton.GetActionString(automaton.CurrentState, possibleFollowStates[i]),
616                level = tree.level + 1
617              };
618            }
619            if (child != null)
620              newChildren.Add(child);
621          }
622
623          if (!newChildren.Any()) {
624            // stuck in a dead end (no final state and no allowed follow states)
625            tree.Done = true;
626            break;
627          }
628
629          foreach (var ch in newChildren) {
630            if (!state.parents.ContainsKey(ch)) {
631              state.parents.Add(ch, new List<Tree>());
632            }
633            state.parents[ch].Add(tree);
634          }
635
636
637          // follow one of the children
638          tree = SelectStateLeadingToFinal(automaton, tree, rand, state);
639          automaton.Goto(tree.state);
640        }
641      }
642
643      bool success;
644
645      // EVALUATE TREE
646      if (!tree.Done && automaton.IsFinalState(automaton.CurrentState)) {
647        tree.Done = true;
648        tree.expr = state.ExprStr(automaton);
649        byte[] code; int nParams;
650        automaton.GetCode(out code, out nParams);
651        q = eval(code, nParams);
652        success = true;
653        BackpropagateQuality(tree, q, state);
654      } else {
655        // we got stuck in roll-out (not evaluation necessary!)
656        q = 0.0;
657        success = false;
658      }
659
660      // RECURSIVELY BACKPROPAGATE RESULTS TO ALL PARENTS
661      // Update statistics
662      // Set branch to done if all children are done.
663      BackpropagateDone(tree, state);
664      BackpropagateDebugStats(tree, q, state);
665
666
667      return success;
668    }
669
670    private static int SelectInternal(List<Tree> list, IRandom rand) {
671      // choose a random node.
672      Debug.Assert(list.Any(t => !t.Done));
673
674      var idx = rand.Next(list.Count);
675      while (list[idx].Done) { idx = rand.Next(list.Count); }
676      return idx;
677    }
678
679    // backpropagate existing statistics to all parents
680    private static void BackpropagateStatistics(Tree tree, State state, int numVisits) {
681      tree.visits += numVisits;
682
683      if (state.parents.ContainsKey(tree)) {
684        foreach (var parent in state.parents[tree]) {
685          BackpropagateStatistics(parent, state, numVisits);
686        }
687      }
688    }
689
690    private static ulong Hashcode(Automaton automaton) {
691      byte[] code;
692      int nParams;
693      automaton.GetCode(out code, out nParams);
694      return (ulong)ExprHashSymbolic.GetHash(code, nParams);
695    }
696
697    private static void BackpropagateQuality(Tree tree, double q, State state) {
698      tree.visits++;
699      // TODO: q is ignored for now
700
701      if (state.parents.ContainsKey(tree)) {
702        foreach (var parent in state.parents[tree]) {
703          BackpropagateQuality(parent, q, state);
704        }
705      }
706    }
707
708    private static void BackpropagateDone(Tree tree, State state) {
709      if (state.children.ContainsKey(tree) && state.children[tree].All(ch => ch.Done)) {
710        tree.Done = true;
711        // children[tree] = null; keep all nodes
712      }
713
714      if (state.parents.ContainsKey(tree)) {
715        foreach (var parent in state.parents[tree]) {
716          BackpropagateDone(parent, state);
717        }
718      }
719    }
720
721    private static void BackpropagateDebugStats(Tree tree, double q, State state) {
722      if (state.parents.ContainsKey(tree)) {
723        foreach (var parent in state.parents[tree]) {
724          BackpropagateDebugStats(parent, q, state);
725        }
726      }
727
728    }
729
730    private static Tree SelectStateLeadingToFinal(Automaton automaton, Tree tree, IRandom rand, State state) {
731      // find the child with the smallest state value (smaller values are closer to the final state)
732      int selectedChildIdx = 0;
733      var children = state.children[tree];
734      Tree minChild = children.First();
735      for (int i = 1; i < children.Count; i++) {
736        if (children[i].state < minChild.state)
737          selectedChildIdx = i;
738      }
739      return children[selectedChildIdx];
740    }
741
742    // scales data and extracts values from dataset into arrays
743    private static void GenerateData(IRegressionProblemData problemData, bool scaleVariables, IEnumerable<int> rows,
744      out double[][] xs, out double[] y, out double[] scalingFactor, out double[] scalingOffset) {
745      xs = new double[problemData.AllowedInputVariables.Count()][];
746
747      var i = 0;
748      if (scaleVariables) {
749        scalingFactor = new double[xs.Length + 1];
750        scalingOffset = new double[xs.Length + 1];
751      } else {
752        scalingFactor = null;
753        scalingOffset = null;
754      }
755      foreach (var var in problemData.AllowedInputVariables) {
756        if (scaleVariables) {
757          var minX = problemData.Dataset.GetDoubleValues(var, rows).Min();
758          var maxX = problemData.Dataset.GetDoubleValues(var, rows).Max();
759          var range = maxX - minX;
760
761          // scaledX = (x - min) / range
762          var sf = 1.0 / range;
763          var offset = -minX / range;
764          scalingFactor[i] = sf;
765          scalingOffset[i] = offset;
766          i++;
767        }
768      }
769
770      if (scaleVariables) {
771        // transform target variable to zero-mean
772        scalingFactor[i] = 1.0;
773        scalingOffset[i] = -problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows).Average();
774      }
775
776      GenerateData(problemData, rows, scalingFactor, scalingOffset, out xs, out y);
777    }
778
779    // extract values from dataset into arrays
780    private static void GenerateData(IRegressionProblemData problemData, IEnumerable<int> rows, double[] scalingFactor, double[] scalingOffset,
781     out double[][] xs, out double[] y) {
782      xs = new double[problemData.AllowedInputVariables.Count()][];
783
784      int i = 0;
785      foreach (var var in problemData.AllowedInputVariables) {
786        var sf = scalingFactor == null ? 1.0 : scalingFactor[i];
787        var offset = scalingFactor == null ? 0.0 : scalingOffset[i];
788        xs[i++] =
789          problemData.Dataset.GetDoubleValues(var, rows).Select(xi => xi * sf + offset).ToArray();
790      }
791
792      {
793        var sf = scalingFactor == null ? 1.0 : scalingFactor[i];
794        var offset = scalingFactor == null ? 0.0 : scalingOffset[i];
795        y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows).Select(yi => yi * sf + offset).ToArray();
796      }
797    }
798
799    // for debugging only
800
801
802    private static string TraceTree(Tree tree, State state) {
803      var sb = new StringBuilder();
804      sb.Append(
805@"digraph {
806  ratio = fill;
807  node [style=filled];
808");
809      int nodeId = 0;
810
811      TraceTreeRec(tree, 0, sb, ref nodeId, state);
812      sb.Append("}");
813      return sb.ToString();
814    }
815
816    private static void TraceTreeRec(Tree tree, int parentId, StringBuilder sb, ref int nextId, State state) {
817      var tries = tree.visits;
818
819      sb.AppendFormat("{0} [label=\"{1}\"]; ", parentId, tries).AppendLine();
820
821      var list = new List<Tuple<int, int, Tree>>();
822      if (state.children.ContainsKey(tree)) {
823        foreach (var ch in state.children[tree]) {
824          nextId++;
825          tries = ch.visits;
826          sb.AppendFormat("{0} [label=\"{1}\"]; ", nextId, tries).AppendLine();
827          sb.AppendFormat("{0} -> {1} [label=\"{2}\"]", parentId, nextId, ch.expr).AppendLine();
828          list.Add(Tuple.Create(tries, nextId, ch));
829        }
830
831        foreach (var tup in list) {
832          var ch = tup.Item3;
833          var chId = tup.Item2;
834          if (state.children.ContainsKey(ch) && state.children[ch].Count == 1) {
835            var chch = state.children[ch].First();
836            nextId++;
837            tries = chch.visits;
838            sb.AppendFormat("{0} [label=\"{1}\"]; ", nextId, tries).AppendLine();
839            sb.AppendFormat("{0} -> {1} [label=\"{2}\"]", chId, nextId, chch.expr).AppendLine();
840          }
841        }
842
843        foreach (var tup in list.OrderByDescending(t => t.Item1).Take(1)) {
844          TraceTreeRec(tup.Item3, tup.Item2, sb, ref nextId, state);
845        }
846      }
847    }
848
849    private static string WriteTree(Tree tree, State state) {
850      var sb = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);
851      var nodeIds = new Dictionary<Tree, int>();
852      sb.Write(
853@"digraph {
854  ratio = fill;
855  node [style=filled];
856");
857      int threshold = /* state.nodes.Count > 500 ? 10 : */ 0;
858      foreach (var kvp in state.children) {
859        var parent = kvp.Key;
860        int parentId;
861        if (!nodeIds.TryGetValue(parent, out parentId)) {
862          parentId = nodeIds.Count + 1;
863          var tries = parent.visits;
864          if (tries > threshold)
865            sb.Write("{0} [label=\"{1}\"]; ", parentId, tries);
866          nodeIds.Add(parent, parentId);
867        }
868        foreach (var child in kvp.Value) {
869          int childId;
870          if (!nodeIds.TryGetValue(child, out childId)) {
871            childId = nodeIds.Count + 1;
872            nodeIds.Add(child, childId);
873          }
874          var tries = child.visits;
875          if (tries < 1) continue;
876          if (tries > threshold) {
877            sb.Write("{0} [label=\"{1}\"]; ", childId, tries);
878            var edgeLabel = child.expr;
879            // if (parent.expr.Length > 0) edgeLabel = edgeLabel.Replace(parent.expr, "");
880            sb.Write("{0} -> {1} [label=\"{2}\"]", parentId, childId, edgeLabel);
881          }
882        }
883      }
884
885      sb.Write("}");
886      return sb.ToString();
887    }
888  }
889}
Note: See TracBrowser for help on using the repository browser.