Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3694 was 3689, checked in by abeham, 15 years ago

#893

  • fixed wiring in the algorithms
File size: 17.4 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> MoveAnalyzerParameter {
75      get { return (ValueParameter<MultiAnalyzer>)Parameters["MoveAnalyzer"]; }
[3621]76    }
[3658]77    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
78      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
[3621]79    }
[3078]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    }
[3187]107    public IntValue SampleSize {
108      get { return SampleSizeParameter.Value; }
109      set { SampleSizeParameter.Value = value; }
110    }
[3658]111    public MultiAnalyzer MoveAnalyzer {
[3621]112      get { return MoveAnalyzerParameter.Value; }
113      set { MoveAnalyzerParameter.Value = value; }
114    }
[3658]115    public MultiAnalyzer Analyzer {
[3621]116      get { return AnalyzerParameter.Value; }
117      set { AnalyzerParameter.Value = value; }
118    }
[3078]119    private RandomCreator RandomCreator {
120      get { return (RandomCreator)OperatorGraph.InitialOperator; }
121    }
122    private SolutionsCreator SolutionsCreator {
123      get { return (SolutionsCreator)RandomCreator.Successor; }
124    }
[3103]125    private LocalSearchMainLoop MainLoop {
126      get { return (LocalSearchMainLoop)SolutionsCreator.Successor; }
[3078]127    }
[3689]128    [Storable]
[3662]129    private BestAverageWorstQualityAnalyzer moveQualityAnalyzer;
[3078]130    #endregion
131
[3621]132    [StorableConstructor]
133    private LocalSearch(bool deserializing) : base(deserializing) { }
[3103]134    public LocalSearch()
[3078]135      : base() {
136      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
137      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
138      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
139      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
140      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
141      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
[3187]142      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
[3658]143      Parameters.Add(new ValueParameter<MultiAnalyzer>("MoveAnalyzer", "The operator used to analyze the moves.", new MultiAnalyzer()));
144      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution.", new MultiAnalyzer()));
[3621]145     
[3078]146      RandomCreator randomCreator = new RandomCreator();
147      SolutionsCreator solutionsCreator = new SolutionsCreator();
[3103]148      LocalSearchMainLoop lsMainLoop = new LocalSearchMainLoop();
[3078]149      OperatorGraph.InitialOperator = randomCreator;
150
151      randomCreator.RandomParameter.ActualName = "Random";
152      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
153      randomCreator.SeedParameter.Value = null;
154      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
155      randomCreator.SetSeedRandomlyParameter.Value = null;
156      randomCreator.Successor = solutionsCreator;
157
158      solutionsCreator.NumberOfSolutions = new IntValue(1);
159      solutionsCreator.Successor = lsMainLoop;
160
161      lsMainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
162      lsMainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
163      lsMainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
164      lsMainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
165      lsMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
166      lsMainLoop.ResultsParameter.ActualName = "Results";
[3621]167      lsMainLoop.MoveAnalyzerParameter.ActualName = MoveAnalyzerParameter.Name;
168      lsMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
[3078]169
[3689]170      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
171      ParameterizeAnalyzers();
172      UpdateAnalyzers();
173
[3078]174      Initialize();
175    }
176
177    public override IDeepCloneable Clone(Cloner cloner) {
[3103]178      LocalSearch clone = (LocalSearch)base.Clone(cloner);
[3689]179      clone.moveQualityAnalyzer = (BestAverageWorstQualityAnalyzer)cloner.Clone(moveQualityAnalyzer);
[3078]180      clone.Initialize();
181      return clone;
182    }
183
[3275]184    public override void Prepare() {
[3265]185      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
[3275]186        base.Prepare();
[3189]187    }
188
[3078]189    #region Events
190    protected override void OnProblemChanged() {
191      ParameterizeStochasticOperator(Problem.SolutionCreator);
192      ParameterizeStochasticOperator(Problem.Evaluator);
193      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
194      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
195        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
196      }
197      ParameterizeSolutionsCreator();
[3134]198      ParameterizeMainLoop();
[3145]199      ParameterizeMoveEvaluators();
200      ParameterizeMoveMakers();
[3621]201      ParameterizeAnalyzers();
[3078]202      UpdateMoveGenerator();
[3187]203      UpdateMoveParameters();
[3621]204      UpdateAnalyzers();
[3078]205      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
206      base.OnProblemChanged();
207    }
208    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
209      ParameterizeStochasticOperator(Problem.SolutionCreator);
210      ParameterizeSolutionsCreator();
211      base.Problem_SolutionCreatorChanged(sender, e);
212    }
213    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
214      ParameterizeStochasticOperator(Problem.Evaluator);
215      ParameterizeSolutionsCreator();
[3134]216      ParameterizeMainLoop();
[3145]217      ParameterizeMoveEvaluators();
218      ParameterizeMoveMakers();
[3621]219      ParameterizeAnalyzers();
[3078]220      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
221      base.Problem_EvaluatorChanged(sender, e);
222    }
223    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
224      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
225      // This may seem pointless, but some operators already have the eventhandler registered, others don't
226      // FIXME: Is there another way to solve this problem?
227      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
228        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
229        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
230      }
231      UpdateMoveGenerator();
[3187]232      UpdateMoveParameters();
[3621]233      UpdateAnalyzers();
[3134]234      ParameterizeMainLoop();
[3145]235      ParameterizeMoveEvaluators();
236      ParameterizeMoveMakers();
[3636]237      ParameterizeAnalyzers();
[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    [StorableHook(HookType.AfterDeserialization)]
264    private void Initialize() {
265      if (Problem != null) {
266        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
267        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
268          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
269        }
270      }
271      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
272      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
273    }
274    private void UpdateMoveGenerator() {
275      IMoveGenerator oldMoveGenerator = MoveGenerator;
276      MoveGeneratorParameter.ValidValues.Clear();
277      if (Problem != null) {
278        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
279          MoveGeneratorParameter.ValidValues.Add(generator);
280      }
[3145]281      if (oldMoveGenerator != null) {
282        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
283        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
284      }
[3078]285      if (MoveGenerator == null) {
286        ClearMoveParameters();
287      }
288    }
289    private void UpdateMoveParameters() {
290      IMoveMaker oldMoveMaker = MoveMaker;
291      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
292      ClearMoveParameters();
[3131]293      if (MoveGenerator != null) {
294        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
295        foreach (Type type in moveTypes.ToList()) {
296          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
297            moveTypes.Remove(type);
298        }
299        foreach (Type type in moveTypes) {
300          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
301          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
302            MoveMakerParameter.ValidValues.Add(moveMaker);
303          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
304            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
305        }
306        if (oldMoveMaker != null) {
307          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
308          if (mm != null) MoveMaker = mm;
309        }
310        if (oldMoveEvaluator != null) {
311          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
312          if (me != null) MoveEvaluator = me;
313        }
[3078]314      }
315    }
[3621]316    private void UpdateAnalyzers() {
317      Analyzer.Operators.Clear();
318      MoveAnalyzer.Operators.Clear();
319      MoveAnalyzer.Operators.Add(moveQualityAnalyzer);
[3626]320      if (Problem != null) {
[3669]321        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>().OrderBy(x => x.Name)) {
322          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
323            param.Depth = 0;
[3621]324          Analyzer.Operators.Add(analyzer);
[3669]325        }
[3626]326      }
[3621]327    }
[3078]328    private void ClearMoveParameters() {
329      MoveMakerParameter.ValidValues.Clear();
330      MoveEvaluatorParameter.ValidValues.Clear();
331    }
332    private void ParameterizeSolutionsCreator() {
333      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
334      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
335    }
[3134]336    private void ParameterizeMainLoop() {
[3145]337      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[3103]338      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
339      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[3078]340      if (MoveEvaluator != null)
[3103]341        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
[3078]342    }
343    private void ParameterizeStochasticOperator(IOperator op) {
344      if (op is IStochasticOperator)
345        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
346    }
[3145]347    private void ParameterizeMoveEvaluators() {
[3078]348      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
349        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
350      }
351    }
[3145]352    private void ParameterizeMoveMakers() {
[3078]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    }
[3621]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    }
[3078]368    #endregion
369  }
370}
Note: See TracBrowser for help on using the repository browser.