Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.EMM/EMMAlgorithm.cs @ 16899

Last change on this file since 16899 was 16899, checked in by msemenki, 5 years ago

#2988: New version of class structure.

File size: 13.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.Problems.DataAnalysis.Symbolic;
28using HeuristicLab.Random;
29using HeuristicLab.Selection;
30using System.Collections.Generic;
31using System.IO;
32using System.Linq;
33using CancellationToken = System.Threading.CancellationToken;
34using Variable = HeuristicLab.Core.Variable;
35
36namespace HeuristicLab.Algorithms.EvolvmentModelsOfModels {
37  [Item("EvolvmentModelsOfModels Algorithm ", "EMM implementation")]
38  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 125)]
39  [StorableType("AD23B21F-089A-4C6C-AD2E-1B01E7939CF5")]
40  public class EMMAlgorithm : EvolvmentModelsOfModelsAlgorithmBase {
41    public EMMAlgorithm() : base() { }
42    protected EMMAlgorithm(EMMAlgorithm original, Cloner cloner) : base(original, cloner) {
43      //if (original.Map != null) {
44      //  Map = cloner.Clone(original.Map);
45      //}
46    }
47    public override IDeepCloneable Clone(Cloner cloner) {
48      return new EMMAlgorithm(this, cloner);
49    }
50
51    [StorableConstructor]
52    protected EMMAlgorithm(StorableConstructorFlag _) : base(_) { }
53
54    protected override void Run(CancellationToken cancellationToken) {
55      InfixExpressionParser parser = new InfixExpressionParser();
56      var trees = File.ReadAllLines(InputFileParameter.Value.Value).Select(parser.Parse);
57      if (AlgorithmImplemetationType.Value == "Read") {
58        Map.MapRead(RandomParameter.Value, trees, "Map.txt");
59      } else {
60        Map.MapCreationPrepare(RandomParameter.Value, trees, ClusterNumbersParameter.Value.Value);
61        Map.CreateMap(RandomParameter.Value, ClusterNumbersParameter.Value.Value);
62       // Map.WriteMapToTxtFile(RandomParameter.Value);
63      }
64
65      ClusterNumbersShowParameter.Value.Value = Map.K;
66
67      if (AlgorithmImplemetationType.Value == "OnlyMap") {
68        globalScope = new Scope("Global Scope");
69        executionContext = new ExecutionContext(null, this, globalScope);
70      } else {
71        if (previousExecutionState != ExecutionState.Paused) {
72          InitializeAlgorithm(cancellationToken);
73        }
74        if (!globalScope.Variables.ContainsKey("TreeModelMap"))
75          globalScope.Variables.Add(new Variable("TreeModelMap", Map));
76        EMMAlgorithmRun(cancellationToken);
77      }
78    }
79    private void EMMAlgorithmRun(CancellationToken cancellationToken) {
80      var bestSelector = new BestSelector();
81      bestSelector.CopySelected = new BoolValue(false);
82      bestSelector.MaximizationParameter.ActualName = "Maximization";
83      bestSelector.NumberOfSelectedSubScopesParameter.ActualName = "Elites";
84      bestSelector.QualityParameter.ActualName = "Quality";
85
86      var populationSize = PopulationSize.Value;
87      var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value;
88      var crossover = Crossover;
89      var selector = Selector;
90      var groupSize = GroupSize.Value;
91      var crossoverProbability = CrossoverProbability.Value;
92      var mutator = Mutator;
93      var mutationProbability = MutationProbability.Value;
94      var evaluator = Problem.Evaluator;
95      var analyzer = Analyzer;
96      var rand = RandomParameter.Value;
97      var elites = Elites.Value;
98
99      // cancellation token for the inner operations which should not be immediately cancelled
100      var innerToken = new CancellationToken();
101
102      while (EvaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) {
103
104        var op4 = executionContext.CreateChildOperation(bestSelector, executionContext.Scope); // select elites
105        ExecuteOperation(executionContext, innerToken, op4);
106
107        var remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
108        executionContext.Scope.SubScopes.AddRange(remaining.SubScopes);
109        var selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
110        executionContext.Scope.SubScopes.AddRange(selected.SubScopes);
111        Population.Clear();
112        Population.AddRange(selected.SubScopes.Select(x => new EMMSolution(x)));
113        executionContext.Scope.SubScopes.Remove(remaining);
114        executionContext.Scope.SubScopes.Remove(selected);
115
116        var op = executionContext.CreateChildOperation(selector, executionContext.Scope);// select the rest of the Population
117        ExecuteOperation(executionContext, innerToken, op);
118
119        remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
120        selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
121
122        for (int i = 0; i < selector.NumberOfSelectedSubScopesParameter.Value.Value; i += 2) {
123          // crossover
124          IScope childScope = null;
125          if (rand.NextDouble() < crossoverProbability) {
126            childScope = new Scope($"{i}+{i + 1}") { Parent = executionContext.Scope };
127            childScope.SubScopes.Add(selected.SubScopes[i]);
128            childScope.SubScopes.Add(selected.SubScopes[i + 1]);
129            var op1 = executionContext.CreateChildOperation(crossover, childScope);
130            ExecuteOperation(executionContext, innerToken, op1);
131            childScope.SubScopes.Clear();
132          }
133
134          childScope = childScope ?? selected.SubScopes[i];
135          // mutation
136          if (rand.NextDouble() < mutationProbability) {
137            var op2 = executionContext.CreateChildOperation(mutator, childScope);
138            ExecuteOperation(executionContext, innerToken, op2);
139          }
140
141          // evaluation
142          if (childScope != null) {
143            var op3 = executionContext.CreateChildOperation(evaluator, childScope);
144            ExecuteOperation(executionContext, innerToken, op3);
145            var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
146            var childSolution = new EMMSolution(childScope);
147            // set child qualities
148            childSolution.Qualities = qualities;
149            ++EvaluatedSolutions;
150            Population.Add(new EMMSolution(childScope));
151          } else {// no crossover or mutation were applied, a child was not produced, do nothing
152            Population.Add(new EMMSolution(selected.SubScopes[i]));
153          }
154
155          if (EvaluatedSolutions >= maximumEvaluatedSolutions) {
156            break;
157          }
158
159        }
160        globalScope.SubScopes.Replace(Population.Select(x => (IScope)x.Individual));
161        // run analyzer
162        var analyze = executionContext.CreateChildOperation(analyzer, globalScope);
163        ExecuteOperation(executionContext, innerToken, analyze);
164        Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(EvaluatedSolutions));
165      }
166    }
167    protected void InitializeAlgorithm(CancellationToken cancellationToken) {
168      globalScope = new Scope("Global Scope");
169      executionContext = new ExecutionContext(null, this, globalScope);
170
171      // set the execution context for parameters to allow lookup
172      foreach (var parameter in Problem.Parameters.OfType<IValueParameter>()) {  //
173                                                                                 // we need all of these in order for the wiring of the operators to work
174        globalScope.Variables.Add(new Core.Variable(parameter.Name, parameter.Value));
175      }
176      globalScope.Variables.Add(new Core.Variable("Results", Results)); // make results available as a parameter for analyzers etc.
177
178      var rand = RandomParameter.Value;
179      if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
180      rand.Reset(Seed);
181
182      var populationSize = PopulationSize.Value;
183
184      InitializePopulation(executionContext, cancellationToken, rand);
185
186      // initialize data structures for map clustering
187      //var models = new ItemList<ISymbolicExpressionTree>(Map.ModelSet);
188      //var map = new ItemList<ItemList<IntValue>>();
189      //foreach (var list in Map.Map) {
190      //  map.Add(new ItemList<IntValue>(list.Select(x => new IntValue(x))));
191      //}
192      //var clusterNumber = new ItemList<IntValue>(Map.ClusterNumber.Select(x => new IntValue(x)));
193      //globalScope.Variables.Add(new Variable("Models", models));
194      //globalScope.Variables.Add(new Variable("Map", map));
195      //globalScope.Variables.Add(new Variable("ClusterNumber", clusterNumber));
196
197      EvaluatedSolutions = populationSize;
198      base.Initialize(cancellationToken);
199    }
200    private void InitializePopulation(ExecutionContext executionContext, CancellationToken cancellationToken, IRandom random) {
201      var creator = Problem.SolutionCreator;
202      var evaluator = Problem.Evaluator;
203      var populationSize = PopulationSize.Value;
204      Population = new List<IEMMSolution>(populationSize);
205
206      var parentScope = executionContext.Scope; //main scope for the next step work
207      // first, create all individuals
208      for (int i = 0; i < populationSize; ++i) {
209        var childScope = new Scope(i.ToString()) { Parent = parentScope };
210        ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(creator, childScope));
211        var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
212        var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
213        foreach (var node in tree.IterateNodesPostfix().OfType<TreeModelTreeNode>()) {
214          node.Tree = Map.NewModelForInizializtion(random, out int cluster, out int treeNumber);
215          node.SetLocalParameters(random, 0.5);
216          node.ClusterNumer = cluster;
217          node.TreeNumber = treeNumber;
218        }
219        parentScope.SubScopes.Add(childScope);
220      }
221
222      // then, evaluate them and update qualities
223      for (int i = 0; i < populationSize; ++i) {
224        var childScope = parentScope.SubScopes[i];
225        ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
226
227        var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
228        var solution = new EMMSolution(childScope);  // Create solution and push individual inside
229
230        solution.Qualities = qualities;
231        Population.Add(solution);  // push solution to Population
232      }
233    }
234    private void LocalDecent(ISymbolicDataAnalysisSingleObjectiveProblem problem, CancellationToken cancellationToken, IScope childScope) {
235      int maxStepNumber = 100;
236      var creator = Problem.SolutionCreator;
237      var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
238      var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
239      var evaluator = problem.Evaluator;
240      var oldTree = tree.Clone();
241      ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
242      var rand = RandomParameter.Value;
243      if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
244      rand.Reset(Seed);
245      while (maxStepNumber > 0) {
246        maxStepNumber = TreeIterator(tree.Root, rand, cancellationToken, childScope, maxStepNumber);
247      }
248    }
249    int TreeIterator(ISymbolicExpressionTreeNode a, IRandom rand, CancellationToken cancellationToken, IScope childScope, int maxStepNumber) {
250      if (a is TreeModelTreeNode modelNode) {
251        ModelChange(modelNode, rand, cancellationToken, childScope);
252        maxStepNumber--;
253      }
254      if (a.Subtrees != null) {
255        for (int i = 0; i < (a.Subtrees.Count()); i++) {
256          TreeIterator(a.Subtrees.ToList()[i], rand, cancellationToken, childScope, maxStepNumber);
257        }
258      }
259      return maxStepNumber;
260    }
261    void ModelChange(TreeModelTreeNode a, IRandom rand, CancellationToken cancellationToken, IScope childScope) {
262      int treeNumber = a.TreeNumber;
263      var oldSubTree = (ISymbolicExpressionTree)a.Tree.Clone();
264      double oldQuality = ((DoubleValue)childScope.Variables["Quality"].Value).Value;
265      int cluster = Map.ClusterNumber[treeNumber];
266      int newTreeNumber = rand.Next(Map.Map[cluster].Count);
267      a.Tree = (ISymbolicExpressionTree)Map.ModelSet[newTreeNumber].Clone();
268      a.Tree.Root.ShakeLocalParameters(rand, 1);
269      var evaluator = Problem.Evaluator;
270      ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
271      double currentQuality = ((DoubleValue)childScope.Variables["Quality"].Value).Value;
272      if (oldQuality > currentQuality) {
273        a.Tree = (ISymbolicExpressionTree)oldSubTree.Clone();
274        ((DoubleValue)childScope.Variables["Quality"].Value).Value = oldQuality;
275      }
276    }
277  }
278
279
280}
281
Note: See TracBrowser for help on using the repository browser.