Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Analysis.FitnessLandscape/3.3/Algorithms/LocalAnalysis.cs @ 17514

Last change on this file since 17514 was 16728, checked in by abeham, 6 years ago

#1614: updated to new persistence and .NET 4.6.1

File size: 13.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
24using HEAL.Attic;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Random;
33
34namespace HeuristicLab.Analysis.FitnessLandscape {
35  [Item("Local Analysis", "A local analysis algorithm.")]
36  [StorableType("F76A2278-93BC-4F35-A603-9E1E84C9651A")]
37  public abstract class LocalAnalysis<T> : HeuristicOptimizationEngineAlgorithm, IStorableContent where T : class, IOperator, new() {
38    public string Filename { get; set; }
39
40    #region Problem Properties
41    public override Type ProblemType {
42      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
43    }
44    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
45      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
46      set { base.Problem = value; }
47    }
48    #endregion
49
50    #region Parameter Properties
51    public IFixedValueParameter<IntValue> SeedParameter {
52      get { return (IFixedValueParameter<IntValue>)Parameters["Seed"]; }
53    }
54    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
55      get { return (IFixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
56    }
57    public IConstrainedValueParameter<IManipulator> MutatorParameter {
58      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
59    }
60    public IFixedValueParameter<IntValue> MaximumIterationsParameter {
61      get { return (IFixedValueParameter<IntValue>)Parameters["MaximumIterations"]; }
62    }
63    public IFixedValueParameter<IntValue> RepetitionsParameter {
64      get { return (IFixedValueParameter<IntValue>)Parameters["Repetitions"]; }
65    }
66    public IValueParameter<MultiAnalyzer> AnalyzerParameter {
67      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
68    }
69    public IFixedValueParameter<T> SelectorParameter {
70      get { return (IFixedValueParameter<T>)Parameters["Selector"]; }
71    }
72    #endregion
73
74    #region Properties
75    protected RandomCreator GlobalRandomCreator {
76      get { return (RandomCreator)OperatorGraph.InitialOperator; }
77    }
78    protected UniformSubScopesProcessor FirstUniformSubScopesProcessor {
79      get { return (UniformSubScopesProcessor)((SubScopesCreator)GlobalRandomCreator.Successor).Successor; }
80    }
81    protected LocalRandomCreator IteratedRandomCreator {
82      get { return (LocalRandomCreator)FirstUniformSubScopesProcessor.Operator; }
83    }
84    protected VariableCreator VariableCreator {
85      get { return (VariableCreator)IteratedRandomCreator.Successor; }
86    }
87    protected UniformSubScopesProcessor SecondUniformSubScopesProcessor {
88      get { return (UniformSubScopesProcessor)FirstUniformSubScopesProcessor.Successor; }
89    }
90    protected SolutionsCreator SolutionsCreator {
91      get { return (SolutionsCreator)SecondUniformSubScopesProcessor.Operator; }
92    }
93    protected LocalAnalysisMainLoop MainLoop {
94      get { return (LocalAnalysisMainLoop)SolutionsCreator.Successor; }
95    }
96
97    [Storable]
98    private QualityTrailMultiAnalyzer qualityTrailAnalyzer;
99    #endregion
100
101    [StorableConstructor]
102    protected LocalAnalysis(StorableConstructorFlag _) : base(_) { }
103    protected LocalAnalysis(LocalAnalysis<T> original, Cloner cloner)
104      : base(original, cloner) {
105      qualityTrailAnalyzer = cloner.Clone(original.qualityTrailAnalyzer);
106      RegisterEventHandlers();
107    }
108    protected LocalAnalysis(T selector)
109      : base() {
110      Parameters.Add(new FixedValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
111      Parameters.Add(new FixedValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
112      Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "Mutation operator."));
113      Parameters.Add(new FixedValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(100)));
114      Parameters.Add(new FixedValueParameter<IntValue>("Repetitions", "The number of repetitions that should be performed.", new IntValue(10)));
115      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
116      Parameters.Add(new FixedValueParameter<T>("Selector", "Selection operator.", selector));
117
118      RandomCreator randomCreator = new RandomCreator();
119      SubScopesCreator ssc = new SubScopesCreator();
120      UniformSubScopesProcessor ussp1 = new UniformSubScopesProcessor();
121      UniformSubScopesProcessor ussp2 = new UniformSubScopesProcessor();
122      LocalRandomCreator lrc = new LocalRandomCreator();
123      VariableCreator variableCreator = new VariableCreator();
124      SolutionsCreator solutionsCreator = new SolutionsCreator();
125      LocalAnalysisMainLoop laMainLoop = new LocalAnalysisMainLoop();
126      ResultsCollector collector = new ResultsCollector();
127
128      OperatorGraph.InitialOperator = randomCreator;
129
130      randomCreator.RandomParameter.ActualName = "Random";
131      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
132      randomCreator.SeedParameter.Value = null;
133      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
134      randomCreator.SetSeedRandomlyParameter.Value = null;
135      randomCreator.Successor = ssc;
136
137      ssc.NumberOfSubScopesParameter.Value = null;
138      ssc.NumberOfSubScopesParameter.ActualName = RepetitionsParameter.Name;
139      ssc.Successor = ussp1;
140
141      ussp1.Depth = new IntValue(1);
142      ussp1.Parallel = new BoolValue(false);
143      ussp1.Operator = lrc;
144      ussp1.Successor = ussp2;
145
146      lrc.GlobalRandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
147      lrc.LocalRandomParameter.ActualName = "IteratedRandom";
148      lrc.Successor = variableCreator;
149
150      var iterResults = new ValueParameter<ResultCollection>("IteratedResults", new ResultCollection());
151      variableCreator.CollectedValues.Add(iterResults);
152      variableCreator.Successor = null;
153
154      ussp2.Depth = new IntValue(1);
155      ussp2.Parallel = new BoolValue(true);
156      ussp2.Operator = solutionsCreator;
157      ussp2.Successor = collector;
158
159      solutionsCreator.NumberOfSolutions = new IntValue(1);
160      solutionsCreator.Successor = laMainLoop;
161
162      laMainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
163      laMainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
164      laMainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
165      laMainLoop.RandomParameter.ActualName = lrc.LocalRandomParameter.ActualName;
166      laMainLoop.ResultsParameter.ActualName = iterResults.Name;
167      laMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
168
169      qualityTrailAnalyzer = new QualityTrailMultiAnalyzer();
170      qualityTrailAnalyzer.UpdateIntervalParameter.Value = null;
171      qualityTrailAnalyzer.UpdateIntervalParameter.ActualName = MaximumIterationsParameter.Name;
172      AnalyzerParameter.Value.Operators.Add(qualityTrailAnalyzer, true);
173
174      collector.CollectedValues.Add(new ScopeTreeLookupParameter<ResultCollection>("IteratedResults", 1));
175      collector.ResultsParameter.ActualName = "Results";
176      collector.CopyValue = new BoolValue(false);
177      collector.Successor = null;
178
179      RegisterEventHandlers();
180    }
181
182    public override void Prepare() {
183      if (Problem != null) base.Prepare();
184    }
185
186    protected override void OnStopped() {
187      var iteratedResults = Results.SingleOrDefault(x => x.Name == "IteratedResults");
188      if (iteratedResults != null) {
189        var rc = iteratedResults.Value as ItemArray<ResultCollection>;
190        if (rc != null) {
191          var results = rc.FirstOrDefault();
192          if (results != null) {
193            var toAvg = results.Select(x => x.Name).ToDictionary(x => x, x => 0.0);
194            foreach (var r in rc) {
195              foreach (var v in r) {
196                if (!toAvg.ContainsKey(v.Name)) continue;
197                var value = v.Value as IntValue;
198                if (value != null) toAvg[v.Name] += value.Value;
199                else {
200                  var doubleValue = v.Value as DoubleValue;
201                  if (doubleValue != null) toAvg[v.Name] += doubleValue.Value;
202                }
203              }
204            }
205
206            foreach (var r in toAvg.Keys.OrderBy(x => x)) {
207              Results.Add(new Result(r, new DoubleValue(toAvg[r] / RepetitionsParameter.Value.Value)));
208            }
209          }
210        }
211      }
212      base.OnStopped();
213    }
214
215    #region Events
216    protected override void OnProblemChanged() {
217      base.OnProblemChanged();
218      UpdateMutators();
219      Parameterize();
220      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
221    }
222    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
223      base.Problem_SolutionCreatorChanged(sender, e);
224      Parameterize();
225    }
226    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
227      base.Problem_EvaluatorChanged(sender, e);
228      Parameterize();
229      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
230    }
231    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
232      UpdateMutators();
233      Parameterize();
234      base.Problem_OperatorsChanged(sender, e);
235    }
236    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
237      Parameterize();
238    }
239    #endregion
240
241    #region Helpers
242    private void RegisterEventHandlers() {
243      if (Problem != null) {
244        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
245      }
246    }
247
248    private void UpdateMutators() {
249      var selected = MutatorParameter.Value;
250      MutatorParameter.ValidValues.Clear();
251      foreach (var m in Problem.Operators.OfType<IManipulator>()) {
252        MutatorParameter.ValidValues.Add(m);
253        if (selected != null && selected.GetType() == m.GetType()) MutatorParameter.Value = m;
254      }
255    }
256
257    protected virtual void Parameterize() {
258      if (Problem == null) return;
259
260      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
261      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
262      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
263      foreach (var sOp in Problem.Operators.OfType<IStochasticOperator>()) {
264        sOp.RandomParameter.ActualName = IteratedRandomCreator.LocalRandomParameter.ActualName;
265      }
266      foreach (var iOp in Problem.Operators.OfType<IIterationBasedOperator>()) {
267        iOp.IterationsParameter.ActualName = "Iterations";
268        iOp.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
269      }
270      var sEval = Problem.Evaluator as IStochasticOperator;
271      if (sEval != null) sEval.RandomParameter.ActualName = IteratedRandomCreator.LocalRandomParameter.ActualName;
272      var sCrea = Problem.SolutionCreator as IStochasticOperator;
273      if (sCrea != null) sCrea.RandomParameter.ActualName = IteratedRandomCreator.LocalRandomParameter.ActualName;
274      var sSel = SelectorParameter.Value as IStochasticOperator;
275      if (sSel != null) sSel.RandomParameter.ActualName = IteratedRandomCreator.LocalRandomParameter.ActualName;
276      var sel = SelectorParameter.Value as ISelector;
277      if (sel != null) {
278        sel.NumberOfSelectedSubScopesParameter.Value = new IntValue(1);
279        sel.CopySelected = new BoolValue(false);
280        var sos = sel as ISingleObjectiveSelector;
281        if (sos != null) {
282          sos.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
283          sos.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
284        }
285      }
286
287      foreach (var op in Problem.Operators.OfType<IParameterizedItem>()) {
288        var resultsParam = op.Parameters.SingleOrDefault(x => x.Name == "Results");
289        var lookupParam = resultsParam as ILookupParameter<ResultCollection>;
290        if (lookupParam == null) continue;
291        lookupParam.ActualName = "IteratedResults";
292      }
293    }
294    #endregion
295  }
296}
Note: See TracBrowser for help on using the repository browser.