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

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

#1331:

  • added custom crossover operator (NChildCrossover)
  • added parameters and adjusted types
  • replaced SolutionCombinationMethod with a placeholder
  • adjusted event handling
  • changed access levels
  • minor code improvements
File size: 15.8 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 IValueParameter<ILocalImprovementOperator> ImproverParameter {
64      get { return (IValueParameter<ILocalImprovementOperator>)Parameters["Improver"]; }
65    }
66    public IValueParameter<IntValue> MaximumIterationsParameter {
67      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
68    }
69    public IValueParameter<IntValue> NumberOfHighQualitySolutionsParameter {
70      get { return (IValueParameter<IntValue>)Parameters["NumberOfHighQualitySolutions"]; }
71    }
72    public IValueParameter<IntValue> PopulationSizeParameter {
73      get { return (IValueParameter<IntValue>)Parameters["PopulationSize"]; }
74    }
75    public IValueParameter<IntValue> ReferenceSetSizeParameter {
76      get { return (IValueParameter<IntValue>)Parameters["ReferenceSetSize"]; }
77    }
78    public IValueParameter<IntValue> SeedParameter {
79      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
80    }
81    public IValueParameter<BoolValue> SetSeedRandomlyParameter {
82      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
83    }
84    #endregion
85
86    #region Properties
87    private MultiAnalyzer Analyzer {
88      get { return AnalyzerParameter.Value; }
89      set { AnalyzerParameter.Value = value; }
90    }
91    private ICrossover Crossover {
92      get { return CrossoverParameter.Value; }
93      set { CrossoverParameter.Value = value; }
94    }
95    private ILocalImprovementOperator Improver {
96      get { return ImproverParameter.Value; }
97      set { ImproverParameter.Value = value; }
98    }
99    private IntValue MaximumIterations {
100      get { return MaximumIterationsParameter.Value; }
101      set { MaximumIterationsParameter.Value = value; }
102    }
103    private IntValue NumberOfHighQualitySolutions {
104      get { return NumberOfHighQualitySolutionsParameter.Value; }
105      set { NumberOfHighQualitySolutionsParameter.Value = value; }
106    }
107    private IntValue PopulationSize {
108      get { return PopulationSizeParameter.Value; }
109      set { PopulationSizeParameter.Value = value; }
110    }
111    private IntValue ReferenceSetSize {
112      get { return ReferenceSetSizeParameter.Value; }
113      set { ReferenceSetSizeParameter.Value = value; }
114    }
115    private IntValue Seed {
116      get { return SeedParameter.Value; }
117      set { SeedParameter.Value = value; }
118    }
119    private BoolValue SetSeedRandomly {
120      get { return SetSeedRandomlyParameter.Value; }
121      set { SetSeedRandomlyParameter.Value = value; }
122    }
123    public RandomCreator RandomCreator {
124      get { return (RandomCreator)OperatorGraph.InitialOperator; }
125    }
126    public SolutionsCreator SolutionsCreator {
127      get { return (SolutionsCreator)RandomCreator.Successor; }
128    }
129    public ScatterSearchMainLoop MainLoop {
130      get { return FindMainLoop(SolutionsCreator.Successor); }
131    }
132
133    [Storable]
134    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
135    #endregion
136
137    [StorableConstructor]
138    private ScatterSearch(bool deserializing) : base(deserializing) { }
139    [StorableHook(HookType.AfterDeserialization)]
140    private void AfterDeserialization() {
141      Initialize();
142    }
143    private ScatterSearch(ScatterSearch original, Cloner cloner)
144      : base(original, cloner) {
145      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
146      Initialize();
147    }
148    public override IDeepCloneable Clone(Cloner cloner) {
149      return new ScatterSearch(this, cloner);
150    }
151    public ScatterSearch()
152      : base() {
153      #region Create parameters
154      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
155      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to combine solutions."));
156      Parameters.Add(new ValueParameter<ILocalImprovementOperator>("Improver", "The operator used to improve solutions.", new ScatterSearchImprovementOperator()));
157      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
158      Parameters.Add(new ValueParameter<IntValue>("NumberOfHighQualitySolutions", "The number of high quality solutions that should be added to the reference set.", new IntValue(5)));
159      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population.", new IntValue(30)));
160      Parameters.Add(new ValueParameter<IntValue>("ReferenceSetSize", "The size of the reference set.", new IntValue(10)));
161      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
162      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
163      #endregion
164
165      #region Create operators
166      RandomCreator randomCreator = new RandomCreator();
167      SolutionsCreator solutionsCreator = new SolutionsCreator();
168      UniformSubScopesProcessor uniformSubScopesProcessor = new UniformSubScopesProcessor();
169      Placeholder solutionEvaluator = new Placeholder();
170      Placeholder solutionImprover = new Placeholder();
171      BestSelector bestSelector = new BestSelector();
172      VariableCreator variableCreator = new VariableCreator();
173      ResultsCollector resultsCollector = new ResultsCollector();
174      ScatterSearchMainLoop mainLoop = new ScatterSearchMainLoop();
175      #endregion
176
177      #region Create operator graph
178      OperatorGraph.InitialOperator = randomCreator;
179      randomCreator.RandomParameter.ActualName = "Random";
180      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
181      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
182      randomCreator.Successor = solutionsCreator;
183
184      solutionsCreator.Name = "DiversificationGenerationMethod";
185      solutionsCreator.NumberOfSolutionsParameter.ActualName = "PopulationSize";
186      solutionsCreator.Successor = uniformSubScopesProcessor;
187
188      uniformSubScopesProcessor.Operator = solutionImprover;
189      uniformSubScopesProcessor.Successor = bestSelector;
190
191      solutionImprover.Name = "SolutionImprover";
192      solutionImprover.OperatorParameter.ActualName = "Improver";
193      solutionImprover.Successor = solutionEvaluator;
194
195      solutionEvaluator.Name = "SolutionEvaluator";
196      solutionEvaluator.OperatorParameter.ActualName = "Evaluator";
197      solutionEvaluator.Successor = null;
198
199      bestSelector.NumberOfSelectedSubScopesParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
200      bestSelector.CopySelected = new BoolValue(false);
201      bestSelector.Successor = variableCreator;
202
203      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
204      variableCreator.CollectedValues.Add(new ValueParameter<BoolValue>("NewSolutions", new BoolValue(false)));
205      variableCreator.Successor = resultsCollector;
206
207      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Iterations"));
208      resultsCollector.ResultsParameter.ActualName = "Results";
209      resultsCollector.Successor = mainLoop;
210
211      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
212      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
213      mainLoop.ResultsParameter.ActualName = "Results";
214      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
215      mainLoop.IterationsParameter.ActualName = "Iterations";
216      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
217      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
218      mainLoop.NumberOfHighQualitySolutionsParameter.ActualName = NumberOfHighQualitySolutionsParameter.Name;
219      mainLoop.Successor = null;
220      #endregion
221
222      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
223      ParameterizeAnalyzers();
224      UpdateAnalyzers();
225
226      Initialize();
227    }
228
229    public override void Prepare() {
230      base.Prepare();
231    }
232
233    #region Events
234    protected override void OnProblemChanged() {
235      ParameterizeStochasticOperator(Problem.SolutionCreator);
236      ParameterizeStochasticOperator(Problem.Evaluator);
237      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
238      ParameterizeAnalyzers();
239      ParameterizeMainLoop();
240      ParameterizeSolutionsCreator();
241      UpdateAnalyzers();
242      UpdateCrossovers();
243      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
244      base.OnProblemChanged();
245    }
246    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
247      ParameterizeStochasticOperator(Problem.SolutionCreator);
248      ParameterizeSolutionsCreator();
249      base.Problem_SolutionCreatorChanged(sender, e);
250    }
251    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
252      ParameterizeStochasticOperator(Problem.Evaluator);
253      ParameterizeSolutionsCreator();
254      ParameterizeMainLoop();
255      ParameterizeAnalyzers();
256      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
257      base.Problem_EvaluatorChanged(sender, e);
258    }
259    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
260      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
261      UpdateAnalyzers();
262      UpdateCrossovers();
263      ParameterizeMainLoop();
264      ParameterizeAnalyzers();
265      base.Problem_OperatorsChanged(sender, e);
266    }
267    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
268      ParameterizeMainLoop();
269      ParameterizeAnalyzers();
270    }
271    #endregion
272
273    #region Helpers
274    private void Initialize() {
275      if (Problem != null) {
276        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
277      }
278    }
279    private void UpdateAnalyzers() {
280      Analyzer.Operators.Clear();
281      if (Problem != null) {
282        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
283          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
284            param.Depth = 1;
285          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
286        }
287      }
288      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
289    }
290    private void UpdateCrossovers() {
291      ICrossover oldCrossover = CrossoverParameter.Value;
292      CrossoverParameter.ValidValues.Clear();
293      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
294
295      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
296        CrossoverParameter.ValidValues.Add(crossover);
297
298      foreach (var crossover in CrossoverParameter.ValidValues.OfType<Knapsack.INBinaryVectorCrossover>())
299        crossover.ParentsParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
300
301      if (oldCrossover != null) {
302        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
303        if (crossover != null) CrossoverParameter.Value = crossover;
304        else oldCrossover = null;
305      }
306      if (oldCrossover == null && defaultCrossover != null)
307        CrossoverParameter.Value = defaultCrossover;
308    }
309    private void ParameterizeSolutionsCreator() {
310      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
311      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
312    }
313    private void ParameterizeMainLoop() {
314      if (Problem != null) {
315        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
316        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
317        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
318      }
319    }
320    private void ParameterizeStochasticOperator(IOperator op) {
321      if (op is IStochasticOperator) {
322        IStochasticOperator stOp = (IStochasticOperator)op;
323        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
324        stOp.RandomParameter.Hidden = true;
325      }
326    }
327    private void ParameterizeAnalyzers() {
328      qualityAnalyzer.ResultsParameter.ActualName = "Results";
329      qualityAnalyzer.ResultsParameter.Hidden = true;
330      if (Problem != null) {
331        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
332        qualityAnalyzer.MaximizationParameter.Hidden = true;
333        qualityAnalyzer.QualityParameter.Hidden = false;
334        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
335        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
336      } else {
337        qualityAnalyzer.MaximizationParameter.Hidden = false;
338        qualityAnalyzer.BestKnownQualityParameter.Hidden = false;
339      }
340    }
341    private ScatterSearchMainLoop FindMainLoop(IOperator start) {
342      IOperator mainLoop = start;
343      while (mainLoop != null && !(mainLoop is ScatterSearchMainLoop))
344        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
345      if (mainLoop == null) return null;
346      else return (ScatterSearchMainLoop)mainLoop;
347    }
348    #endregion
349  }
350}
Note: See TracBrowser for help on using the repository browser.