Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Algorithms.LocalSearch/3.3/LocalSearch.cs @ 13806

Last change on this file since 13806 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 20.1 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]
[5809]40  public sealed class LocalSearch : HeuristicOptimizationEngineAlgorithm, IStorableContent {
[4437]41    public string Filename { get; set; }
42
[3078]43    #region Problem Properties
44    public override Type ProblemType {
[5809]45      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
[3078]46    }
[5809]47    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
48      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
[3078]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    }
[6760]60    public ConstrainedValueParameter<IMoveGenerator> MoveGeneratorParameter {
[3078]61      get { return (ConstrainedValueParameter<IMoveGenerator>)Parameters["MoveGenerator"]; }
62    }
[6760]63    public ConstrainedValueParameter<IMoveMaker> MoveMakerParameter {
[3078]64      get { return (ConstrainedValueParameter<IMoveMaker>)Parameters["MoveMaker"]; }
65    }
[6760]66    public ConstrainedValueParameter<ISingleObjectiveMoveEvaluator> MoveEvaluatorParameter {
[3078]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()));
[5753]170      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
171      variableCreator.CollectedValues.Add(new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(0)));
[5356]172      variableCreator.Successor = resultsCollector;
[3078]173
[5356]174      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Moves", null, "EvaluatedMoves"));
175      resultsCollector.ResultsParameter.ActualName = "Results";
176      resultsCollector.Successor = mainLoop;
177
178      mainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
179      mainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
180      mainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
181      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
182      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
183      mainLoop.ResultsParameter.ActualName = "Results";
184      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
185      mainLoop.EvaluatedMovesParameter.ActualName = "EvaluatedMoves";
[5753]186      mainLoop.IterationsParameter.ActualName = "Iterations";
[6042]187      mainLoop.BestLocalQualityParameter.ActualName = "BestQuality";
[5356]188
[3689]189      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
190      ParameterizeAnalyzers();
191      UpdateAnalyzers();
192
[3078]193      Initialize();
194    }
195
[3275]196    public override void Prepare() {
[3265]197      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
[3275]198        base.Prepare();
[3189]199    }
200
[3078]201    #region Events
202    protected override void OnProblemChanged() {
203      ParameterizeStochasticOperator(Problem.SolutionCreator);
204      ParameterizeStochasticOperator(Problem.Evaluator);
205      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
206      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
207        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
208      }
209      ParameterizeSolutionsCreator();
[3134]210      ParameterizeMainLoop();
[3750]211      UpdateMoveGenerator();
212      UpdateMoveParameters();
213      UpdateAnalyzers();
[4048]214      ParameterizeMoveGenerators();
[3145]215      ParameterizeMoveEvaluators();
216      ParameterizeMoveMakers();
[3621]217      ParameterizeAnalyzers();
[3750]218      ParameterizeIterationBasedOperators();
[3078]219      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
220      base.OnProblemChanged();
221    }
222    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
223      ParameterizeStochasticOperator(Problem.SolutionCreator);
224      ParameterizeSolutionsCreator();
225      base.Problem_SolutionCreatorChanged(sender, e);
226    }
227    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
228      ParameterizeStochasticOperator(Problem.Evaluator);
229      ParameterizeSolutionsCreator();
[3134]230      ParameterizeMainLoop();
[3145]231      ParameterizeMoveEvaluators();
232      ParameterizeMoveMakers();
[3621]233      ParameterizeAnalyzers();
[3078]234      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
235      base.Problem_EvaluatorChanged(sender, e);
236    }
237    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
238      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
239      // This may seem pointless, but some operators already have the eventhandler registered, others don't
240      // FIXME: Is there another way to solve this problem?
241      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
242        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
243        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
244      }
245      UpdateMoveGenerator();
[3187]246      UpdateMoveParameters();
[3621]247      UpdateAnalyzers();
[3134]248      ParameterizeMainLoop();
[4048]249      ParameterizeMoveGenerators();
[3145]250      ParameterizeMoveEvaluators();
251      ParameterizeMoveMakers();
[3636]252      ParameterizeAnalyzers();
[3750]253      ParameterizeIterationBasedOperators();
[3078]254      base.Problem_OperatorsChanged(sender, e);
255    }
256    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]257      ParameterizeMainLoop();
[3145]258      ParameterizeMoveEvaluators();
259      ParameterizeMoveMakers();
[3078]260    }
261    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
262      UpdateMoveParameters();
263    }
264    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
[3134]265      ParameterizeMainLoop();
[3145]266      ParameterizeMoveEvaluators();
267      ParameterizeMoveMakers();
[3621]268      ParameterizeAnalyzers();
[3078]269    }
270    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]271      ParameterizeMainLoop();
[3145]272      ParameterizeMoveEvaluators();
273      ParameterizeMoveMakers();
[3621]274      ParameterizeAnalyzers();
[3078]275    }
276    #endregion
277
278    #region Helpers
279    private void Initialize() {
280      if (Problem != null) {
281        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
282        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
283          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
284        }
285      }
286      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
287      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
288    }
289    private void UpdateMoveGenerator() {
290      IMoveGenerator oldMoveGenerator = MoveGenerator;
291      MoveGeneratorParameter.ValidValues.Clear();
292      if (Problem != null) {
293        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
294          MoveGeneratorParameter.ValidValues.Add(generator);
295      }
[3145]296      if (oldMoveGenerator != null) {
297        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
298        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
299      }
[3078]300      if (MoveGenerator == null) {
301        ClearMoveParameters();
302      }
303    }
304    private void UpdateMoveParameters() {
305      IMoveMaker oldMoveMaker = MoveMaker;
306      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
307      ClearMoveParameters();
[3131]308      if (MoveGenerator != null) {
309        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
310        foreach (Type type in moveTypes.ToList()) {
311          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
312            moveTypes.Remove(type);
313        }
314        foreach (Type type in moveTypes) {
315          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
316          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
317            MoveMakerParameter.ValidValues.Add(moveMaker);
318          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
319            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
320        }
321        if (oldMoveMaker != null) {
322          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
323          if (mm != null) MoveMaker = mm;
324        }
325        if (oldMoveEvaluator != null) {
326          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
327          if (me != null) MoveEvaluator = me;
328        }
[3078]329      }
330    }
[3621]331    private void UpdateAnalyzers() {
332      Analyzer.Operators.Clear();
[3626]333      if (Problem != null) {
[3816]334        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
[3669]335          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
336            param.Depth = 0;
[3621]337          Analyzer.Operators.Add(analyzer);
[3669]338        }
[3626]339      }
[3809]340      Analyzer.Operators.Add(moveQualityAnalyzer);
[3621]341    }
[3078]342    private void ClearMoveParameters() {
343      MoveMakerParameter.ValidValues.Clear();
344      MoveEvaluatorParameter.ValidValues.Clear();
345    }
346    private void ParameterizeSolutionsCreator() {
347      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
348      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
349    }
[3134]350    private void ParameterizeMainLoop() {
[6053]351      if (Problem != null) {
352        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
353        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
354        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
355      }
[3078]356      if (MoveEvaluator != null)
[3103]357        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[3078]358    }
359    private void ParameterizeStochasticOperator(IOperator op) {
[6053]360      if (op is IStochasticOperator) {
361        IStochasticOperator stOp = (IStochasticOperator)op;
362        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
363        stOp.RandomParameter.Hidden = true;
364      }
[3078]365    }
[4048]366    private void ParameterizeMoveGenerators() {
367      if (Problem != null) {
[6053]368        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>()) {
[4048]369          generator.SampleSizeParameter.ActualName = SampleSizeParameter.Name;
[6053]370          generator.SampleSizeParameter.Hidden = true;
371        }
[4048]372      }
373    }
[3145]374    private void ParameterizeMoveEvaluators() {
[3078]375      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
376        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[6053]377        op.QualityParameter.Hidden = true;
[3078]378      }
379    }
[3145]380    private void ParameterizeMoveMakers() {
[3078]381      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
382        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[6053]383        op.QualityParameter.Hidden = true;
384        if (MoveEvaluator != null) {
[3078]385          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[6053]386          op.MoveQualityParameter.Hidden = true;
387        } else {
388          op.MoveQualityParameter.Hidden = false;
389        }
[3078]390      }
391    }
[3621]392    private void ParameterizeAnalyzers() {
393      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
[6053]394      moveQualityAnalyzer.ResultsParameter.Hidden = true;
[3621]395      if (Problem != null) {
396        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
[6053]397        moveQualityAnalyzer.MaximizationParameter.Hidden = true;
398        if (MoveEvaluator != null) {
[3621]399          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[6053]400          moveQualityAnalyzer.QualityParameter.Hidden = true;
401        } else moveQualityAnalyzer.QualityParameter.Hidden = false;
[3621]402        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[6053]403        moveQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
404      } else {
405        moveQualityAnalyzer.MaximizationParameter.Hidden = false;
406        moveQualityAnalyzer.BestKnownQualityParameter.Hidden = false;
[3621]407      }
408    }
[3750]409    private void ParameterizeIterationBasedOperators() {
410      if (Problem != null) {
411        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
412          op.IterationsParameter.ActualName = "Iterations";
[6053]413          op.IterationsParameter.Hidden = true;
[3750]414          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
[6053]415          op.MaximumIterationsParameter.Hidden = true;
[3750]416        }
417      }
418    }
[5366]419    private LocalSearchMainLoop FindMainLoop(IOperator start) {
420      IOperator mainLoop = start;
421      while (mainLoop != null && !(mainLoop is LocalSearchMainLoop))
422        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
423      if (mainLoop == null) return null;
424      else return (LocalSearchMainLoop)mainLoop;
425    }
[3078]426    #endregion
427  }
428}
Note: See TracBrowser for help on using the repository browser.