Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5142 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 17.7 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;
[4068]25using HeuristicLab.Analysis;
[3376]26using HeuristicLab.Common;
[3078]27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[3368]33using HeuristicLab.Random;
[3078]34
[3103]35namespace HeuristicLab.Algorithms.LocalSearch {
[3280]36  [Item("Local Search", "A local search algorithm.")]
[3078]37  [Creatable("Algorithms")]
[3201]38  [StorableClass]
[4437]39  public sealed class LocalSearch : EngineAlgorithm, IStorableContent {
40    public string Filename { get; set; }
41
[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) { }
[4722]127    [StorableHook(HookType.AfterDeserialization)]
128    private void AfterDeserialization() {
129      Initialize();
130    }
131    private LocalSearch(LocalSearch original, Cloner cloner)
132      : base(original, cloner) {
133      moveQualityAnalyzer = cloner.Clone(original.moveQualityAnalyzer);
134      Initialize();
135    }
136    public override IDeepCloneable Clone(Cloner cloner) {
137      return new LocalSearch(this, cloner);
138    }
[3103]139    public LocalSearch()
[3078]140      : base() {
141      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
142      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
143      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
144      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
145      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
146      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
[3187]147      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
[3809]148      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
[4068]149
[3078]150      RandomCreator randomCreator = new RandomCreator();
151      SolutionsCreator solutionsCreator = new SolutionsCreator();
[3103]152      LocalSearchMainLoop lsMainLoop = new LocalSearchMainLoop();
[3078]153      OperatorGraph.InitialOperator = randomCreator;
154
155      randomCreator.RandomParameter.ActualName = "Random";
156      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
157      randomCreator.SeedParameter.Value = null;
158      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
159      randomCreator.SetSeedRandomlyParameter.Value = null;
160      randomCreator.Successor = solutionsCreator;
161
162      solutionsCreator.NumberOfSolutions = new IntValue(1);
163      solutionsCreator.Successor = lsMainLoop;
164
165      lsMainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
166      lsMainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
167      lsMainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
168      lsMainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
169      lsMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
170      lsMainLoop.ResultsParameter.ActualName = "Results";
[3621]171      lsMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
[3078]172
[3689]173      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
174      ParameterizeAnalyzers();
175      UpdateAnalyzers();
176
[3078]177      Initialize();
178    }
179
[3275]180    public override void Prepare() {
[3265]181      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
[3275]182        base.Prepare();
[3189]183    }
184
[3078]185    #region Events
186    protected override void OnProblemChanged() {
187      ParameterizeStochasticOperator(Problem.SolutionCreator);
188      ParameterizeStochasticOperator(Problem.Evaluator);
189      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
190      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
191        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
192      }
193      ParameterizeSolutionsCreator();
[3134]194      ParameterizeMainLoop();
[3750]195      UpdateMoveGenerator();
196      UpdateMoveParameters();
197      UpdateAnalyzers();
[4048]198      ParameterizeMoveGenerators();
[3145]199      ParameterizeMoveEvaluators();
200      ParameterizeMoveMakers();
[3621]201      ParameterizeAnalyzers();
[3750]202      ParameterizeIterationBasedOperators();
[3078]203      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
204      base.OnProblemChanged();
205    }
206    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
207      ParameterizeStochasticOperator(Problem.SolutionCreator);
208      ParameterizeSolutionsCreator();
209      base.Problem_SolutionCreatorChanged(sender, e);
210    }
211    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
212      ParameterizeStochasticOperator(Problem.Evaluator);
213      ParameterizeSolutionsCreator();
[3134]214      ParameterizeMainLoop();
[3145]215      ParameterizeMoveEvaluators();
216      ParameterizeMoveMakers();
[3621]217      ParameterizeAnalyzers();
[3078]218      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
219      base.Problem_EvaluatorChanged(sender, e);
220    }
221    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
222      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
223      // This may seem pointless, but some operators already have the eventhandler registered, others don't
224      // FIXME: Is there another way to solve this problem?
225      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
226        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
227        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
228      }
229      UpdateMoveGenerator();
[3187]230      UpdateMoveParameters();
[3621]231      UpdateAnalyzers();
[3134]232      ParameterizeMainLoop();
[4048]233      ParameterizeMoveGenerators();
[3145]234      ParameterizeMoveEvaluators();
235      ParameterizeMoveMakers();
[3636]236      ParameterizeAnalyzers();
[3750]237      ParameterizeIterationBasedOperators();
[3078]238      base.Problem_OperatorsChanged(sender, e);
239    }
240    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]241      ParameterizeMainLoop();
[3145]242      ParameterizeMoveEvaluators();
243      ParameterizeMoveMakers();
[3078]244    }
245    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
246      UpdateMoveParameters();
247    }
248    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
[3134]249      ParameterizeMainLoop();
[3145]250      ParameterizeMoveEvaluators();
251      ParameterizeMoveMakers();
[3621]252      ParameterizeAnalyzers();
[3078]253    }
254    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3134]255      ParameterizeMainLoop();
[3145]256      ParameterizeMoveEvaluators();
257      ParameterizeMoveMakers();
[3621]258      ParameterizeAnalyzers();
[3078]259    }
260    #endregion
261
262    #region Helpers
263    private void Initialize() {
264      if (Problem != null) {
265        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
266        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
267          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
268        }
269      }
270      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
271      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
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      }
[3145]280      if (oldMoveGenerator != null) {
281        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
282        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
283      }
[3078]284      if (MoveGenerator == null) {
285        ClearMoveParameters();
286      }
287    }
288    private void UpdateMoveParameters() {
289      IMoveMaker oldMoveMaker = MoveMaker;
290      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
291      ClearMoveParameters();
[3131]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        }
[3078]313      }
314    }
[3621]315    private void UpdateAnalyzers() {
316      Analyzer.Operators.Clear();
[3626]317      if (Problem != null) {
[3816]318        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
[3669]319          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
320            param.Depth = 0;
[3621]321          Analyzer.Operators.Add(analyzer);
[3669]322        }
[3626]323      }
[3809]324      Analyzer.Operators.Add(moveQualityAnalyzer);
[3621]325    }
[3078]326    private void ClearMoveParameters() {
327      MoveMakerParameter.ValidValues.Clear();
328      MoveEvaluatorParameter.ValidValues.Clear();
329    }
330    private void ParameterizeSolutionsCreator() {
331      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
332      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
333    }
[3134]334    private void ParameterizeMainLoop() {
[3145]335      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[3103]336      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
337      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[3078]338      if (MoveEvaluator != null)
[3103]339        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[3078]340    }
341    private void ParameterizeStochasticOperator(IOperator op) {
342      if (op is IStochasticOperator)
343        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
344    }
[4048]345    private void ParameterizeMoveGenerators() {
346      if (Problem != null) {
347        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>())
348          generator.SampleSizeParameter.ActualName = SampleSizeParameter.Name;
349      }
350    }
[3145]351    private void ParameterizeMoveEvaluators() {
[3078]352      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
353        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
354      }
355    }
[3145]356    private void ParameterizeMoveMakers() {
[3078]357      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
358        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
359        if (MoveEvaluator != null)
360          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
361      }
362    }
[3621]363    private void ParameterizeAnalyzers() {
364      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
365      if (Problem != null) {
366        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
367        if (MoveEvaluator != null)
368          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
369        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
370      }
371    }
[3750]372    private void ParameterizeIterationBasedOperators() {
373      if (Problem != null) {
374        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
375          op.IterationsParameter.ActualName = "Iterations";
376          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
377        }
378      }
379    }
[3078]380    #endregion
381  }
382}
Note: See TracBrowser for help on using the repository browser.