Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/RemoveBranchManipulation.cs @ 17387

Last change on this file since 17387 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 6.7 KB
RevLine 
[4189]1#region License Information
2/* HeuristicLab
[17181]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4189]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
[8333]22using System.Collections.Generic;
[4189]23using System.Linq;
[4722]24using HeuristicLab.Common;
[4189]25using HeuristicLab.Core;
26using HeuristicLab.Data;
[5686]27using HeuristicLab.Parameters;
[17097]28using HEAL.Attic;
[12706]29using HeuristicLab.Random;
[4189]30
[5499]31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[17097]32  [StorableType("639F837E-3AF9-4783-9AC2-0A4DC8991FED")]
[8333]33  [Item("RemoveBranchManipulation", "Removes a random sub-tree of the input tree and fixes the tree by generating random subtrees if necessary..")]
34  public sealed class RemoveBranchManipulation : SymbolicExpressionTreeManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
[7662]35    private const int MAX_TRIES = 100;
[5499]36    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
37    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
38    #region Parameter Properties
39    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
40      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
41    }
42    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
43      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
44    }
45    #endregion
46    #region Properties
47    public IntValue MaximumSymbolicExpressionTreeLength {
48      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
49    }
50    public IntValue MaximumSymbolicExpressionTreeDepth {
51      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
52    }
53    #endregion
54
[4722]55    [StorableConstructor]
[17097]56    private RemoveBranchManipulation(StorableConstructorFlag _) : base(_) { }
[8333]57    private RemoveBranchManipulation(RemoveBranchManipulation original, Cloner cloner) : base(original, cloner) { }
58    public RemoveBranchManipulation()
[5499]59      : base() {
60      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
61      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
62    }
[4189]63
[4722]64    public override IDeepCloneable Clone(Cloner cloner) {
[8333]65      return new RemoveBranchManipulation(this, cloner);
[4189]66    }
67
[5499]68    protected override void Manipulate(IRandom random, ISymbolicExpressionTree symbolicExpressionTree) {
[8333]69      RemoveRandomBranch(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
[4189]70    }
71
[8333]72    public static void RemoveRandomBranch(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, int maxTreeLength, int maxTreeDepth) {
[7662]73      var allowedSymbols = new List<ISymbol>();
74      ISymbolicExpressionTreeNode parent;
75      int childIndex;
76      int maxLength;
77      int maxDepth;
78      // repeat until a fitting parent and child are found (MAX_TRIES times)
79      int tries = 0;
[8333]80
81      var nodes = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).ToList();
[7662]82      do {
[12706]83        parent = nodes.SampleRandom(random);
84
[7662]85        childIndex = random.Next(parent.SubtreeCount);
86        var child = parent.GetSubtree(childIndex);
87        maxLength = maxTreeLength - symbolicExpressionTree.Length + child.GetLength();
88        maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + child.GetDepth();
[5014]89
[7662]90        allowedSymbols.Clear();
91        foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) {
92          // check basic properties that the new symbol must have
93          if (symbol.Name != child.Symbol.Name &&
94            symbol.InitialFrequency > 0 &&
95            parent.Grammar.GetMinimumExpressionDepth(symbol) + 1 <= maxDepth &&
96            parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength) {
97            allowedSymbols.Add(symbol);
98          }
99        }
100        tries++;
101      } while (tries < MAX_TRIES && allowedSymbols.Count == 0);
[5569]102
[8333]103      if (tries >= MAX_TRIES) return;
104      ReplaceWithMinimalTree(random, symbolicExpressionTree.Root, parent, childIndex);
105    }
[4189]106
[8333]107    private static void ReplaceWithMinimalTree(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode parent, int childIndex) {
108      // determine possible symbols that will lead to the smallest possible tree
109      var possibleSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)
110                             where s.InitialFrequency > 0.0
111                             group s by parent.Grammar.GetMinimumExpressionLength(s) into g
112                             orderby g.Key
113                             select g).First().ToList();
114      var weights = possibleSymbols.Select(x => x.InitialFrequency).ToList();
[12706]115
116#pragma warning disable 612, 618
[8333]117      var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[12706]118#pragma warning restore 612, 618
119
[8333]120      var newTreeNode = selectedSymbol.CreateTreeNode();
121      if (newTreeNode.HasLocalParameters) newTreeNode.ResetLocalParameters(random);
122      parent.RemoveSubtree(childIndex);
123      parent.InsertSubtree(childIndex, newTreeNode);
124
125      var topLevelNode = newTreeNode as SymbolicExpressionTreeTopLevelNode;
126      if (topLevelNode != null)
127        topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
128
129      for (int i = 0; i < newTreeNode.Grammar.GetMinimumSubtreeCount(newTreeNode.Symbol); i++) {
130        // insert a dummy sub-tree and add the pending extension to the list
131        var dummy = new SymbolicExpressionTreeNode();
132        newTreeNode.AddSubtree(dummy);
133        // replace the just inserted dummy by recursive application
134        ReplaceWithMinimalTree(random, root, newTreeNode, i);
[7662]135      }
[4189]136    }
137  }
138}
Note: See TracBrowser for help on using the repository browser.