Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4436 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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