Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.LocalSearch/3.3/LocalSearch.cs @ 5447

Last change on this file since 5447 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 18.7 KB
RevLine 
[3078]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3078]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;
[4068]25using HeuristicLab.Analysis;
[3376]26using HeuristicLab.Common;
[3078]27using HeuristicLab.Core;
28using HeuristicLab.Data;
[5356]29using HeuristicLab.Operators;
[3078]30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[3368]34using HeuristicLab.Random;
[3078]35
[3103]36namespace HeuristicLab.Algorithms.LocalSearch {
[3280]37  [Item("Local Search", "A local search algorithm.")]
[3078]38  [Creatable("Algorithms")]
[3201]39  [StorableClass]
[4437]40  public sealed class LocalSearch : EngineAlgorithm, IStorableContent {
41    public string Filename { get; set; }
42
[3078]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    }
[3187]72    private ValueParameter<IntValue> SampleSizeParameter {
73      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
74    }
[3658]75    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
76      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
[3621]77    }
[3078]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    }
[3187]105    public IntValue SampleSize {
106      get { return SampleSizeParameter.Value; }
107      set { SampleSizeParameter.Value = value; }
108    }
[3658]109    public MultiAnalyzer Analyzer {
[3621]110      get { return AnalyzerParameter.Value; }
111      set { AnalyzerParameter.Value = value; }
112    }
[3078]113    private RandomCreator RandomCreator {
114      get { return (RandomCreator)OperatorGraph.InitialOperator; }
115    }
116    private SolutionsCreator SolutionsCreator {
117      get { return (SolutionsCreator)RandomCreator.Successor; }
118    }
[3103]119    private LocalSearchMainLoop MainLoop {
[5366]120      get { return FindMainLoop(SolutionsCreator.Successor); }
[3078]121    }
[3689]122    [Storable]
[3662]123    private BestAverageWorstQualityAnalyzer moveQualityAnalyzer;
[3078]124    #endregion
125
[3621]126    [StorableConstructor]
127    private LocalSearch(bool deserializing) : base(deserializing) { }
[4722]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    }
[3103]140    public LocalSearch()
[3078]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)));
[3187]148      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
[3809]149      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
[4068]150
[3078]151      RandomCreator randomCreator = new RandomCreator();
152      SolutionsCreator solutionsCreator = new SolutionsCreator();
[5356]153      VariableCreator variableCreator = new VariableCreator();
154      ResultsCollector resultsCollector = new ResultsCollector();
155      LocalSearchMainLoop mainLoop = new LocalSearchMainLoop();
[3078]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);
[5356]166      solutionsCreator.Successor = variableCreator;
[3078]167
[5356]168      variableCreator.Name = "Initialize EvaluatedMoves";
169      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedMoves", new IntValue()));
170      variableCreator.Successor = resultsCollector;
[3078]171
[5356]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
[3689]185      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
186      ParameterizeAnalyzers();
187      UpdateAnalyzers();
188
[3078]189      Initialize();
190    }
191
[3275]192    public override void Prepare() {
[3265]193      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
[3275]194        base.Prepare();
[3189]195    }
196
[3078]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();
[3134]206      ParameterizeMainLoop();
[3750]207      UpdateMoveGenerator();
208      UpdateMoveParameters();
209      UpdateAnalyzers();
[4048]210      ParameterizeMoveGenerators();
[3145]211      ParameterizeMoveEvaluators();
212      ParameterizeMoveMakers();
[3621]213      ParameterizeAnalyzers();
[3750]214      ParameterizeIterationBasedOperators();
[3078]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();
[3134]226      ParameterizeMainLoop();
[3145]227      ParameterizeMoveEvaluators();
228      ParameterizeMoveMakers();
[3621]229      ParameterizeAnalyzers();
[3078]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();
[3187]242      UpdateMoveParameters();
[3621]243      UpdateAnalyzers();
[3134]244      ParameterizeMainLoop();
[4048]245      ParameterizeMoveGenerators();
[3145]246      ParameterizeMoveEvaluators();
247      ParameterizeMoveMakers();
[3636]248      ParameterizeAnalyzers();
[3750]249      ParameterizeIterationBasedOperators();
[3078]250      base.Problem_OperatorsChanged(sender, e);
251    }
252    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]253      ParameterizeMainLoop();
[3145]254      ParameterizeMoveEvaluators();
255      ParameterizeMoveMakers();
[3078]256    }
257    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
258      UpdateMoveParameters();
259    }
260    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
[3134]261      ParameterizeMainLoop();
[3145]262      ParameterizeMoveEvaluators();
263      ParameterizeMoveMakers();
[3621]264      ParameterizeAnalyzers();
[3078]265    }
266    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]267      ParameterizeMainLoop();
[3145]268      ParameterizeMoveEvaluators();
269      ParameterizeMoveMakers();
[3621]270      ParameterizeAnalyzers();
[3078]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      }
[3145]292      if (oldMoveGenerator != null) {
293        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
294        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
295      }
[3078]296      if (MoveGenerator == null) {
297        ClearMoveParameters();
298      }
299    }
300    private void UpdateMoveParameters() {
301      IMoveMaker oldMoveMaker = MoveMaker;
302      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
303      ClearMoveParameters();
[3131]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        }
[3078]325      }
326    }
[3621]327    private void UpdateAnalyzers() {
328      Analyzer.Operators.Clear();
[3626]329      if (Problem != null) {
[3816]330        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
[3669]331          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
332            param.Depth = 0;
[3621]333          Analyzer.Operators.Add(analyzer);
[3669]334        }
[3626]335      }
[3809]336      Analyzer.Operators.Add(moveQualityAnalyzer);
[3621]337    }
[3078]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    }
[3134]346    private void ParameterizeMainLoop() {
[3145]347      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[3103]348      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
349      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[3078]350      if (MoveEvaluator != null)
[3103]351        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[3078]352    }
353    private void ParameterizeStochasticOperator(IOperator op) {
354      if (op is IStochasticOperator)
355        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
356    }
[4048]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    }
[3145]363    private void ParameterizeMoveEvaluators() {
[3078]364      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
365        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
366      }
367    }
[3145]368    private void ParameterizeMoveMakers() {
[3078]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    }
[3621]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    }
[3750]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    }
[5366]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    }
[3078]399    #endregion
400  }
401}
Note: See TracBrowser for help on using the repository browser.