Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Manipulators/ChangeNodeTypeManipulation.cs @ 4722

Last change on this file since 4722 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 5.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Manipulators {
32  [StorableClass]
33  [Item("ChangeNodeTypeManipulation", "Selects a random tree node and changes the symbol.")]
34  public sealed class ChangeNodeTypeManipulation : SymbolicExpressionTreeManipulator {
35
36    [StorableConstructor]
37    private ChangeNodeTypeManipulation(bool deserializing) : base(deserializing) { }
38    private ChangeNodeTypeManipulation(ChangeNodeTypeManipulation original, Cloner cloner) : base(original, cloner) { }
39    public ChangeNodeTypeManipulation() : base() { }
40
41    public override IDeepCloneable Clone(Cloner cloner) {
42      return new ChangeNodeTypeManipulation(this, cloner);
43    }
44
45    protected override void Manipulate(IRandom random, SymbolicExpressionTree symbolicExpressionTree, ISymbolicExpressionGrammar grammar, IntValue maxTreeSize, IntValue maxTreeHeight, out bool success) {
46      ChangeNodeType(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, out success);
47    }
48
49    public static void ChangeNodeType(IRandom random, SymbolicExpressionTree symbolicExpressionTree, ISymbolicExpressionGrammar grammar, int maxTreeSize, int maxTreeHeight, out bool success) {
50
51      // select any node as parent (except the root node)
52      var manipulationPoint = (from parent in symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1)
53                               from subtree in parent.SubTrees
54                               select new { Parent = parent, Node = subtree, Index = parent.SubTrees.IndexOf(subtree) }).SelectRandom(random);
55      // find possible symbols for the node (also considering the existing branches below it)
56      var allowedSymbols = from symbol in manipulationPoint.Parent.GetAllowedSymbols(manipulationPoint.Index)
57                           where manipulationPoint.Node.SubTrees.Count <= manipulationPoint.Node.Grammar.GetMaxSubtreeCount(symbol)
58                           where manipulationPoint.Node.SubTrees.Count >= manipulationPoint.Node.Grammar.GetMinSubtreeCount(symbol)
59                           select symbol;
60
61      if (allowedSymbols.Count() <= 1) {
62        success = false;
63        return;
64      }
65      var node = manipulationPoint.Node;
66      // keep only symbols that are still possible considering the existing sub-trees
67      var constrainedSymbols = from symbol in allowedSymbols
68                               let disallowedSubtrees =
69                                     from subtree in node.SubTrees
70                                     where !node.Grammar.IsAllowedChild(symbol, subtree.Symbol, node.SubTrees.IndexOf(subtree))
71                                     select subtree
72                               where disallowedSubtrees.Count() == 0
73                               select symbol;
74      if (constrainedSymbols.Count() <= 1) {
75        success = false;
76        return;
77      }
78      var newSymbol = SelectRandomSymbol(random, constrainedSymbols);
79
80      // replace the old node with the new node
81      var newNode = newSymbol.CreateTreeNode();
82      if (newNode.HasLocalParameters)
83        newNode.ResetLocalParameters(random);
84      foreach (var subtree in node.SubTrees)
85        newNode.AddSubTree(subtree);
86      manipulationPoint.Parent.RemoveSubTree(manipulationPoint.Index);
87      manipulationPoint.Parent.InsertSubTree(manipulationPoint.Index, newNode);
88      success = true;
89    }
90
91    private static Symbol SelectRandomSymbol(IRandom random, IEnumerable<Symbol> symbols) {
92      var symbolList = symbols.ToList();
93      var ticketsSum = symbolList.Select(x => x.InitialFrequency).Sum();
94      if (ticketsSum == 0.0) throw new ArgumentException("The initial frequency of all allowed symbols is zero.");
95      var r = random.NextDouble() * ticketsSum;
96      double aggregatedTickets = 0;
97      for (int i = 0; i < symbolList.Count; i++) {
98        aggregatedTickets += symbolList[i].InitialFrequency;
99        if (aggregatedTickets > r) {
100          return symbolList[i];
101        }
102      }
103      // this should never happen
104      throw new ArgumentException("There is a problem with the initial frequency setting of allowed symbols.");
105    }
106  }
107}
Note: See TracBrowser for help on using the repository browser.