Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4437 was 4437, checked in by swagner, 13 years ago

Implemented !IStorableContent separately for each algorithm (#1193)

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, IStorableContent {
40    public string Filename { get; set; }
41
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    }
71    private ValueParameter<IntValue> SampleSizeParameter {
72      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
73    }
74    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
75      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
76    }
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    }
104    public IntValue SampleSize {
105      get { return SampleSizeParameter.Value; }
106      set { SampleSizeParameter.Value = value; }
107    }
108    public MultiAnalyzer Analyzer {
109      get { return AnalyzerParameter.Value; }
110      set { AnalyzerParameter.Value = value; }
111    }
112    private RandomCreator RandomCreator {
113      get { return (RandomCreator)OperatorGraph.InitialOperator; }
114    }
115    private SolutionsCreator SolutionsCreator {
116      get { return (SolutionsCreator)RandomCreator.Successor; }
117    }
118    private LocalSearchMainLoop MainLoop {
119      get { return (LocalSearchMainLoop)SolutionsCreator.Successor; }
120    }
121    [Storable]
122    private BestAverageWorstQualityAnalyzer moveQualityAnalyzer;
123    #endregion
124
125    [StorableConstructor]
126    private LocalSearch(bool deserializing) : base(deserializing) { }
127    public LocalSearch()
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)));
135      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
136      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
137
138      RandomCreator randomCreator = new RandomCreator();
139      SolutionsCreator solutionsCreator = new SolutionsCreator();
140      LocalSearchMainLoop lsMainLoop = new LocalSearchMainLoop();
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";
159      lsMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
160
161      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
162      ParameterizeAnalyzers();
163      UpdateAnalyzers();
164
165      Initialize();
166    }
167
168    public override IDeepCloneable Clone(Cloner cloner) {
169      LocalSearch clone = (LocalSearch)base.Clone(cloner);
170      clone.moveQualityAnalyzer = (BestAverageWorstQualityAnalyzer)cloner.Clone(moveQualityAnalyzer);
171      clone.Initialize();
172      return clone;
173    }
174
175    public override void Prepare() {
176      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
177        base.Prepare();
178    }
179
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();
189      ParameterizeMainLoop();
190      UpdateMoveGenerator();
191      UpdateMoveParameters();
192      UpdateAnalyzers();
193      ParameterizeMoveGenerators();
194      ParameterizeMoveEvaluators();
195      ParameterizeMoveMakers();
196      ParameterizeAnalyzers();
197      ParameterizeIterationBasedOperators();
198      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
199      base.OnProblemChanged();
200    }
201    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
202      ParameterizeStochasticOperator(Problem.SolutionCreator);
203      ParameterizeSolutionsCreator();
204      base.Problem_SolutionCreatorChanged(sender, e);
205    }
206    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
207      ParameterizeStochasticOperator(Problem.Evaluator);
208      ParameterizeSolutionsCreator();
209      ParameterizeMainLoop();
210      ParameterizeMoveEvaluators();
211      ParameterizeMoveMakers();
212      ParameterizeAnalyzers();
213      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
214      base.Problem_EvaluatorChanged(sender, e);
215    }
216    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
217      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
218      // This may seem pointless, but some operators already have the eventhandler registered, others don't
219      // FIXME: Is there another way to solve this problem?
220      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
221        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
222        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
223      }
224      UpdateMoveGenerator();
225      UpdateMoveParameters();
226      UpdateAnalyzers();
227      ParameterizeMainLoop();
228      ParameterizeMoveGenerators();
229      ParameterizeMoveEvaluators();
230      ParameterizeMoveMakers();
231      ParameterizeAnalyzers();
232      ParameterizeIterationBasedOperators();
233      base.Problem_OperatorsChanged(sender, e);
234    }
235    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
236      ParameterizeMainLoop();
237      ParameterizeMoveEvaluators();
238      ParameterizeMoveMakers();
239    }
240    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
241      UpdateMoveParameters();
242    }
243    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
244      ParameterizeMainLoop();
245      ParameterizeMoveEvaluators();
246      ParameterizeMoveMakers();
247      ParameterizeAnalyzers();
248    }
249    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
250      ParameterizeMainLoop();
251      ParameterizeMoveEvaluators();
252      ParameterizeMoveMakers();
253      ParameterizeAnalyzers();
254    }
255    #endregion
256
257    #region Helpers
258    [StorableHook(HookType.AfterDeserialization)]
259    private void Initialize() {
260      if (Problem != null) {
261        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
262        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
263          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
264        }
265      }
266      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
267      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
268    }
269    private void UpdateMoveGenerator() {
270      IMoveGenerator oldMoveGenerator = MoveGenerator;
271      MoveGeneratorParameter.ValidValues.Clear();
272      if (Problem != null) {
273        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
274          MoveGeneratorParameter.ValidValues.Add(generator);
275      }
276      if (oldMoveGenerator != null) {
277        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
278        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
279      }
280      if (MoveGenerator == null) {
281        ClearMoveParameters();
282      }
283    }
284    private void UpdateMoveParameters() {
285      IMoveMaker oldMoveMaker = MoveMaker;
286      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
287      ClearMoveParameters();
288      if (MoveGenerator != null) {
289        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
290        foreach (Type type in moveTypes.ToList()) {
291          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
292            moveTypes.Remove(type);
293        }
294        foreach (Type type in moveTypes) {
295          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
296          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
297            MoveMakerParameter.ValidValues.Add(moveMaker);
298          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
299            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
300        }
301        if (oldMoveMaker != null) {
302          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
303          if (mm != null) MoveMaker = mm;
304        }
305        if (oldMoveEvaluator != null) {
306          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
307          if (me != null) MoveEvaluator = me;
308        }
309      }
310    }
311    private void UpdateAnalyzers() {
312      Analyzer.Operators.Clear();
313      if (Problem != null) {
314        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
315          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
316            param.Depth = 0;
317          Analyzer.Operators.Add(analyzer);
318        }
319      }
320      Analyzer.Operators.Add(moveQualityAnalyzer);
321    }
322    private void ClearMoveParameters() {
323      MoveMakerParameter.ValidValues.Clear();
324      MoveEvaluatorParameter.ValidValues.Clear();
325    }
326    private void ParameterizeSolutionsCreator() {
327      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
328      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
329    }
330    private void ParameterizeMainLoop() {
331      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
332      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
333      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
334      if (MoveEvaluator != null)
335        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
336    }
337    private void ParameterizeStochasticOperator(IOperator op) {
338      if (op is IStochasticOperator)
339        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
340    }
341    private void ParameterizeMoveGenerators() {
342      if (Problem != null) {
343        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>())
344          generator.SampleSizeParameter.ActualName = SampleSizeParameter.Name;
345      }
346    }
347    private void ParameterizeMoveEvaluators() {
348      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
349        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
350      }
351    }
352    private void ParameterizeMoveMakers() {
353      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
354        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
355        if (MoveEvaluator != null)
356          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
357      }
358    }
359    private void ParameterizeAnalyzers() {
360      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
361      if (Problem != null) {
362        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
363        if (MoveEvaluator != null)
364          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
365        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
366      }
367    }
368    private void ParameterizeIterationBasedOperators() {
369      if (Problem != null) {
370        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
371          op.IterationsParameter.ActualName = "Iterations";
372          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
373        }
374      }
375    }
376    #endregion
377  }
378}
Note: See TracBrowser for help on using the repository browser.