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 |
|
---|
22 | using HEAL.Attic;
|
---|
23 | using HeuristicLab.Common;
|
---|
24 | using HeuristicLab.Core;
|
---|
25 | using HeuristicLab.Data;
|
---|
26 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
27 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
28 | using HeuristicLab.Random;
|
---|
29 | using HeuristicLab.Selection;
|
---|
30 | using System.Collections.Generic;
|
---|
31 | using System.IO;
|
---|
32 | using System.Linq;
|
---|
33 | using CancellationToken = System.Threading.CancellationToken;
|
---|
34 | using Variable = HeuristicLab.Core.Variable;
|
---|
35 |
|
---|
36 | namespace 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 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 | // this.Problem.SymbolicExpressionTreeGrammar;
|
---|
60 | /* Problem.ProblemData.Dataset.ColumnNames.Take(2).ToList();
|
---|
61 | trees.First().Root.Grammar.ContainsSymbol((IVariable)a).
|
---|
62 | = this.Problem.SymbolicExpressionTreeGrammar;*/
|
---|
63 | int flag = 1;
|
---|
64 | switch (flag) {
|
---|
65 | case 0: // for case when we want only create map, and do not want made somting also.
|
---|
66 | Map = new EMMMapTreeModel(RandomParameter.Value, trees, ClusterNumbersParameter.Value.Value);
|
---|
67 | ClusterNumbersParameter.Value.Value = Map.K;
|
---|
68 | File.WriteAllLines("Map.txt", Map.MapToString());
|
---|
69 | File.WriteAllLines("MapToSee.txt", Map.MapToSee());
|
---|
70 | globalScope = new Scope("Global Scope");
|
---|
71 | executionContext = new ExecutionContext(null, this, globalScope);
|
---|
72 | break;
|
---|
73 | case 1: // for case when we want read existed map and work with it;
|
---|
74 | Map = new EMMMapTreeModel(RandomParameter.Value, trees);
|
---|
75 | ClusterNumbersParameter.Value.Value = Map.K;
|
---|
76 | if (previousExecutionState != ExecutionState.Paused) {
|
---|
77 | InitializeAlgorithm(cancellationToken);
|
---|
78 | }
|
---|
79 | globalScope.Variables.Add(new Variable("TreeModelMap", Map));
|
---|
80 | EMMEvolutionaryAlgorithmRun(cancellationToken);
|
---|
81 | break;
|
---|
82 |
|
---|
83 | default: //for case of usial from zero step starting
|
---|
84 | Map = new EMMMapTreeModel(RandomParameter.Value, trees, ClusterNumbersParameter.Value.Value);
|
---|
85 | ClusterNumbersParameter.Value.Value = Map.K;
|
---|
86 | if (previousExecutionState != ExecutionState.Paused) {
|
---|
87 | InitializeAlgorithm(cancellationToken);
|
---|
88 | }
|
---|
89 | globalScope.Variables.Add(new Variable("TreeModelMap", Map));
|
---|
90 | EMMEvolutionaryAlgorithmRun(cancellationToken);
|
---|
91 | break;
|
---|
92 | }
|
---|
93 |
|
---|
94 | }
|
---|
95 | private void EMMEvolutionaryAlgorithmRun(CancellationToken cancellationToken) {
|
---|
96 | var bestSelector = new BestSelector();
|
---|
97 | bestSelector.CopySelected = new BoolValue(false);
|
---|
98 | bestSelector.MaximizationParameter.ActualName = "Maximization";
|
---|
99 | bestSelector.NumberOfSelectedSubScopesParameter.ActualName = "Elites";
|
---|
100 | bestSelector.QualityParameter.ActualName = "Quality";
|
---|
101 |
|
---|
102 | var populationSize = PopulationSize.Value;
|
---|
103 | var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value;
|
---|
104 | var crossover = Crossover;
|
---|
105 | var selector = Selector;
|
---|
106 | var groupSize = GroupSize.Value;
|
---|
107 | var crossoverProbability = CrossoverProbability.Value;
|
---|
108 | var mutator = Mutator;
|
---|
109 | var mutationProbability = MutationProbability.Value;
|
---|
110 | var evaluator = Problem.Evaluator;
|
---|
111 | var analyzer = Analyzer;
|
---|
112 | var rand = RandomParameter.Value;
|
---|
113 | var elites = Elites.Value;
|
---|
114 |
|
---|
115 | // cancellation token for the inner operations which should not be immediately cancelled
|
---|
116 | var innerToken = new CancellationToken();
|
---|
117 |
|
---|
118 | while (evaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) {
|
---|
119 |
|
---|
120 | var op4 = executionContext.CreateChildOperation(bestSelector, executionContext.Scope); // select elites
|
---|
121 | ExecuteOperation(executionContext, innerToken, op4);
|
---|
122 |
|
---|
123 | var remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
|
---|
124 | executionContext.Scope.SubScopes.AddRange(remaining.SubScopes);
|
---|
125 | var selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
|
---|
126 | executionContext.Scope.SubScopes.AddRange(selected.SubScopes);
|
---|
127 | population.Clear();
|
---|
128 | population.AddRange(selected.SubScopes.Select(x => new EMMSolution(x)));
|
---|
129 | executionContext.Scope.SubScopes.Remove(remaining);
|
---|
130 | executionContext.Scope.SubScopes.Remove(selected);
|
---|
131 |
|
---|
132 | var op = executionContext.CreateChildOperation(selector, executionContext.Scope);// select the rest of the population
|
---|
133 | ExecuteOperation(executionContext, innerToken, op);
|
---|
134 |
|
---|
135 | remaining = executionContext.Scope.SubScopes.Single(x => x.Name == "Remaining");
|
---|
136 | selected = executionContext.Scope.SubScopes.Single(x => x.Name == "Selected");
|
---|
137 |
|
---|
138 | for (int i = 0; i < selector.NumberOfSelectedSubScopesParameter.Value.Value; i += 2) {
|
---|
139 | // crossover
|
---|
140 | IScope childScope = null;
|
---|
141 | if (rand.NextDouble() < crossoverProbability) {
|
---|
142 | childScope = new Scope($"{i}+{i + 1}") { Parent = executionContext.Scope };
|
---|
143 | childScope.SubScopes.Add(selected.SubScopes[i]);
|
---|
144 | childScope.SubScopes.Add(selected.SubScopes[i + 1]);
|
---|
145 | var op1 = executionContext.CreateChildOperation(crossover, childScope);
|
---|
146 | ExecuteOperation(executionContext, innerToken, op1);
|
---|
147 | childScope.SubScopes.Clear();
|
---|
148 | }
|
---|
149 |
|
---|
150 | childScope = childScope ?? selected.SubScopes[i];
|
---|
151 | // mutation
|
---|
152 | if (rand.NextDouble() < mutationProbability) {
|
---|
153 | var op2 = executionContext.CreateChildOperation(mutator, childScope);
|
---|
154 | ExecuteOperation(executionContext, innerToken, op2);
|
---|
155 | }
|
---|
156 |
|
---|
157 | // evaluation
|
---|
158 | if (childScope != null) {
|
---|
159 | var op3 = executionContext.CreateChildOperation(evaluator, childScope);
|
---|
160 | ExecuteOperation(executionContext, innerToken, op3);
|
---|
161 | var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
|
---|
162 | var childSolution = new EMMSolution(childScope);
|
---|
163 | // set child qualities
|
---|
164 | childSolution.Qualities = qualities;
|
---|
165 | ++evaluatedSolutions;
|
---|
166 | population.Add(new EMMSolution(childScope));
|
---|
167 | } else {// no crossover or mutation were applied, a child was not produced, do nothing
|
---|
168 | population.Add(new EMMSolution(selected.SubScopes[i]));
|
---|
169 | }
|
---|
170 |
|
---|
171 | if (evaluatedSolutions >= maximumEvaluatedSolutions) {
|
---|
172 | break;
|
---|
173 | }
|
---|
174 |
|
---|
175 | }
|
---|
176 | globalScope.SubScopes.Replace(population.Select(x => (IScope)x.Individual));
|
---|
177 | // run analyzer
|
---|
178 | var analyze = executionContext.CreateChildOperation(analyzer, globalScope);
|
---|
179 | ExecuteOperation(executionContext, innerToken, analyze);
|
---|
180 | Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(evaluatedSolutions));
|
---|
181 | }
|
---|
182 | }
|
---|
183 | protected void InitializeAlgorithm(CancellationToken cancellationToken) {
|
---|
184 | globalScope = new Scope("Global Scope");
|
---|
185 | executionContext = new ExecutionContext(null, this, globalScope);
|
---|
186 |
|
---|
187 | // set the execution context for parameters to allow lookup
|
---|
188 | foreach (var parameter in Problem.Parameters.OfType<IValueParameter>()) { //
|
---|
189 | // we need all of these in order for the wiring of the operators to work
|
---|
190 | globalScope.Variables.Add(new Core.Variable(parameter.Name, parameter.Value));
|
---|
191 | }
|
---|
192 | globalScope.Variables.Add(new Core.Variable("Results", Results)); // make results available as a parameter for analyzers etc.
|
---|
193 |
|
---|
194 | var rand = RandomParameter.Value;
|
---|
195 | if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
|
---|
196 | rand.Reset(Seed);
|
---|
197 |
|
---|
198 | var populationSize = PopulationSize.Value;
|
---|
199 |
|
---|
200 | InitializePopulation(executionContext, cancellationToken, rand);
|
---|
201 |
|
---|
202 | // initialize data structures for map clustering
|
---|
203 | var models = new ItemList<ISymbolicExpressionTree>(Map.ModelSet);
|
---|
204 | var map = new ItemList<ItemList<IntValue>>();
|
---|
205 | foreach (var list in Map.Map) {
|
---|
206 | map.Add(new ItemList<IntValue>(list.Select(x => new IntValue(x))));
|
---|
207 | }
|
---|
208 | var clusterNumber = new ItemList<IntValue>(Map.ClusterNumber.Select(x => new IntValue(x)));
|
---|
209 | globalScope.Variables.Add(new Core.Variable("Models", models));
|
---|
210 | globalScope.Variables.Add(new Core.Variable("Map", map));
|
---|
211 | globalScope.Variables.Add(new Core.Variable("ClusterNumber", clusterNumber));
|
---|
212 |
|
---|
213 | evaluatedSolutions = populationSize;
|
---|
214 | base.Initialize(cancellationToken);
|
---|
215 | }
|
---|
216 | private void InitializePopulation(ExecutionContext executionContext, CancellationToken cancellationToken, IRandom random) {
|
---|
217 | var creator = Problem.SolutionCreator;
|
---|
218 | var evaluator = Problem.Evaluator;
|
---|
219 | var populationSize = PopulationSize.Value;
|
---|
220 | population = new List<IEMMSolution>(populationSize);
|
---|
221 |
|
---|
222 | var parentScope = executionContext.Scope; //main scope for the next step work
|
---|
223 | // first, create all individuals
|
---|
224 | for (int i = 0; i < populationSize; ++i) {
|
---|
225 | var childScope = new Scope(i.ToString()) { Parent = parentScope };
|
---|
226 | ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(creator, childScope));
|
---|
227 | var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
|
---|
228 | var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
|
---|
229 | foreach (var node in tree.IterateNodesPostfix().OfType<TreeModelTreeNode>()) {
|
---|
230 | node.Tree = Map.NewModelForInizializtion(random, out int cluster, out int treeNumber);
|
---|
231 | node.SetLocalParameters(random, 0.5);
|
---|
232 | node.ClusterNumer = cluster;
|
---|
233 | node.TreeNumber = treeNumber;
|
---|
234 | }
|
---|
235 | parentScope.SubScopes.Add(childScope);
|
---|
236 | }
|
---|
237 |
|
---|
238 | // then, evaluate them and update qualities
|
---|
239 | for (int i = 0; i < populationSize; ++i) {
|
---|
240 | var childScope = parentScope.SubScopes[i];
|
---|
241 | ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
|
---|
242 |
|
---|
243 | var qualities = (DoubleValue)childScope.Variables["Quality"].Value;
|
---|
244 | var solution = new EMMSolution(childScope); // Create solution and push individual inside
|
---|
245 |
|
---|
246 | solution.Qualities = qualities;
|
---|
247 | population.Add(solution); // push solution to population
|
---|
248 | }
|
---|
249 | }
|
---|
250 | }
|
---|
251 |
|
---|
252 | }
|
---|
253 |
|
---|