Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3629 was 3626, checked in by abeham, 15 years ago

Fixed build break in ES, LS, and SA due to Analyzer changes #999

File size: 17.5 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.Common;
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;
34using HeuristicLab.Random;
35using HeuristicLab.Analysis;
36
37namespace HeuristicLab.Algorithms.LocalSearch {
38  [Item("Local Search", "A local search algorithm.")]
39  [Creatable("Algorithms")]
40  [StorableClass]
41  public sealed class LocalSearch : EngineAlgorithm {
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<IPopulationAnalyzer>> MoveAnalyzerParameter {
75      get { return (ValueParameter<MultiAnalyzer<IPopulationAnalyzer>>)Parameters["MoveAnalyzer"]; }
76    }
77    private ValueParameter<MultiAnalyzer<ISolutionAnalyzer>> AnalyzerParameter {
78      get { return (ValueParameter<MultiAnalyzer<ISolutionAnalyzer>>)Parameters["Analyzer"]; }
79    }
80    #endregion
81
82    #region Properties
83    public IntValue Seed {
84      get { return SeedParameter.Value; }
85      set { SeedParameter.Value = value; }
86    }
87    public BoolValue SetSeedRandomly {
88      get { return SetSeedRandomlyParameter.Value; }
89      set { SetSeedRandomlyParameter.Value = value; }
90    }
91    public IMoveGenerator MoveGenerator {
92      get { return MoveGeneratorParameter.Value; }
93      set { MoveGeneratorParameter.Value = value; }
94    }
95    public IMoveMaker MoveMaker {
96      get { return MoveMakerParameter.Value; }
97      set { MoveMakerParameter.Value = value; }
98    }
99    public ISingleObjectiveMoveEvaluator MoveEvaluator {
100      get { return MoveEvaluatorParameter.Value; }
101      set { MoveEvaluatorParameter.Value = value; }
102    }
103    public IntValue MaximumIterations {
104      get { return MaximumIterationsParameter.Value; }
105      set { MaximumIterationsParameter.Value = value; }
106    }
107    public IntValue SampleSize {
108      get { return SampleSizeParameter.Value; }
109      set { SampleSizeParameter.Value = value; }
110    }
111    public MultiAnalyzer<IPopulationAnalyzer> MoveAnalyzer {
112      get { return MoveAnalyzerParameter.Value; }
113      set { MoveAnalyzerParameter.Value = value; }
114    }
115    public MultiAnalyzer<ISolutionAnalyzer> Analyzer {
116      get { return AnalyzerParameter.Value; }
117      set { AnalyzerParameter.Value = value; }
118    }
119    private RandomCreator RandomCreator {
120      get { return (RandomCreator)OperatorGraph.InitialOperator; }
121    }
122    private SolutionsCreator SolutionsCreator {
123      get { return (SolutionsCreator)RandomCreator.Successor; }
124    }
125    private LocalSearchMainLoop MainLoop {
126      get { return (LocalSearchMainLoop)SolutionsCreator.Successor; }
127    }
128    private PopulationBestAverageWorstQualityAnalyzer moveQualityAnalyzer;
129    #endregion
130
131    [StorableConstructor]
132    private LocalSearch(bool deserializing) : base(deserializing) { }
133    public LocalSearch()
134      : base() {
135      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
136      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
137      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
138      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
139      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
140      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
141      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
142      Parameters.Add(new ValueParameter<MultiAnalyzer<IPopulationAnalyzer>>("MoveAnalyzer", "The operator used to analyze the moves in each iteration.", new MultiAnalyzer<IPopulationAnalyzer>()));
143      Parameters.Add(new ValueParameter<MultiAnalyzer<ISolutionAnalyzer>>("Analyzer", "The operator used to analyze each iteration.", new MultiAnalyzer<ISolutionAnalyzer>()));
144     
145      RandomCreator randomCreator = new RandomCreator();
146      SolutionsCreator solutionsCreator = new SolutionsCreator();
147      LocalSearchMainLoop lsMainLoop = new LocalSearchMainLoop();
148      OperatorGraph.InitialOperator = randomCreator;
149
150      randomCreator.RandomParameter.ActualName = "Random";
151      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
152      randomCreator.SeedParameter.Value = null;
153      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
154      randomCreator.SetSeedRandomlyParameter.Value = null;
155      randomCreator.Successor = solutionsCreator;
156
157      solutionsCreator.NumberOfSolutions = new IntValue(1);
158      solutionsCreator.Successor = lsMainLoop;
159
160      lsMainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
161      lsMainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
162      lsMainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
163      lsMainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
164      lsMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
165      lsMainLoop.ResultsParameter.ActualName = "Results";
166      lsMainLoop.MoveAnalyzerParameter.ActualName = MoveAnalyzerParameter.Name;
167      lsMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
168
169      Initialize();
170    }
171
172    public override IDeepCloneable Clone(Cloner cloner) {
173      LocalSearch clone = (LocalSearch)base.Clone(cloner);
174      clone.Initialize();
175      return clone;
176    }
177
178    public override void Prepare() {
179      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
180        base.Prepare();
181    }
182
183    #region Events
184    protected override void OnProblemChanged() {
185      ParameterizeStochasticOperator(Problem.SolutionCreator);
186      ParameterizeStochasticOperator(Problem.Evaluator);
187      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
188      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
189        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
190      }
191      ParameterizeSolutionsCreator();
192      ParameterizeMainLoop();
193      ParameterizeMoveEvaluators();
194      ParameterizeMoveMakers();
195      ParameterizeAnalyzers();
196      UpdateMoveGenerator();
197      UpdateMoveParameters();
198      UpdateAnalyzers();
199      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
200      base.OnProblemChanged();
201    }
202    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
203      ParameterizeStochasticOperator(Problem.SolutionCreator);
204      ParameterizeSolutionsCreator();
205      base.Problem_SolutionCreatorChanged(sender, e);
206    }
207    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
208      ParameterizeStochasticOperator(Problem.Evaluator);
209      ParameterizeSolutionsCreator();
210      ParameterizeMainLoop();
211      ParameterizeMoveEvaluators();
212      ParameterizeMoveMakers();
213      ParameterizeAnalyzers();
214      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
215      base.Problem_EvaluatorChanged(sender, e);
216    }
217    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
218      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
219      // This may seem pointless, but some operators already have the eventhandler registered, others don't
220      // FIXME: Is there another way to solve this problem?
221      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
222        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
223        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
224      }
225      UpdateMoveGenerator();
226      UpdateMoveParameters();
227      UpdateAnalyzers();
228      ParameterizeMainLoop();
229      ParameterizeMoveEvaluators();
230      ParameterizeMoveMakers();
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      InitializeAnalyzers();
259      UpdateAnalyzers();
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 InitializeAnalyzers() {
270      moveQualityAnalyzer = new PopulationBestAverageWorstQualityAnalyzer();
271      ParameterizeAnalyzers();
272    }
273    private void UpdateMoveGenerator() {
274      IMoveGenerator oldMoveGenerator = MoveGenerator;
275      MoveGeneratorParameter.ValidValues.Clear();
276      if (Problem != null) {
277        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
278          MoveGeneratorParameter.ValidValues.Add(generator);
279      }
280      if (oldMoveGenerator != null) {
281        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
282        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
283      }
284      if (MoveGenerator == null) {
285        ClearMoveParameters();
286      }
287    }
288    private void UpdateMoveParameters() {
289      IMoveMaker oldMoveMaker = MoveMaker;
290      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
291      ClearMoveParameters();
292      if (MoveGenerator != null) {
293        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
294        foreach (Type type in moveTypes.ToList()) {
295          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
296            moveTypes.Remove(type);
297        }
298        foreach (Type type in moveTypes) {
299          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
300          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
301            MoveMakerParameter.ValidValues.Add(moveMaker);
302          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
303            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
304        }
305        if (oldMoveMaker != null) {
306          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
307          if (mm != null) MoveMaker = mm;
308        }
309        if (oldMoveEvaluator != null) {
310          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
311          if (me != null) MoveEvaluator = me;
312        }
313      }
314    }
315    private void UpdateAnalyzers() {
316      Analyzer.Operators.Clear();
317      MoveAnalyzer.Operators.Clear();
318      MoveAnalyzer.Operators.Add(moveQualityAnalyzer);
319      if (Problem != null) {
320        foreach (ISolutionAnalyzer analyzer in Problem.Operators.OfType<ISolutionAnalyzer>().OrderBy(x => x.Name))
321          Analyzer.Operators.Add(analyzer);
322      }
323    }
324    private void ClearMoveParameters() {
325      MoveMakerParameter.ValidValues.Clear();
326      MoveEvaluatorParameter.ValidValues.Clear();
327    }
328    private void ParameterizeSolutionsCreator() {
329      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
330      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
331    }
332    private void ParameterizeMainLoop() {
333      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
334      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
335      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
336      if (MoveEvaluator != null)
337        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
338    }
339    private void ParameterizeStochasticOperator(IOperator op) {
340      if (op is IStochasticOperator)
341        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
342    }
343    private void ParameterizeMoveEvaluators() {
344      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
345        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
346      }
347    }
348    private void ParameterizeMoveMakers() {
349      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
350        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
351        if (MoveEvaluator != null)
352          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
353      }
354    }
355    private void ParameterizeAnalyzers() {
356      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
357      if (Problem != null) {
358        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
359        if (MoveEvaluator != null)
360          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
361        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
362      }
363    }
364    #endregion
365  }
366}
Note: See TracBrowser for help on using the repository browser.