Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.EMM/EMMMutators.cs @ 16752

Last change on this file since 16752 was 16734, checked in by msemenki, 6 years ago

#2988: Add Model Symbol Frequency Analyzer and Model's Clusters Frequency Analyzer. Fix Bag's with Keys. Fix changing during mutation for Variables Types in SubModels .

File size: 6.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
27using HeuristicLab.Parameters;
28using HeuristicLab.Problems.DataAnalysis.Symbolic;
29using HeuristicLab.Random;
30using System.Collections.Generic;
31using System.Linq;
32
33namespace HeuristicLab.Algorithms.EvolvmentModelsOfModels {
34  [Item("EMMChangeNodeTypeManipulation", "Selects a random tree node and changes the symbol.")]
35  [StorableType("990D3946-7F06-48B4-B8DB-F8E308D6304D")]
36  public sealed class EMMMutators : SymbolicExpressionTreeManipulator {
37    private const int MAX_TRIES = 100;
38
39    private const string ModelSetParameterName = "Models";
40    private const string ClusterNumberParameterName = "ClusterNumber";
41    private const string MapParameterName = "Map";
42
43    public ILookupParameter<ItemList<ISymbolicExpressionTree>> ModelSetParameter {
44      get { return (ILookupParameter<ItemList<ISymbolicExpressionTree>>)Parameters[ModelSetParameterName]; }
45    }
46
47    public ILookupParameter<ItemList<IntValue>> ClusterNumberParameter {
48      get { return (ILookupParameter<ItemList<IntValue>>)Parameters[ClusterNumberParameterName]; }
49    }
50
51    public ILookupParameter<ItemList<ItemList<IntValue>>> MapParameter {
52      get { return (ILookupParameter<ItemList<ItemList<IntValue>>>)Parameters[MapParameterName]; }
53    }
54
55    public ItemList<ISymbolicExpressionTree> ModelSet => ModelSetParameter.ActualValue;
56    public ItemList<IntValue> ClusterNumber => ClusterNumberParameter.ActualValue;
57    public ItemList<ItemList<IntValue>> Map => MapParameter.ActualValue;
58
59    [StorableConstructor]
60    private EMMMutators(StorableConstructorFlag _) : base(_) { }
61    private EMMMutators(EMMMutators original, Cloner cloner) : base(original, cloner) { }
62    public EMMMutators() : base() {
63      Parameters.Add(new LookupParameter<ItemList<ISymbolicExpressionTree>>(ModelSetParameterName));
64      Parameters.Add(new LookupParameter<ItemList<IntValue>>(ClusterNumberParameterName));
65      Parameters.Add(new LookupParameter<ItemList<ItemList<IntValue>>>(MapParameterName));
66    }
67
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new EMMMutators(this, cloner);
70    }
71
72    protected override void Manipulate(IRandom random, ISymbolicExpressionTree symbolicExpressionTree) {
73      //EMMMapTreeModel map= (EMMMapTreeModel)ExecutionContext.Scope.Variables["TreeModelMap"].Value;
74      EMMMutatorsPart(random, symbolicExpressionTree, ModelSet, ClusterNumber, Map);
75    }
76    public static void EMMMutatorsPart(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, ItemList<ISymbolicExpressionTree> modelSet, ItemList<IntValue> clusterNumber, ItemList<ItemList<IntValue>> map) {
77      List<ISymbol> allowedSymbols = new List<ISymbol>();
78      ISymbolicExpressionTreeNode parent;
79      int childIndex;
80      ISymbolicExpressionTreeNode child;
81      // repeat until a fitting parent and child are found (MAX_TRIES times)
82      int tries = 0;
83      do {
84
85#pragma warning disable 612, 618
86        parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random);
87#pragma warning restore 612, 618
88
89        childIndex = random.Next(parent.SubtreeCount);
90
91        child = parent.GetSubtree(childIndex);
92        int existingSubtreeCount = child.SubtreeCount;
93        allowedSymbols.Clear();
94        foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) {
95          // check basic properties that the new symbol must have
96          if (symbol.Name != child.Symbol.Name &&
97            symbol.InitialFrequency > 0 &&
98            existingSubtreeCount <= parent.Grammar.GetMinimumSubtreeCount(symbol) &&
99            existingSubtreeCount >= parent.Grammar.GetMaximumSubtreeCount(symbol)) {
100            // check that all existing subtrees are also allowed for the new symbol
101            bool allExistingSubtreesAllowed = true;
102            for (int existingSubtreeIndex = 0; existingSubtreeIndex < existingSubtreeCount && allExistingSubtreesAllowed; existingSubtreeIndex++) {
103              var existingSubtree = child.GetSubtree(existingSubtreeIndex);
104              allExistingSubtreesAllowed &= parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex);
105            }
106            if (allExistingSubtreesAllowed) {
107              allowedSymbols.Add(symbol);
108            }
109          }
110        }
111        tries++;
112      } while (tries < MAX_TRIES && allowedSymbols.Count == 0);
113
114      if (tries < MAX_TRIES) {
115        var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList();
116#pragma warning disable 612, 618
117        var newSymbol = allowedSymbols.SelectRandom(weights, random);
118#pragma warning restore 612, 618
119
120        // replace the old node with the new node
121
122        var newNode = newSymbol.CreateTreeNode();
123        if (newNode.HasLocalParameters)
124          if (newNode is TreeModelTreeNode treeNode) {
125            int p = random.Next(map.Count);
126            if (child is TreeModelTreeNode chNode) // in real life never bacame true. It need some cheking
127            { p = chNode.ClusterNumer; }
128            treeNode.TreeNumber = map[p].SampleRandom(random).Value;
129            treeNode.Tree = (ISymbolicExpressionTree)modelSet[treeNode.TreeNumber].Clone();
130            treeNode.SetLocalParameters(random, 0.5);
131          } else
132            newNode.ResetLocalParameters(random);
133        foreach (var subtree in child.Subtrees)
134          newNode.AddSubtree(subtree);
135        parent.RemoveSubtree(childIndex);
136        parent.InsertSubtree(childIndex, newNode);
137      }
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.