source: branches/ScatterSearch/HeuristicLab.Algorithms.ScatterSearch/3.3/ScatterSearch.cs @ 7744

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

#1331:

  • added problem specific improvement operators (KnapsackImprovementOperator, TravelingSalesmanImprovementOperator)
  • added custom interface (IScatterSearchTargetProcessor) for Scatter Search specific operators that use a target parameter
  • added custom operator (OffspringProcessor) to process multiple children that were created by crossovers
  • extracted diversity calculation and added problem/encoding specific operators (BinaryVectorDiversityCalculator, PermutationDiversityCalculator) for it
  • added parameters and adjusted types
  • adjusted event handling
  • minor code improvements
File size: 19.4 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 HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Random;
34using HeuristicLab.Selection;
35
36namespace HeuristicLab.Algorithms.ScatterSearch {
37  /// <summary>
38  /// A scatter search algorithm.
39  /// </summary>
40  [Item("Scatter Search", "A scatter search algorithm.")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public sealed class ScatterSearch : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
49    }
50    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
51      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
57    public IValueParameter<MultiAnalyzer> AnalyzerParameter {
58      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
59    }
60    public ConstrainedValueParameter<ICrossover> CrossoverParameter {
61      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
62    }
63    public ConstrainedValueParameter<ILocalImprovementOperator> ImproverParameter {
64      get { return (ConstrainedValueParameter<ILocalImprovementOperator>)Parameters["Improver"]; }
65    }
66    public ConstrainedValueParameter<DiversityCalculator> DiversityCalculatorParameter {
67      get { return (ConstrainedValueParameter<DiversityCalculator>)Parameters["DiversityCalculator"]; }
68    }
69    public IValueParameter<IntValue> MaximumIterationsParameter {
70      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
71    }
72    public IValueParameter<IntValue> NumberOfHighQualitySolutionsParameter {
73      get { return (IValueParameter<IntValue>)Parameters["NumberOfHighQualitySolutions"]; }
74    }
75    public IValueParameter<IntValue> PopulationSizeParameter {
76      get { return (IValueParameter<IntValue>)Parameters["PopulationSize"]; }
77    }
78    public IValueParameter<IntValue> ReferenceSetSizeParameter {
79      get { return (IValueParameter<IntValue>)Parameters["ReferenceSetSize"]; }
80    }
81    public IValueParameter<IntValue> SeedParameter {
82      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
83    }
84    public IValueParameter<BoolValue> SetSeedRandomlyParameter {
85      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
86    }
87    #endregion
88
89    #region Properties
90    private MultiAnalyzer Analyzer {
91      get { return AnalyzerParameter.Value; }
92      set { AnalyzerParameter.Value = value; }
93    }
94    private ICrossover Crossover {
95      get { return CrossoverParameter.Value; }
96      set { CrossoverParameter.Value = value; }
97    }
98    private ILocalImprovementOperator Improver {
99      get { return ImproverParameter.Value; }
100      set { ImproverParameter.Value = value; }
101    }
102    private DiversityCalculator DiversityCalculator {
103      get { return DiversityCalculatorParameter.Value; }
104      set { DiversityCalculatorParameter.Value = value; }
105    }
106    private IntValue MaximumIterations {
107      get { return MaximumIterationsParameter.Value; }
108      set { MaximumIterationsParameter.Value = value; }
109    }
110    private IntValue NumberOfHighQualitySolutions {
111      get { return NumberOfHighQualitySolutionsParameter.Value; }
112      set { NumberOfHighQualitySolutionsParameter.Value = value; }
113    }
114    private IntValue PopulationSize {
115      get { return PopulationSizeParameter.Value; }
116      set { PopulationSizeParameter.Value = value; }
117    }
118    private IntValue ReferenceSetSize {
119      get { return ReferenceSetSizeParameter.Value; }
120      set { ReferenceSetSizeParameter.Value = value; }
121    }
122    private IntValue Seed {
123      get { return SeedParameter.Value; }
124      set { SeedParameter.Value = value; }
125    }
126    private BoolValue SetSeedRandomly {
127      get { return SetSeedRandomlyParameter.Value; }
128      set { SetSeedRandomlyParameter.Value = value; }
129    }
130    public RandomCreator RandomCreator {
131      get { return (RandomCreator)OperatorGraph.InitialOperator; }
132    }
133    public SolutionsCreator SolutionsCreator {
134      get { return (SolutionsCreator)RandomCreator.Successor; }
135    }
136    public ScatterSearchMainLoop MainLoop {
137      get { return FindMainLoop(SolutionsCreator.Successor); }
138    }
139
140    [Storable]
141    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
142    #endregion
143
144    [StorableConstructor]
145    private ScatterSearch(bool deserializing) : base(deserializing) { }
146    [StorableHook(HookType.AfterDeserialization)]
147    private void AfterDeserialization() {
148      Initialize();
149    }
150    private ScatterSearch(ScatterSearch original, Cloner cloner)
151      : base(original, cloner) {
152      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
153      Initialize();
154    }
155    public override IDeepCloneable Clone(Cloner cloner) {
156      return new ScatterSearch(this, cloner);
157    }
158    public ScatterSearch()
159      : base() {
160      #region Create parameters
161      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
162      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to combine solutions."));
163      Parameters.Add(new ConstrainedValueParameter<ILocalImprovementOperator>("Improver", "The operator used to improve solutions."));
164      Parameters.Add(new ConstrainedValueParameter<DiversityCalculator>("DiversityCalculator", "The operator used to calculate the diversity of two solutions."));
165      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(100)));
166      Parameters.Add(new ValueParameter<IntValue>("NumberOfHighQualitySolutions", "The number of high quality solutions that should be added to the reference set.", new IntValue(10)));
167      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population.", new IntValue(300)));
168      Parameters.Add(new ValueParameter<IntValue>("ReferenceSetSize", "The size of the reference set.", new IntValue(100)));
169      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
170      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
171      #endregion
172
173      #region Create operators
174      RandomCreator randomCreator = new RandomCreator();
175      SolutionsCreator solutionsCreator = new SolutionsCreator();
176      UniformSubScopesProcessor uniformSubScopesProcessor = new UniformSubScopesProcessor();
177      Placeholder solutionEvaluator = new Placeholder();
178      Placeholder solutionImprover = new Placeholder();
179      BestSelector bestSelector = new BestSelector();
180      VariableCreator variableCreator = new VariableCreator();
181      ResultsCollector resultsCollector = new ResultsCollector();
182      ScatterSearchMainLoop mainLoop = new ScatterSearchMainLoop();
183      #endregion
184
185      #region Create operator graph
186      OperatorGraph.InitialOperator = randomCreator;
187      randomCreator.RandomParameter.ActualName = "Random";
188      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
189      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
190      randomCreator.Successor = solutionsCreator;
191
192      solutionsCreator.Name = "DiversificationGenerationMethod";
193      solutionsCreator.NumberOfSolutionsParameter.ActualName = "PopulationSize";
194      solutionsCreator.Successor = uniformSubScopesProcessor;
195
196      uniformSubScopesProcessor.Operator = solutionImprover;
197      uniformSubScopesProcessor.Successor = bestSelector;
198
199      solutionImprover.Name = "SolutionImprover";
200      solutionImprover.OperatorParameter.ActualName = "Improver";
201      solutionImprover.Successor = solutionEvaluator;
202
203      solutionEvaluator.Name = "SolutionEvaluator";
204      solutionEvaluator.OperatorParameter.ActualName = "Evaluator";
205      solutionEvaluator.Successor = null;
206
207      bestSelector.NumberOfSelectedSubScopesParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
208      bestSelector.CopySelected = new BoolValue(false);
209      bestSelector.Successor = variableCreator;
210
211      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
212      variableCreator.CollectedValues.Add(new ValueParameter<BoolValue>("NewSolutions", new BoolValue(false)));
213      variableCreator.Successor = resultsCollector;
214
215      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Iterations"));
216      resultsCollector.ResultsParameter.ActualName = "Results";
217      resultsCollector.Successor = mainLoop;
218
219      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
220      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
221      mainLoop.ResultsParameter.ActualName = "Results";
222      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
223      mainLoop.IterationsParameter.ActualName = "Iterations";
224      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
225      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
226      mainLoop.NumberOfHighQualitySolutionsParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
227      mainLoop.Successor = null;
228      #endregion
229
230      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
231      ParameterizeAnalyzers();
232      UpdateAnalyzers();
233
234      Initialize();
235    }
236
237    public override void Prepare() {
238      base.Prepare();
239    }
240
241    #region Events
242    protected override void OnProblemChanged() {
243      ParameterizeStochasticOperator(Problem.SolutionCreator);
244      ParameterizeStochasticOperator(Problem.Evaluator);
245      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
246      ParameterizeAnalyzers();
247      ParameterizeMainLoop();
248      ParameterizeSolutionsCreator();
249      UpdateAnalyzers();
250      UpdateCrossovers();
251      UpdateDiversityCalculators();
252      UpdateImprovers();
253      UpdateDiversityCalculators();
254      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
255      base.OnProblemChanged();
256    }
257    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
258      ParameterizeStochasticOperator(Problem.SolutionCreator);
259      ParameterizeSolutionsCreator();
260      base.Problem_SolutionCreatorChanged(sender, e);
261    }
262    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
263      ParameterizeStochasticOperator(Problem.Evaluator);
264      ParameterizeSolutionsCreator();
265      ParameterizeMainLoop();
266      ParameterizeAnalyzers();
267      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
268      base.Problem_EvaluatorChanged(sender, e);
269    }
270    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
271      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
272      UpdateAnalyzers();
273      UpdateCrossovers();
274      UpdateDiversityCalculators();
275      UpdateImprovers();
276      ParameterizeMainLoop();
277      ParameterizeAnalyzers();
278      base.Problem_OperatorsChanged(sender, e);
279    }
280    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
281      ParameterizeMainLoop();
282      ParameterizeAnalyzers();
283    }
284    #endregion
285
286    #region Helpers
287    private void Initialize() {
288      if (Problem != null) {
289        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
290      }
291    }
292    private void UpdateAnalyzers() {
293      Analyzer.Operators.Clear();
294      if (Problem != null) {
295        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
296          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
297            param.Depth = 1;
298          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
299        }
300      }
301      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
302    }
303    private void UpdateCrossovers() {
304      ICrossover oldCrossover = CrossoverParameter.Value;
305      CrossoverParameter.ValidValues.Clear();
306      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
307
308      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
309        CrossoverParameter.ValidValues.Add(crossover);
310
311      foreach (var crossover in CrossoverParameter.ValidValues.OfType<Knapsack.INBinaryVectorCrossover>())
312        crossover.ParentsParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
313
314      if (oldCrossover != null) {
315        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
316        if (crossover != null) CrossoverParameter.Value = crossover;
317        else oldCrossover = null;
318      }
319      if (oldCrossover == null && defaultCrossover != null)
320        CrossoverParameter.Value = defaultCrossover;
321    }
322    private void UpdateDiversityCalculators() {
323      DiversityCalculator oldDiversityCalculator = DiversityCalculatorParameter.Value;
324      DiversityCalculatorParameter.ValidValues.Clear();
325      DiversityCalculator defaultDiversityCalculator = Problem.Operators.OfType<DiversityCalculator>().FirstOrDefault();
326
327      DiversityCalculatorParameter.ValidValues.Add(new Knapsack.BinaryVectorDiversityCalculator());
328      DiversityCalculatorParameter.ValidValues.Add(new TravelingSalesman.PermutationDiversityCalculator());
329
330      foreach (DiversityCalculator diversityCalculator in Problem.Operators.OfType<DiversityCalculator>().OrderBy(x => x.Name))
331        DiversityCalculatorParameter.ValidValues.Add(diversityCalculator);
332
333      if (oldDiversityCalculator != null) {
334        DiversityCalculator diversityCalculator = DiversityCalculatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldDiversityCalculator.GetType());
335        if (diversityCalculator != null) DiversityCalculatorParameter.Value = diversityCalculator;
336        else oldDiversityCalculator = null;
337      }
338      if (oldDiversityCalculator == null && defaultDiversityCalculator != null)
339        DiversityCalculatorParameter.Value = defaultDiversityCalculator;
340    }
341    private void UpdateImprovers() {
342      ILocalImprovementOperator oldImprover = ImproverParameter.Value;
343      ImproverParameter.ValidValues.Clear();
344      ILocalImprovementOperator defaultImprover = Problem.Operators.OfType<ILocalImprovementOperator>().FirstOrDefault();
345
346      ImproverParameter.ValidValues.Add(new Knapsack.KnapsackImprovementOperator());
347      ImproverParameter.ValidValues.Add(new TravelingSalesman.TravelingSalesmanImprovementOperator());
348
349      foreach (ILocalImprovementOperator improver in Problem.Operators.OfType<ILocalImprovementOperator>().OrderBy(x => x.Name))
350        ImproverParameter.ValidValues.Add(improver);
351
352      foreach (var improver in ImproverParameter.ValidValues.OfType<IScatterSearchTargetProcessor>())
353        improver.TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
354
355      if (oldImprover != null) {
356        ILocalImprovementOperator improver = ImproverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldImprover.GetType());
357        if (improver != null) ImproverParameter.Value = improver;
358        else oldImprover = null;
359      }
360      if (oldImprover == null && defaultImprover != null)
361        ImproverParameter.Value = defaultImprover;
362    }
363    private void ParameterizeSolutionsCreator() {
364      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
365      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
366    }
367    private void ParameterizeMainLoop() {
368      if (Problem != null) {
369        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
370        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
371        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
372      }
373    }
374    private void ParameterizeStochasticOperator(IOperator op) {
375      if (op is IStochasticOperator) {
376        IStochasticOperator stOp = (IStochasticOperator)op;
377        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
378        stOp.RandomParameter.Hidden = true;
379      }
380    }
381    //private void ParameterizeScatterSearchTargetProcessor(IOperator op) {
382    //  if (op is IScatterSearchTargetProcessor) {
383    //    IScatterSearchTargetProcessor ssOp = (IScatterSearchTargetProcessor)op;
384    //    ssOp.TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
385    //    ssOp.TargetParameter.Hidden = true;
386    //  }
387    //}
388    private void ParameterizeAnalyzers() {
389      qualityAnalyzer.ResultsParameter.ActualName = "Results";
390      qualityAnalyzer.ResultsParameter.Hidden = true;
391      if (Problem != null) {
392        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
393        qualityAnalyzer.MaximizationParameter.Hidden = true;
394        qualityAnalyzer.QualityParameter.Hidden = false;
395        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
396        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
397      } else {
398        qualityAnalyzer.MaximizationParameter.Hidden = false;
399        qualityAnalyzer.BestKnownQualityParameter.Hidden = false;
400      }
401    }
402    private ScatterSearchMainLoop FindMainLoop(IOperator start) {
403      IOperator mainLoop = start;
404      while (mainLoop != null && !(mainLoop is ScatterSearchMainLoop))
405        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
406      if (mainLoop == null) return null;
407      else return (ScatterSearchMainLoop)mainLoop;
408    }
409    #endregion
410  }
411}
Note: See TracBrowser for help on using the repository browser.