source: branches/ScatterSearch (trunk integration)/HeuristicLab.Algorithms.ScatterSearch/3.3/ScatterSearch.cs @ 7954

Last change on this file since 7954 was 7954, checked in by jkarder, 8 years ago

#1331:

  • added EvaluatedSolutions parameter
  • SingleObjectiveTestFunctionImprovementOperator now retrieves the bounds from the scope tree
  • SingleObjectiveTestFunctionProblem now assigns the bounds to the similarity calculator
File size: 20.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 System.Reflection;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Random;
35using HeuristicLab.Selection;
36
37namespace HeuristicLab.Algorithms.ScatterSearch {
38  /// <summary>
39  /// A scatter search algorithm.
40  /// </summary>
41  [Item("Scatter Search", "A scatter search algorithm.")]
42  [Creatable("Algorithms")]
43  [StorableClass]
44  public sealed class ScatterSearch : HeuristicOptimizationEngineAlgorithm, IStorableContent {
45    public string Filename { get; set; }
46
47    #region Problem Properties
48    public override Type ProblemType {
49      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
50    }
51    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
52      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
53      set { base.Problem = value; }
54    }
55    #endregion
56
57    #region Parameter Properties
58    public IValueParameter<MultiAnalyzer> AnalyzerParameter {
59      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
60    }
61    public ConstrainedValueParameter<ICrossover> CrossoverParameter {
62      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
63    }
64    public IValueParameter<BoolValue> ExecutePathRelinkingParameter {
65      get { return (IValueLookupParameter<BoolValue>)Parameters["ExecutePathRelinking"]; }
66    }
67    public ConstrainedValueParameter<IImprovementOperator> ImproverParameter {
68      get { return (ConstrainedValueParameter<IImprovementOperator>)Parameters["Improver"]; }
69    }
70    public IValueParameter<IntValue> MaximumIterationsParameter {
71      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
72    }
73    public IValueParameter<IntValue> NumberOfHighQualitySolutionsParameter {
74      get { return (IValueParameter<IntValue>)Parameters["NumberOfHighQualitySolutions"]; }
75    }
76    public ConstrainedValueParameter<IPathRelinker> PathRelinkerParameter {
77      get { return (ConstrainedValueParameter<IPathRelinker>)Parameters["PathRelinker"]; }
78    }
79    public IValueParameter<IntValue> PopulationSizeParameter {
80      get { return (IValueParameter<IntValue>)Parameters["PopulationSize"]; }
81    }
82    public IValueParameter<IntValue> ReferenceSetSizeParameter {
83      get { return (IValueParameter<IntValue>)Parameters["ReferenceSetSize"]; }
84    }
85    public IValueParameter<IntValue> SeedParameter {
86      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
87    }
88    public IValueParameter<BoolValue> SetSeedRandomlyParameter {
89      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
90    }
91    public ConstrainedValueParameter<ISimilarityCalculator> SimilarityCalculatorParameter {
92      get { return (ConstrainedValueParameter<ISimilarityCalculator>)Parameters["SimilarityCalculator"]; }
93    }
94    #endregion
95
96    #region Properties
97    private MultiAnalyzer Analyzer {
98      get { return AnalyzerParameter.Value; }
99      set { AnalyzerParameter.Value = value; }
100    }
101    private ICrossover Crossover {
102      get { return CrossoverParameter.Value; }
103      set { CrossoverParameter.Value = value; }
104    }
105    private BoolValue ExecutePathRelinking {
106      get { return ExecutePathRelinkingParameter.Value; }
107      set { ExecutePathRelinkingParameter.Value = value; }
108    }
109    private IImprovementOperator Improver {
110      get { return ImproverParameter.Value; }
111      set { ImproverParameter.Value = value; }
112    }
113    private IntValue MaximumIterations {
114      get { return MaximumIterationsParameter.Value; }
115      set { MaximumIterationsParameter.Value = value; }
116    }
117    private IntValue NumberOfHighQualitySolutions {
118      get { return NumberOfHighQualitySolutionsParameter.Value; }
119      set { NumberOfHighQualitySolutionsParameter.Value = value; }
120    }
121    private IPathRelinker PathRelinker {
122      get { return PathRelinkerParameter.Value; }
123      set { PathRelinkerParameter.Value = value; }
124    }
125    private IntValue PopulationSize {
126      get { return PopulationSizeParameter.Value; }
127      set { PopulationSizeParameter.Value = value; }
128    }
129    private IntValue ReferenceSetSize {
130      get { return ReferenceSetSizeParameter.Value; }
131      set { ReferenceSetSizeParameter.Value = value; }
132    }
133    private IntValue Seed {
134      get { return SeedParameter.Value; }
135      set { SeedParameter.Value = value; }
136    }
137    private BoolValue SetSeedRandomly {
138      get { return SetSeedRandomlyParameter.Value; }
139      set { SetSeedRandomlyParameter.Value = value; }
140    }
141    private ISimilarityCalculator SimilarityCalculator {
142      get { return SimilarityCalculatorParameter.Value; }
143      set { SimilarityCalculatorParameter.Value = value; }
144    }
145    private RandomCreator RandomCreator {
146      get { return (RandomCreator)OperatorGraph.InitialOperator; }
147    }
148    private SolutionsCreator SolutionsCreator {
149      get { return (SolutionsCreator)RandomCreator.Successor; }
150    }
151    private ScatterSearchMainLoop MainLoop {
152      get { return FindMainLoop(SolutionsCreator.Successor); }
153    }
154
155    [Storable]
156    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
157    #endregion
158
159    [StorableConstructor]
160    private ScatterSearch(bool deserializing) : base(deserializing) { }
161    [StorableHook(HookType.AfterDeserialization)]
162    private void AfterDeserialization() {
163      Initialize();
164    }
165    private ScatterSearch(ScatterSearch original, Cloner cloner)
166      : base(original, cloner) {
167      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
168      Initialize();
169    }
170    public override IDeepCloneable Clone(Cloner cloner) {
171      return new ScatterSearch(this, cloner);
172    }
173    public ScatterSearch()
174      : base() {
175      #region Create parameters
176      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", new MultiAnalyzer()));
177      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover"));
178      Parameters.Add(new ValueParameter<BoolValue>("ExecutePathRelinking", new BoolValue(true)));
179      Parameters.Add(new ConstrainedValueParameter<IImprovementOperator>("Improver"));
180      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", new IntValue(100)));
181      Parameters.Add(new ValueParameter<IntValue>("NumberOfHighQualitySolutions", new IntValue(10)));
182      Parameters.Add(new ConstrainedValueParameter<IPathRelinker>("PathRelinker"));
183      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", new IntValue(300)));
184      Parameters.Add(new ValueParameter<IntValue>("ReferenceSetSize", new IntValue(100)));
185      Parameters.Add(new ValueParameter<IntValue>("Seed", new IntValue(0)));
186      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", new BoolValue(true)));
187      Parameters.Add(new ConstrainedValueParameter<ISimilarityCalculator>("SimilarityCalculator"));
188      #endregion
189
190      #region Create operators
191      RandomCreator randomCreator = new RandomCreator();
192      SolutionsCreator solutionsCreator = new SolutionsCreator();
193      UniformSubScopesProcessor uniformSubScopesProcessor = new UniformSubScopesProcessor();
194      Placeholder solutionEvaluator = new Placeholder();
195      Placeholder solutionImprover = new Placeholder();
196      SubScopesCounter subScopesCounter = new SubScopesCounter();
197      ResultsCollector resultsCollector = new ResultsCollector();
198      BestSelector bestSelector = new BestSelector();
199      ScatterSearchMainLoop mainLoop = new ScatterSearchMainLoop();
200      #endregion
201
202      #region Create operator graph
203      OperatorGraph.InitialOperator = randomCreator;
204      randomCreator.RandomParameter.ActualName = "Random";
205      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
206      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
207      randomCreator.Successor = solutionsCreator;
208
209      solutionsCreator.Name = "DiversificationGenerationMethod";
210      solutionsCreator.NumberOfSolutionsParameter.ActualName = "PopulationSize";
211      solutionsCreator.Successor = uniformSubScopesProcessor;
212
213      uniformSubScopesProcessor.Operator = solutionImprover;
214      uniformSubScopesProcessor.Successor = subScopesCounter;
215
216      solutionImprover.Name = "SolutionImprover";
217      solutionImprover.OperatorParameter.ActualName = "Improver";
218      solutionImprover.Successor = solutionEvaluator;
219
220      solutionEvaluator.Name = "SolutionEvaluator";
221      solutionEvaluator.OperatorParameter.ActualName = "Evaluator";
222      solutionEvaluator.Successor = null;
223
224      subScopesCounter.Name = "Initialize EvaluatedSolutions";
225      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
226      subScopesCounter.Successor = resultsCollector;
227
228      resultsCollector.Name = "ResultsCollector";
229      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("EvaluatedSolutions", null, "EvaluatedSolutions"));
230      resultsCollector.Successor = bestSelector;
231
232      bestSelector.NumberOfSelectedSubScopesParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
233      bestSelector.CopySelected = new BoolValue(false);
234      bestSelector.Successor = mainLoop;
235
236      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
237      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
238      mainLoop.ResultsParameter.ActualName = "Results";
239      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
240      mainLoop.IterationsParameter.ActualName = "Iterations";
241      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
242      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
243      mainLoop.NumberOfHighQualitySolutionsParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
244      mainLoop.Successor = null;
245      #endregion
246
247      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
248      ParameterizeAnalyzers();
249      UpdateAnalyzers();
250
251      Initialize();
252    }
253
254    public override void Prepare() {
255      if (Problem != null && Improver != null && PathRelinker != null && SimilarityCalculator != null)
256        base.Prepare();
257    }
258
259    #region Events
260    protected override void OnProblemChanged() {
261      ParameterizeStochasticOperator(Problem.SolutionCreator);
262      ParameterizeStochasticOperator(Problem.Evaluator);
263      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
264      ParameterizeAnalyzers();
265      ParameterizeSolutionsCreator();
266      ParameterizeBestSelector();
267      UpdateAnalyzers();
268      UpdateCrossovers();
269      UpdatePathRelinkers();
270      UpdateSimilarityCalculators();
271      UpdateImprovers();
272      ParameterizeMainLoop();
273      UpdateSimilarityCalculators();
274      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
275      base.OnProblemChanged();
276    }
277    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
278      ParameterizeStochasticOperator(Problem.SolutionCreator);
279      ParameterizeSolutionsCreator();
280      base.Problem_SolutionCreatorChanged(sender, e);
281    }
282    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
283      ParameterizeStochasticOperator(Problem.Evaluator);
284      ParameterizeSolutionsCreator();
285      ParameterizeMainLoop();
286      ParameterizeAnalyzers();
287      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
288      base.Problem_EvaluatorChanged(sender, e);
289    }
290    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
291      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
292      UpdateAnalyzers();
293      UpdateCrossovers();
294      UpdatePathRelinkers();
295      UpdateSimilarityCalculators();
296      UpdateImprovers();
297      ParameterizeMainLoop();
298      ParameterizeAnalyzers();
299      base.Problem_OperatorsChanged(sender, e);
300    }
301    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
302      ParameterizeMainLoop();
303      ParameterizeAnalyzers();
304      ParameterizeBestSelector();
305    }
306    #endregion
307
308    #region Helpers
309    private void Initialize() {
310      if (Problem != null) {
311        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
312      }
313    }
314    private void UpdateAnalyzers() {
315      Analyzer.Operators.Clear();
316      if (Problem != null) {
317        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
318          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
319            param.Depth = 1;
320          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
321        }
322      }
323      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
324    }
325    private void UpdateCrossovers() {
326      ICrossover oldCrossover = CrossoverParameter.Value;
327      CrossoverParameter.ValidValues.Clear();
328      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
329
330      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
331        CrossoverParameter.ValidValues.Add(crossover);
332
333      if (oldCrossover != null) {
334        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
335        if (crossover != null) CrossoverParameter.Value = crossover;
336        else oldCrossover = null;
337      }
338      if (oldCrossover == null && defaultCrossover != null)
339        CrossoverParameter.Value = defaultCrossover;
340    }
341    private void UpdateImprovers() {
342      IImprovementOperator oldImprover = ImproverParameter.Value;
343      ImproverParameter.ValidValues.Clear();
344      IImprovementOperator defaultImprover = Problem.Operators.OfType<IImprovementOperator>().FirstOrDefault();
345
346      foreach (IImprovementOperator improver in Problem.Operators.OfType<IImprovementOperator>().OrderBy(x => x.Name))
347        ImproverParameter.ValidValues.Add(improver);
348
349      if (oldImprover != null) {
350        IImprovementOperator improver = ImproverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldImprover.GetType());
351        if (improver != null) ImproverParameter.Value = improver;
352        else oldImprover = null;
353      }
354      if (oldImprover == null && defaultImprover != null)
355        ImproverParameter.Value = defaultImprover;
356    }
357    private void UpdatePathRelinkers() {
358      IPathRelinker oldPathRelinker = PathRelinkerParameter.Value;
359      PathRelinkerParameter.ValidValues.Clear();
360      IPathRelinker defaultPathRelinker = Problem.Operators.OfType<IPathRelinker>().FirstOrDefault();
361
362      foreach (IPathRelinker pathRelinker in Problem.Operators.OfType<IPathRelinker>().OrderBy(x => x.Name))
363        PathRelinkerParameter.ValidValues.Add(pathRelinker);
364
365      if (oldPathRelinker != null) {
366        IPathRelinker pathRelinker = PathRelinkerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldPathRelinker.GetType());
367        if (pathRelinker != null) PathRelinkerParameter.Value = pathRelinker;
368        else oldPathRelinker = null;
369      }
370      if (oldPathRelinker == null && defaultPathRelinker != null)
371        PathRelinkerParameter.Value = defaultPathRelinker;
372    }
373    private void UpdateSimilarityCalculators() {
374      ISimilarityCalculator oldDiversityCalculator = SimilarityCalculatorParameter.Value;
375      SimilarityCalculatorParameter.ValidValues.Clear();
376      ISimilarityCalculator defaultDiversityCalculator = Problem.Operators.OfType<ISimilarityCalculator>().FirstOrDefault();
377
378      foreach (ISimilarityCalculator diversityCalculator in Problem.Operators.OfType<ISimilarityCalculator>().OrderBy(x => x.Name))
379        SimilarityCalculatorParameter.ValidValues.Add(diversityCalculator);
380
381      if (oldDiversityCalculator != null) {
382        ISimilarityCalculator diversityCalculator = SimilarityCalculatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldDiversityCalculator.GetType());
383        if (diversityCalculator != null) SimilarityCalculatorParameter.Value = diversityCalculator;
384        else oldDiversityCalculator = null;
385      }
386      if (oldDiversityCalculator == null && defaultDiversityCalculator != null)
387        SimilarityCalculatorParameter.Value = defaultDiversityCalculator;
388    }
389    private void ParameterizeBestSelector() {
390      OperatorGraph.Operators.OfType<ISingleObjectiveSelector>()
391                             .First().QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
392    }
393    private void ParameterizeSolutionsCreator() {
394      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
395      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
396    }
397    private void ParameterizeMainLoop() {
398      if (Problem != null && Improver != null) {
399        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
400        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
401        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
402        MainLoop.TargetParameter.ActualName = Improver.TargetParameter.ActualName;
403        foreach (var item in MainLoop.OperatorGraph.Operators.OfType<IScatterSearchOperator>()) {
404          // parameter should be accessed direclty (using an interface definition)
405          PropertyInfo propInfo = item.GetType().GetProperty(MainLoop.TargetParameter.Name + "Parameter");
406          if (propInfo != null && propInfo.CanRead)
407            (propInfo.GetValue(item, null) as IValueLookupParameter<IItem>).ActualName = MainLoop.TargetParameter.ActualName;
408          propInfo = item.GetType().GetProperty(MainLoop.QualityParameter.Name + "Parameter");
409          if (propInfo != null && propInfo.CanRead)
410            (propInfo.GetValue(item, null) as IValueLookupParameter<IItem>).ActualName = MainLoop.QualityParameter.ActualName;
411        }
412      }
413    }
414    private void ParameterizeStochasticOperator(IOperator op) {
415      if (op is IStochasticOperator) {
416        IStochasticOperator stOp = (IStochasticOperator)op;
417        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
418        stOp.RandomParameter.Hidden = true;
419      }
420    }
421    private void ParameterizeAnalyzers() {
422      qualityAnalyzer.ResultsParameter.ActualName = "Results";
423      qualityAnalyzer.ResultsParameter.Hidden = true;
424      if (Problem != null) {
425        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
426        qualityAnalyzer.MaximizationParameter.Hidden = true;
427        qualityAnalyzer.QualityParameter.Hidden = false;
428        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
429        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
430      } else {
431        qualityAnalyzer.MaximizationParameter.Hidden = false;
432        qualityAnalyzer.BestKnownQualityParameter.Hidden = false;
433      }
434    }
435    private ScatterSearchMainLoop FindMainLoop(IOperator start) {
436      IOperator mainLoop = start;
437      while (mainLoop != null && !(mainLoop is ScatterSearchMainLoop))
438        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
439      return mainLoop as ScatterSearchMainLoop;
440    }
441    #endregion
442  }
443}
Note: See TracBrowser for help on using the repository browser.