Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.StructureIdentification/Manipulation/CutOutNodeManipulation.cs @ 135

Last change on this file since 135 was 23, checked in by gkronber, 17 years ago

changed boolean variable BalanceTrees to double BalancedTreesRate (ticket #11)

File size: 8.4 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Operators;
27using HeuristicLab.Random;
28using System;
29
30namespace HeuristicLab.StructureIdentification {
31  public class CutOutNodeManipulation : OperatorBase {
32    public override string Description {
33      get {
34        return @"Takes a tree, selects a random node of the tree and then tries to replace a random child
35of that node with one of the childs of the selected child.
36
37               O                             O
38              / \                           / \
39             O   X                         O   2
40                / \    2 is selected =>       / \
41               1   2                         4   5
42              /   / \
43             3   4   5
44";
45      }
46    }
47
48    public CutOutNodeManipulation()
49      : base() {
50      AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In));
51      AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(GPOperatorLibrary), VariableKind.In));
52      AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In));
53      AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
[23]54      AddVariableInfo(new VariableInfo("BalancedTreesRate", "Determines how many trees should be balanced", typeof(DoubleData), VariableKind.In));
[2]55      AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IOperator), VariableKind.In));
56      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
57      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In));
58    }
59
60
61    public override IOperation Apply(IScope scope) {
62      IOperator rootOperator = GetVariableValue<IOperator>("OperatorTree", scope, true);
63      MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true);
64      GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);
65      int maxTreeHeight = GetVariableValue<IntData>("MaxTreeHeight", scope, true).Data;
66      int maxTreeSize = GetVariableValue<IntData>("MaxTreeSize", scope, true).Data;
[23]67      double balancedTreesRate = GetVariableValue<DoubleData>("BalancedTreesRate", scope, true).Data;
[2]68
69      TreeGardener gardener = new TreeGardener(random, library);
70      IOperator parent = gardener.GetRandomParentNode(rootOperator);
71      // parent == null means we should cut out the root node
72      // => return a random suboperator of the root
73      if (parent == null) {
74        // when there are suboperators then replace the old operator with a random suboperator
75        if (rootOperator.SubOperators.Count > 0) {
76          rootOperator = rootOperator.SubOperators[random.Next(rootOperator.SubOperators.Count)];
77
78          GetVariableValue<IntData>("TreeSize", scope, true).Data = gardener.GetTreeSize(rootOperator);
79          GetVariableValue<IntData>("TreeHeight", scope, true).Data = gardener.GetTreeHeight(rootOperator);
80
81          // this is not really necessary (we can leave it in until the operator is stable)
82          if (!gardener.IsValidTree(rootOperator)) {
83            throw new InvalidProgramException();
84          }
85
86          // update the variable
87          scope.GetVariable("OperatorTree").Value = rootOperator;
88          if (!gardener.IsValidTree(rootOperator)) {
89            throw new InvalidProgramException();
90          }
91
92
93          // the tree is already initialized so we don't have to schedule initialization operations
94          return null;
95        } else {
96          // create a new random tree
[23]97          IOperator newOperator;
98          if(random.NextDouble() <= balancedTreesRate) {
99            newOperator = gardener.CreateRandomTree(gardener.AllOperators, maxTreeSize, maxTreeHeight, true);
100          } else {
101            newOperator = gardener.CreateRandomTree(gardener.AllOperators, maxTreeSize, maxTreeHeight, false);
102          }
[2]103
104          GetVariableValue<IntData>("TreeSize", scope, true).Data = gardener.GetTreeSize(newOperator);
105          GetVariableValue<IntData>("TreeHeight", scope, true).Data = gardener.GetTreeHeight(newOperator);
106
107          if (!gardener.IsValidTree(newOperator)) {
108            throw new InvalidProgramException();
109          }
110
111          // update the variable
112          scope.GetVariable("OperatorTree").Value = newOperator;
113
114          if (!gardener.IsValidTree(newOperator)) {
115            throw new InvalidProgramException();
116          }
117
118          // schedule an operation to initialize the whole operator graph
119          return gardener.CreateInitializationOperation(gardener.GetAllOperators(newOperator), scope);
120        }
121      }
122
123      int childIndex = random.Next(parent.SubOperators.Count);
124      IOperator child = parent.SubOperators[childIndex];
125
126      // match the suboperators of the child with the allowed suboperators of the parent
127      IOperator[] possibleChilds = gardener.GetAllowedSubOperators(parent, childIndex).SelectMany(allowedOp => child.SubOperators
128        .Where(subOp => ((StringData)subOp.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data ==
129          ((StringData)allowedOp.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data)).ToArray();
130
131
132      if (possibleChilds.Length > 0) {
133        // replace child with a random child of the child
134        // make a clone to simplify removing obsolete operators from the operator-graph
135        IOperator selectedChild = (IOperator)possibleChilds[random.Next(possibleChilds.Length)].Clone();       
136        parent.RemoveSubOperator(childIndex);
137        parent.AddSubOperator(selectedChild, childIndex);
138
139        if (!gardener.IsValidTree(rootOperator)) {
140          throw new InvalidProgramException();
141        }
142
143        // update the size and height of our tree
144        GetVariableValue<IntData>("TreeSize", scope, true).Data = gardener.GetTreeSize(rootOperator);
145        GetVariableValue<IntData>("TreeHeight", scope, true).Data = gardener.GetTreeHeight(rootOperator);
146        // don't need to schedule initialization operations
147        return null;
148      } else {
149        // determine the level of the parent
150        int parentLevel = gardener.GetNodeLevel(rootOperator, parent);
151
152        // first remove the old child (first step essential!)
153        parent.RemoveSubOperator(childIndex);
154        // then determine the number of nodes left over after the child has been removed!
155        int remainingNodes = gardener.GetTreeSize(rootOperator);
156
157        IList<IOperator> allowedOperators = gardener.GetAllowedSubOperators(parent, childIndex);
158        IOperator newOperatorTree = gardener.CreateRandomTree(allowedOperators, maxTreeSize - remainingNodes, maxTreeHeight - parentLevel, true);
159
160        parent.AddSubOperator(newOperatorTree, childIndex);
161
162        GetVariableValue<IntData>("TreeSize", scope, true).Data = gardener.GetTreeSize(rootOperator);
163        GetVariableValue<IntData>("TreeHeight", scope, true).Data = gardener.GetTreeHeight(rootOperator);
164
165        if (!gardener.IsValidTree(rootOperator)) {
166          throw new InvalidProgramException();
167        }
168
169        // schedule an initialization operation for the new operator
170        return gardener.CreateInitializationOperation(gardener.GetAllOperators(newOperatorTree), scope);
171      }
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.