Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16724 was 16722, checked in by msemenki, 6 years ago

#2988: Add first version of GP for Evolvment models of models.

File size: 10.6 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("D02C50E5-8325-496F-8DEA-C23651756846")]
40  public class EMMAlgorithm : EvolvmentModelsOfModelsAlgorithmBase {
41    public EMMMapTreeModel Map { get; private set; }
42
43    public EMMAlgorithm() : base() { }
44    protected EMMAlgorithm(EMMAlgorithm original, Cloner cloner) : base(original, cloner) {
45      if (original.Map != null) {
46        Map = cloner.Clone(original.Map);
47      }
48    }
49    public override IDeepCloneable Clone(Cloner cloner) {
50      return new EMMAlgorithm(this, cloner);
51    }
52
53    [StorableConstructor]
54    protected EMMAlgorithm(StorableConstructorFlag _) : base(_) { }
55
56    protected override void Run(CancellationToken cancellationToken) {
57      InfixExpressionParser parser = new InfixExpressionParser();
58      var trees = File.ReadAllLines(InputFileParameter.Value.Value).Select(parser.Parse);
59      Map = new EMMMapTreeModel(RandomParameter.Value, trees, ClusterNumbersParameter.Value.Value);
60      ClusterNumbersParameter.Value.Value = Map.K;
61      if (previousExecutionState != ExecutionState.Paused) {
62        InitializeAlgorithm(cancellationToken);
63      }
64      globalScope.Variables.Add(new Variable("TreeModelMap", Map));
65      EMMEvolutionaryAlgorithmRun(cancellationToken);
66    }
67    private void EMMEvolutionaryAlgorithmRun(CancellationToken cancellationToken) {
68      var bestSelector = new BestSelector();
69      bestSelector.CopySelected = new BoolValue(false);
70      bestSelector.MaximizationParameter.ActualName = "Maximization";
71      bestSelector.NumberOfSelectedSubScopesParameter.ActualName = "Elites";
72      bestSelector.QualityParameter.ActualName = "Quality";
73
74      var populationSize = PopulationSize.Value;
75      var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value;
76      var crossover = Crossover;
77      var selector = Selector;
78      var groupSize = GroupSize.Value;
79      var crossoverProbability = CrossoverProbability.Value;
80      var mutator = Mutator;
81      var mutationProbability = MutationProbability.Value;
82      var evaluator = Problem.Evaluator;
83      var analyzer = Analyzer;
84      var rand = RandomParameter.Value;
85      var elites = Elites.Value;
86
87      // cancellation token for the inner operations which should not be immediately cancelled
88      var innerToken = new CancellationToken();
89
90      while (evaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) {
91
92        var op4 = executionContext.CreateChildOperation(bestSelector, executionContext.Scope); // select elites
93        ExecuteOperation(executionContext, innerToken, op4);
94
95        var remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
96        executionContext.Scope.SubScopes.AddRange(remaining.SubScopes);
97        var selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
98        executionContext.Scope.SubScopes.AddRange(selected.SubScopes);
99        population.Clear();
100        population.AddRange(selected.SubScopes.Select(x => new EMMSolution(x)));
101        executionContext.Scope.SubScopes.Remove(remaining);
102        executionContext.Scope.SubScopes.Remove(selected);
103
104        var op = executionContext.CreateChildOperation(selector, executionContext.Scope);// select the rest of the population
105        ExecuteOperation(executionContext, innerToken, op);
106
107        remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
108        selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
109
110        for (int i = 0; i < selector.NumberOfSelectedSubScopesParameter.Value.Value; i += 2) {
111          // crossover
112          IScope childScope = null;
113          if (rand.NextDouble() < crossoverProbability) {
114            childScope = new Scope($"{i}+{i + 1}") { Parent = executionContext.Scope };
115            childScope.SubScopes.Add(selected.SubScopes[i]);
116            childScope.SubScopes.Add(selected.SubScopes[i + 1]);
117            var op1 = executionContext.CreateChildOperation(crossover, childScope);
118            ExecuteOperation(executionContext, innerToken, op1);
119            childScope.SubScopes.Clear();
120          }
121
122          childScope = childScope ?? selected.SubScopes[i];
123          // mutation
124          if (rand.NextDouble() < mutationProbability) {
125            var op2 = executionContext.CreateChildOperation(mutator, childScope);
126            ExecuteOperation(executionContext, innerToken, op2);
127          }
128
129          // evaluation
130          if (childScope != null) {
131            var op3 = executionContext.CreateChildOperation(evaluator, childScope);
132            ExecuteOperation(executionContext, innerToken, op3);
133            var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
134            var childSolution = new EMMSolution(childScope);
135            // set child qualities
136            childSolution.Qualities = qualities;
137            ++evaluatedSolutions;
138            population.Add(new EMMSolution(childScope));
139          } else {// no crossover or mutation were applied, a child was not produced, do nothing
140            population.Add(new EMMSolution(selected.SubScopes[i]));
141          }
142
143          if (evaluatedSolutions >= maximumEvaluatedSolutions) {
144            break;
145          }
146
147        }
148        globalScope.SubScopes.Replace(population.Select(x => (IScope)x.Individual));
149        // run analyzer
150        var analyze = executionContext.CreateChildOperation(analyzer, globalScope);
151        ExecuteOperation(executionContext, innerToken, analyze);
152        Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(evaluatedSolutions));
153      }
154    }
155    protected void InitializeAlgorithm(CancellationToken cancellationToken) {
156      globalScope = new Scope("Global Scope");
157      executionContext = new ExecutionContext(null, this, globalScope);
158
159      // set the execution context for parameters to allow lookup
160      foreach (var parameter in Problem.Parameters.OfType<IValueParameter>()) {  //
161                                                                                 // we need all of these in order for the wiring of the operators to work
162        globalScope.Variables.Add(new Core.Variable(parameter.Name, parameter.Value));
163      }
164      globalScope.Variables.Add(new Core.Variable("Results", Results)); // make results available as a parameter for analyzers etc.
165
166      var rand = RandomParameter.Value;
167      if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
168      rand.Reset(Seed);
169
170      var populationSize = PopulationSize.Value;
171
172      InitializePopulation(executionContext, cancellationToken, rand);
173
174      // initialize data structures for map clustering
175      var models = new ItemList<ISymbolicExpressionTree>(Map.ModelSet);
176      var map = new ItemList<ItemList<IntValue>>();
177      foreach (var list in Map.Map) {
178        map.Add(new ItemList<IntValue>(list.Select(x => new IntValue(x))));
179      }
180      var clusterNumber = new ItemList<IntValue>(Map.ClusterNumber.Select(x => new IntValue(x)));
181      globalScope.Variables.Add(new Core.Variable("Models", models));
182      globalScope.Variables.Add(new Core.Variable("Map", map));
183      globalScope.Variables.Add(new Core.Variable("ClusterNumber", clusterNumber));
184
185      evaluatedSolutions = populationSize;
186      base.Initialize(cancellationToken);
187    }
188    private void InitializePopulation(ExecutionContext executionContext, CancellationToken cancellationToken, IRandom random) {
189      var creator = Problem.SolutionCreator;
190      var evaluator = Problem.Evaluator;
191      var populationSize = PopulationSize.Value;
192      population = new List<IEMMSolution>(populationSize);
193
194      var parentScope = executionContext.Scope; //main scope for the next step work
195      // first, create all individuals
196      for (int i = 0; i < populationSize; ++i) {
197        var childScope = new Scope(i.ToString()) { Parent = parentScope };
198        ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(creator, childScope));
199        var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
200        var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
201        foreach (var node in tree.IterateNodesPostfix().OfType<TreeModelTreeNode>()) {
202          node.Tree = Map.NewModelForInizializtion(random, out int cluster, out int treeNumber);
203          node.Tree.Root.ShakeLocalParameters(random, 0.5);
204          node.ClusterNumer = cluster;
205          node.TreeNumber = treeNumber;
206        }
207        parentScope.SubScopes.Add(childScope);
208      }
209
210      // then, evaluate them and update qualities
211      for (int i = 0; i < populationSize; ++i) {
212        var childScope = parentScope.SubScopes[i];
213        ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
214
215        var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
216        var solution = new EMMSolution(childScope);  // Create solution and push individual inside
217
218        solution.Qualities = qualities;
219        population.Add(solution);  // push solution to population
220      }
221    }
222  }
223
224}
225
Note: See TracBrowser for help on using the repository browser.