Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3840 was 3816, checked in by swagner, 15 years ago

Removed sorting of analyzer provided by problems (#893)

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