Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7771 was 7756, checked in by jkarder, 13 years ago

#1331:

  • added path relinking and problem specific operators (KnapsackPathRelinker, TravelingSalesmanPathRelinker) for it
  • adjusted event handling
  • minor code improvements
File size: 19.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 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      CrossoverParameter.ValidValues.Add(new TravelingSalesman.TravelingSalesmanPathRelinker());
309      CrossoverParameter.ValidValues.Add(new Knapsack.KnapsackPathRelinker());
310
311      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
312        CrossoverParameter.ValidValues.Add(crossover);
313
314      foreach (var crossover in CrossoverParameter.ValidValues.OfType<Knapsack.INBinaryVectorCrossover>())
315        crossover.ParentsParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
316
317      if (oldCrossover != null) {
318        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
319        if (crossover != null) CrossoverParameter.Value = crossover;
320        else oldCrossover = null;
321      }
322      if (oldCrossover == null && defaultCrossover != null)
323        CrossoverParameter.Value = defaultCrossover;
324    }
325    private void UpdateDiversityCalculators() {
326      DiversityCalculator oldDiversityCalculator = DiversityCalculatorParameter.Value;
327      DiversityCalculatorParameter.ValidValues.Clear();
328      DiversityCalculator defaultDiversityCalculator = Problem.Operators.OfType<DiversityCalculator>().FirstOrDefault();
329
330      DiversityCalculatorParameter.ValidValues.Add(new Knapsack.BinaryVectorDiversityCalculator());
331      DiversityCalculatorParameter.ValidValues.Add(new TravelingSalesman.PermutationDiversityCalculator());
332
333      foreach (DiversityCalculator diversityCalculator in Problem.Operators.OfType<DiversityCalculator>().OrderBy(x => x.Name))
334        DiversityCalculatorParameter.ValidValues.Add(diversityCalculator);
335
336      if (oldDiversityCalculator != null) {
337        DiversityCalculator diversityCalculator = DiversityCalculatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldDiversityCalculator.GetType());
338        if (diversityCalculator != null) DiversityCalculatorParameter.Value = diversityCalculator;
339        else oldDiversityCalculator = null;
340      }
341      if (oldDiversityCalculator == null && defaultDiversityCalculator != null)
342        DiversityCalculatorParameter.Value = defaultDiversityCalculator;
343    }
344    private void UpdateImprovers() {
345      ILocalImprovementOperator oldImprover = ImproverParameter.Value;
346      ImproverParameter.ValidValues.Clear();
347      ILocalImprovementOperator defaultImprover = Problem.Operators.OfType<ILocalImprovementOperator>().FirstOrDefault();
348
349      ImproverParameter.ValidValues.Add(new Knapsack.KnapsackImprovementOperator());
350      ImproverParameter.ValidValues.Add(new TravelingSalesman.TravelingSalesmanImprovementOperator());
351
352      foreach (ILocalImprovementOperator improver in Problem.Operators.OfType<ILocalImprovementOperator>().OrderBy(x => x.Name))
353        ImproverParameter.ValidValues.Add(improver);
354
355      foreach (var improver in ImproverParameter.ValidValues.OfType<IScatterSearchTargetProcessor>())
356        improver.TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
357
358      if (oldImprover != null) {
359        ILocalImprovementOperator improver = ImproverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldImprover.GetType());
360        if (improver != null) ImproverParameter.Value = improver;
361        else oldImprover = null;
362      }
363      if (oldImprover == null && defaultImprover != null)
364        ImproverParameter.Value = defaultImprover;
365    }
366    private void ParameterizeSolutionsCreator() {
367      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
368      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
369    }
370    private void ParameterizeMainLoop() {
371      if (Problem != null) {
372        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
373        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
374        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
375      }
376    }
377    private void ParameterizeStochasticOperator(IOperator op) {
378      if (op is IStochasticOperator) {
379        IStochasticOperator stOp = (IStochasticOperator)op;
380        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
381        stOp.RandomParameter.Hidden = true;
382      }
383    }
384    //private void ParameterizeScatterSearchTargetProcessor(IOperator op) {
385    //  if (op is IScatterSearchTargetProcessor) {
386    //    IScatterSearchTargetProcessor ssOp = (IScatterSearchTargetProcessor)op;
387    //    ssOp.TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
388    //    ssOp.TargetParameter.Hidden = true;
389    //  }
390    //}
391    private void ParameterizeAnalyzers() {
392      qualityAnalyzer.ResultsParameter.ActualName = "Results";
393      qualityAnalyzer.ResultsParameter.Hidden = true;
394      if (Problem != null) {
395        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
396        qualityAnalyzer.MaximizationParameter.Hidden = true;
397        qualityAnalyzer.QualityParameter.Hidden = false;
398        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
399        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
400      } else {
401        qualityAnalyzer.MaximizationParameter.Hidden = false;
402        qualityAnalyzer.BestKnownQualityParameter.Hidden = false;
403      }
404    }
405    private ScatterSearchMainLoop FindMainLoop(IOperator start) {
406      IOperator mainLoop = start;
407      while (mainLoop != null && !(mainLoop is ScatterSearchMainLoop))
408        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
409      if (mainLoop == null) return null;
410      else return (ScatterSearchMainLoop)mainLoop;
411    }
412    #endregion
413  }
414}
Note: See TracBrowser for help on using the repository browser.