Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Manipulators/ReplaceBranchManipulation.cs @ 16375

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

Updated year of copyrights (#1406)

File size: 4.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Creators;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Manipulators {
33  [StorableClass]
34  [Item("ReplaceBranchManipulation", "Selects a branch of the tree randomly and replaces it with a newly initialized branch (using PTC2).")]
35  public sealed class ReplaceBranchManipulation : SymbolicExpressionTreeManipulator {
36    [StorableConstructor]
37    private ReplaceBranchManipulation(bool deserializing) : base(deserializing) { }
38    private ReplaceBranchManipulation(ReplaceBranchManipulation original, Cloner cloner) : base(original, cloner) { }
39    public ReplaceBranchManipulation() : base() { }
40
41    public override IDeepCloneable Clone(Cloner cloner) {
42      return new ReplaceBranchManipulation(this, cloner);
43    }
44
45    protected override void Manipulate(IRandom random, SymbolicExpressionTree symbolicExpressionTree, ISymbolicExpressionGrammar grammar, IntValue maxTreeSize, IntValue maxTreeHeight, out bool success) {
46      ReplaceRandomBranch(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, out success);
47    }
48
49    public static void ReplaceRandomBranch(IRandom random, SymbolicExpressionTree symbolicExpressionTree, ISymbolicExpressionGrammar grammar, int maxTreeSize, int maxTreeHeight, out bool success) {
50      success = false;
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
56      int maxSize = maxTreeSize - symbolicExpressionTree.Size + manipulationPoint.Node.GetSize();
57      int maxHeight = maxTreeHeight - symbolicExpressionTree.Height + manipulationPoint.Node.GetHeight();
58      // find possible symbols for the node (also considering the existing branches below it)
59      var allowedSymbols = from symbol in manipulationPoint.Parent.GetAllowedSymbols(manipulationPoint.Index)
60                           where manipulationPoint.Node.Grammar.GetMinExpressionDepth(symbol) <= maxHeight
61                           where manipulationPoint.Node.Grammar.GetMinExpressionLength(symbol) <= maxSize
62                           select symbol;
63      if (allowedSymbols.Count() == 0) return;
64
65      var seedSymbol = SelectRandomSymbol(random, allowedSymbols);  // replace the old node with the new node
66      var seedNode = seedSymbol.CreateTreeNode();
67      if (seedNode.HasLocalParameters)
68        seedNode.ResetLocalParameters(random);
69
70      manipulationPoint.Parent.RemoveSubTree(manipulationPoint.Index);
71      manipulationPoint.Parent.InsertSubTree(manipulationPoint.Index, seedNode);
72      seedNode = ProbabilisticTreeCreator.PTC2(random, seedNode, maxSize, maxHeight, 0, 0);
73      success = true;
74    }
75
76    private static Symbol SelectRandomSymbol(IRandom random, IEnumerable<Symbol> symbols) {
77      var symbolList = symbols.ToList();
78      var ticketsSum = symbolList.Select(x => x.InitialFrequency).Sum();
79      if (ticketsSum == 0.0) throw new ArgumentException("The initial frequency of all allowed symbols is zero.");
80      var r = random.NextDouble() * ticketsSum;
81      double aggregatedTickets = 0;
82      for (int i = 0; i < symbolList.Count; i++) {
83        aggregatedTickets += symbolList[i].InitialFrequency;
84        if (aggregatedTickets > r) {
85          return symbolList[i];
86        }
87      }
88      // this should never happen
89      throw new ArgumentException("There is a problem with the initial frequency setting of allowed symbols.");
90    }
91  }
92}
Note: See TracBrowser for help on using the repository browser.