Free cookie consent management tool by TermsFeed Policy Generator

source: branches/SuccessProgressAnalysis/HeuristicLab.Algorithms.LocalSearch/3.3/LocalSearch.cs @ 5569

Last change on this file since 5569 was 5366, checked in by abeham, 14 years ago

#1344

  • Fixed discovery of the main loop operator in the MainLoop property
File size: 18.7 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.Collections.Generic;
24using System.Linq;
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;
35
36namespace HeuristicLab.Algorithms.LocalSearch {
37  [Item("Local Search", "A local search algorithm.")]
38  [Creatable("Algorithms")]
39  [StorableClass]
40  public sealed class LocalSearch : EngineAlgorithm, IStorableContent {
41    public string Filename { get; set; }
42
43    #region Problem Properties
44    public override Type ProblemType {
45      get { return typeof(ISingleObjectiveProblem); }
46    }
47    public new ISingleObjectiveProblem Problem {
48      get { return (ISingleObjectiveProblem)base.Problem; }
49      set { base.Problem = value; }
50    }
51    #endregion
52
53    #region Parameter Properties
54    private ValueParameter<IntValue> SeedParameter {
55      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
56    }
57    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
58      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
59    }
60    private ConstrainedValueParameter<IMoveGenerator> MoveGeneratorParameter {
61      get { return (ConstrainedValueParameter<IMoveGenerator>)Parameters["MoveGenerator"]; }
62    }
63    private ConstrainedValueParameter<IMoveMaker> MoveMakerParameter {
64      get { return (ConstrainedValueParameter<IMoveMaker>)Parameters["MoveMaker"]; }
65    }
66    private ConstrainedValueParameter<ISingleObjectiveMoveEvaluator> MoveEvaluatorParameter {
67      get { return (ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>)Parameters["MoveEvaluator"]; }
68    }
69    private ValueParameter<IntValue> MaximumIterationsParameter {
70      get { return (ValueParameter<IntValue>)Parameters["MaximumIterations"]; }
71    }
72    private ValueParameter<IntValue> SampleSizeParameter {
73      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
74    }
75    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
76      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
77    }
78    #endregion
79
80    #region Properties
81    public IntValue Seed {
82      get { return SeedParameter.Value; }
83      set { SeedParameter.Value = value; }
84    }
85    public BoolValue SetSeedRandomly {
86      get { return SetSeedRandomlyParameter.Value; }
87      set { SetSeedRandomlyParameter.Value = value; }
88    }
89    public IMoveGenerator MoveGenerator {
90      get { return MoveGeneratorParameter.Value; }
91      set { MoveGeneratorParameter.Value = value; }
92    }
93    public IMoveMaker MoveMaker {
94      get { return MoveMakerParameter.Value; }
95      set { MoveMakerParameter.Value = value; }
96    }
97    public ISingleObjectiveMoveEvaluator MoveEvaluator {
98      get { return MoveEvaluatorParameter.Value; }
99      set { MoveEvaluatorParameter.Value = value; }
100    }
101    public IntValue MaximumIterations {
102      get { return MaximumIterationsParameter.Value; }
103      set { MaximumIterationsParameter.Value = value; }
104    }
105    public IntValue SampleSize {
106      get { return SampleSizeParameter.Value; }
107      set { SampleSizeParameter.Value = value; }
108    }
109    public MultiAnalyzer Analyzer {
110      get { return AnalyzerParameter.Value; }
111      set { AnalyzerParameter.Value = value; }
112    }
113    private RandomCreator RandomCreator {
114      get { return (RandomCreator)OperatorGraph.InitialOperator; }
115    }
116    private SolutionsCreator SolutionsCreator {
117      get { return (SolutionsCreator)RandomCreator.Successor; }
118    }
119    private LocalSearchMainLoop MainLoop {
120      get { return FindMainLoop(SolutionsCreator.Successor); }
121    }
122    [Storable]
123    private BestAverageWorstQualityAnalyzer moveQualityAnalyzer;
124    #endregion
125
126    [StorableConstructor]
127    private LocalSearch(bool deserializing) : base(deserializing) { }
128    [StorableHook(HookType.AfterDeserialization)]
129    private void AfterDeserialization() {
130      Initialize();
131    }
132    private LocalSearch(LocalSearch original, Cloner cloner)
133      : base(original, cloner) {
134      moveQualityAnalyzer = cloner.Clone(original.moveQualityAnalyzer);
135      Initialize();
136    }
137    public override IDeepCloneable Clone(Cloner cloner) {
138      return new LocalSearch(this, cloner);
139    }
140    public LocalSearch()
141      : base() {
142      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
143      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
144      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
145      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
146      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
147      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
148      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
149      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
150
151      RandomCreator randomCreator = new RandomCreator();
152      SolutionsCreator solutionsCreator = new SolutionsCreator();
153      VariableCreator variableCreator = new VariableCreator();
154      ResultsCollector resultsCollector = new ResultsCollector();
155      LocalSearchMainLoop mainLoop = new LocalSearchMainLoop();
156      OperatorGraph.InitialOperator = randomCreator;
157
158      randomCreator.RandomParameter.ActualName = "Random";
159      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
160      randomCreator.SeedParameter.Value = null;
161      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
162      randomCreator.SetSeedRandomlyParameter.Value = null;
163      randomCreator.Successor = solutionsCreator;
164
165      solutionsCreator.NumberOfSolutions = new IntValue(1);
166      solutionsCreator.Successor = variableCreator;
167
168      variableCreator.Name = "Initialize EvaluatedMoves";
169      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedMoves", new IntValue()));
170      variableCreator.Successor = resultsCollector;
171
172      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Moves", null, "EvaluatedMoves"));
173      resultsCollector.ResultsParameter.ActualName = "Results";
174      resultsCollector.Successor = mainLoop;
175
176      mainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
177      mainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
178      mainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
179      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
180      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
181      mainLoop.ResultsParameter.ActualName = "Results";
182      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
183      mainLoop.EvaluatedMovesParameter.ActualName = "EvaluatedMoves";
184
185      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
186      ParameterizeAnalyzers();
187      UpdateAnalyzers();
188
189      Initialize();
190    }
191
192    public override void Prepare() {
193      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
194        base.Prepare();
195    }
196
197    #region Events
198    protected override void OnProblemChanged() {
199      ParameterizeStochasticOperator(Problem.SolutionCreator);
200      ParameterizeStochasticOperator(Problem.Evaluator);
201      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
202      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
203        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
204      }
205      ParameterizeSolutionsCreator();
206      ParameterizeMainLoop();
207      UpdateMoveGenerator();
208      UpdateMoveParameters();
209      UpdateAnalyzers();
210      ParameterizeMoveGenerators();
211      ParameterizeMoveEvaluators();
212      ParameterizeMoveMakers();
213      ParameterizeAnalyzers();
214      ParameterizeIterationBasedOperators();
215      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
216      base.OnProblemChanged();
217    }
218    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
219      ParameterizeStochasticOperator(Problem.SolutionCreator);
220      ParameterizeSolutionsCreator();
221      base.Problem_SolutionCreatorChanged(sender, e);
222    }
223    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
224      ParameterizeStochasticOperator(Problem.Evaluator);
225      ParameterizeSolutionsCreator();
226      ParameterizeMainLoop();
227      ParameterizeMoveEvaluators();
228      ParameterizeMoveMakers();
229      ParameterizeAnalyzers();
230      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
231      base.Problem_EvaluatorChanged(sender, e);
232    }
233    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
234      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
235      // This may seem pointless, but some operators already have the eventhandler registered, others don't
236      // FIXME: Is there another way to solve this problem?
237      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
238        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
239        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
240      }
241      UpdateMoveGenerator();
242      UpdateMoveParameters();
243      UpdateAnalyzers();
244      ParameterizeMainLoop();
245      ParameterizeMoveGenerators();
246      ParameterizeMoveEvaluators();
247      ParameterizeMoveMakers();
248      ParameterizeAnalyzers();
249      ParameterizeIterationBasedOperators();
250      base.Problem_OperatorsChanged(sender, e);
251    }
252    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
253      ParameterizeMainLoop();
254      ParameterizeMoveEvaluators();
255      ParameterizeMoveMakers();
256    }
257    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
258      UpdateMoveParameters();
259    }
260    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
261      ParameterizeMainLoop();
262      ParameterizeMoveEvaluators();
263      ParameterizeMoveMakers();
264      ParameterizeAnalyzers();
265    }
266    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
267      ParameterizeMainLoop();
268      ParameterizeMoveEvaluators();
269      ParameterizeMoveMakers();
270      ParameterizeAnalyzers();
271    }
272    #endregion
273
274    #region Helpers
275    private void Initialize() {
276      if (Problem != null) {
277        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
278        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
279          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
280        }
281      }
282      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
283      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
284    }
285    private void UpdateMoveGenerator() {
286      IMoveGenerator oldMoveGenerator = MoveGenerator;
287      MoveGeneratorParameter.ValidValues.Clear();
288      if (Problem != null) {
289        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
290          MoveGeneratorParameter.ValidValues.Add(generator);
291      }
292      if (oldMoveGenerator != null) {
293        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
294        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
295      }
296      if (MoveGenerator == null) {
297        ClearMoveParameters();
298      }
299    }
300    private void UpdateMoveParameters() {
301      IMoveMaker oldMoveMaker = MoveMaker;
302      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
303      ClearMoveParameters();
304      if (MoveGenerator != null) {
305        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
306        foreach (Type type in moveTypes.ToList()) {
307          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
308            moveTypes.Remove(type);
309        }
310        foreach (Type type in moveTypes) {
311          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
312          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
313            MoveMakerParameter.ValidValues.Add(moveMaker);
314          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
315            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
316        }
317        if (oldMoveMaker != null) {
318          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
319          if (mm != null) MoveMaker = mm;
320        }
321        if (oldMoveEvaluator != null) {
322          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
323          if (me != null) MoveEvaluator = me;
324        }
325      }
326    }
327    private void UpdateAnalyzers() {
328      Analyzer.Operators.Clear();
329      if (Problem != null) {
330        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
331          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
332            param.Depth = 0;
333          Analyzer.Operators.Add(analyzer);
334        }
335      }
336      Analyzer.Operators.Add(moveQualityAnalyzer);
337    }
338    private void ClearMoveParameters() {
339      MoveMakerParameter.ValidValues.Clear();
340      MoveEvaluatorParameter.ValidValues.Clear();
341    }
342    private void ParameterizeSolutionsCreator() {
343      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
344      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
345    }
346    private void ParameterizeMainLoop() {
347      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
348      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
349      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
350      if (MoveEvaluator != null)
351        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
352    }
353    private void ParameterizeStochasticOperator(IOperator op) {
354      if (op is IStochasticOperator)
355        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
356    }
357    private void ParameterizeMoveGenerators() {
358      if (Problem != null) {
359        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>())
360          generator.SampleSizeParameter.ActualName = SampleSizeParameter.Name;
361      }
362    }
363    private void ParameterizeMoveEvaluators() {
364      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
365        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
366      }
367    }
368    private void ParameterizeMoveMakers() {
369      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
370        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
371        if (MoveEvaluator != null)
372          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
373      }
374    }
375    private void ParameterizeAnalyzers() {
376      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
377      if (Problem != null) {
378        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
379        if (MoveEvaluator != null)
380          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
381        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
382      }
383    }
384    private void ParameterizeIterationBasedOperators() {
385      if (Problem != null) {
386        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
387          op.IterationsParameter.ActualName = "Iterations";
388          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
389        }
390      }
391    }
392    private LocalSearchMainLoop FindMainLoop(IOperator start) {
393      IOperator mainLoop = start;
394      while (mainLoop != null && !(mainLoop is LocalSearchMainLoop))
395        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
396      if (mainLoop == null) return null;
397      else return (LocalSearchMainLoop)mainLoop;
398    }
399    #endregion
400  }
401}
Note: See TracBrowser for help on using the repository browser.