Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.SimulatedAnnealing/3.3/SimulatedAnnealing.cs @ 5370

Last change on this file since 5370 was 5366, checked in by abeham, 14 years ago

#1344

  • Fixed discovery of the main loop operator in the MainLoop property
File size: 21.1 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.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Random;
36
37namespace HeuristicLab.Algorithms.SimulatedAnnealing {
38  [Item("Simulated Annealing", "A simulated annealing algorithm.")]
39  [Creatable("Algorithms")]
40  [StorableClass]
41  public sealed class SimulatedAnnealing : EngineAlgorithm, IStorableContent {
42    public string Filename { get; set; }
43
44    #region Problem Properties
45    public override Type ProblemType {
46      get { return typeof(ISingleObjectiveProblem); }
47    }
48    public new ISingleObjectiveProblem Problem {
49      get { return (ISingleObjectiveProblem)base.Problem; }
50      set { base.Problem = value; }
51    }
52    #endregion
53
54    #region Parameter Properties
55    private ValueParameter<IntValue> SeedParameter {
56      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
57    }
58    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
59      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
60    }
61    private ConstrainedValueParameter<IMultiMoveGenerator> MoveGeneratorParameter {
62      get { return (ConstrainedValueParameter<IMultiMoveGenerator>)Parameters["MoveGenerator"]; }
63    }
64    private ConstrainedValueParameter<IMoveMaker> MoveMakerParameter {
65      get { return (ConstrainedValueParameter<IMoveMaker>)Parameters["MoveMaker"]; }
66    }
67    private ConstrainedValueParameter<ISingleObjectiveMoveEvaluator> MoveEvaluatorParameter {
68      get { return (ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>)Parameters["MoveEvaluator"]; }
69    }
70    private ConstrainedValueParameter<IDiscreteDoubleValueModifier> AnnealingOperatorParameter {
71      get { return (ConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["AnnealingOperator"]; }
72    }
73    private ValueParameter<IntValue> MaximumIterationsParameter {
74      get { return (ValueParameter<IntValue>)Parameters["MaximumIterations"]; }
75    }
76    private ValueParameter<IntValue> InnerIterationsParameter {
77      get { return (ValueParameter<IntValue>)Parameters["InnerIterations"]; }
78    }
79    private ValueParameter<DoubleValue> StartTemperatureParameter {
80      get { return (ValueParameter<DoubleValue>)Parameters["StartTemperature"]; }
81    }
82    private ValueParameter<DoubleValue> EndTemperatureParameter {
83      get { return (ValueParameter<DoubleValue>)Parameters["EndTemperature"]; }
84    }
85    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
86      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
87    }
88    #endregion
89
90    #region Properties
91    public IntValue Seed {
92      get { return SeedParameter.Value; }
93      set { SeedParameter.Value = value; }
94    }
95    public BoolValue SetSeedRandomly {
96      get { return SetSeedRandomlyParameter.Value; }
97      set { SetSeedRandomlyParameter.Value = value; }
98    }
99    public IMultiMoveGenerator MoveGenerator {
100      get { return MoveGeneratorParameter.Value; }
101      set { MoveGeneratorParameter.Value = value; }
102    }
103    public IMoveMaker MoveMaker {
104      get { return MoveMakerParameter.Value; }
105      set { MoveMakerParameter.Value = value; }
106    }
107    public ISingleObjectiveMoveEvaluator MoveEvaluator {
108      get { return MoveEvaluatorParameter.Value; }
109      set { MoveEvaluatorParameter.Value = value; }
110    }
111    public IntValue MaximumIterations {
112      get { return MaximumIterationsParameter.Value; }
113      set { MaximumIterationsParameter.Value = value; }
114    }
115    public IntValue InnerIterations {
116      get { return InnerIterationsParameter.Value; }
117      set { InnerIterationsParameter.Value = value; }
118    }
119    public DoubleValue StartTemperature {
120      get { return StartTemperatureParameter.Value; }
121      set { StartTemperatureParameter.Value = value; }
122    }
123    public DoubleValue EndTemperature {
124      get { return EndTemperatureParameter.Value; }
125      set { EndTemperatureParameter.Value = value; }
126    }
127    public MultiAnalyzer Analyzer {
128      get { return AnalyzerParameter.Value; }
129      set { AnalyzerParameter.Value = value; }
130    }
131    private RandomCreator RandomCreator {
132      get { return (RandomCreator)OperatorGraph.InitialOperator; }
133    }
134    private SolutionsCreator SolutionsCreator {
135      get { return (SolutionsCreator)RandomCreator.Successor; }
136    }
137    private SimulatedAnnealingMainLoop MainLoop {
138      get { return FindMainLoop(SolutionsCreator.Successor); }
139    }
140    [Storable]
141    private QualityAnalyzer qualityAnalyzer;
142    #endregion
143
144    [StorableConstructor]
145    private SimulatedAnnealing(bool deserializing) : base(deserializing) { }
146    [StorableHook(HookType.AfterDeserialization)]
147    private void AfterDeserialization() {
148      Initialize();
149    }
150    private SimulatedAnnealing(SimulatedAnnealing original, Cloner cloner)
151      : base(original, cloner) {
152      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
153      Initialize();
154    }
155    public override IDeepCloneable Clone(Cloner cloner) {
156      return new SimulatedAnnealing(this, cloner);
157    }
158    public SimulatedAnnealing()
159      : base() {
160      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
161      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
162      Parameters.Add(new ConstrainedValueParameter<IMultiMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
163      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
164      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
165      Parameters.Add(new ConstrainedValueParameter<IDiscreteDoubleValueModifier>("AnnealingOperator", "The operator used to modify the temperature."));
166      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(100)));
167      Parameters.Add(new ValueParameter<IntValue>("InnerIterations", "The amount of inner iterations (number of moves before temperature is adjusted again).", new IntValue(10)));
168      Parameters.Add(new ValueParameter<DoubleValue>("StartTemperature", "The initial temperature.", new DoubleValue(100)));
169      Parameters.Add(new ValueParameter<DoubleValue>("EndTemperature", "The final temperature which should be reached when iterations reaches maximum iterations.", new DoubleValue(1e-6)));
170      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
171
172      RandomCreator randomCreator = new RandomCreator();
173      SolutionsCreator solutionsCreator = new SolutionsCreator();
174      VariableCreator variableCreator = new VariableCreator();
175      ResultsCollector resultsCollector = new ResultsCollector();
176      SimulatedAnnealingMainLoop mainLoop = new SimulatedAnnealingMainLoop();
177      OperatorGraph.InitialOperator = randomCreator;
178
179      randomCreator.RandomParameter.ActualName = "Random";
180      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
181      randomCreator.SeedParameter.Value = null;
182      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
183      randomCreator.SetSeedRandomlyParameter.Value = null;
184      randomCreator.Successor = solutionsCreator;
185
186      solutionsCreator.NumberOfSolutions = new IntValue(1);
187      solutionsCreator.Successor = variableCreator;
188
189      variableCreator.Name = "Initialize EvaluatedMoves";
190      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedMoves", new IntValue()));
191      variableCreator.Successor = resultsCollector;
192
193      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Moves", null, "EvaluatedMoves"));
194      resultsCollector.ResultsParameter.ActualName = "Results";
195      resultsCollector.Successor = mainLoop;
196
197      mainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
198      mainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
199      mainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
200      mainLoop.AnnealingOperatorParameter.ActualName = AnnealingOperatorParameter.Name;
201      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
202      mainLoop.StartTemperatureParameter.ActualName = StartTemperatureParameter.Name;
203      mainLoop.EndTemperatureParameter.ActualName = EndTemperatureParameter.Name;
204      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
205      mainLoop.ResultsParameter.ActualName = "Results";
206      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
207      mainLoop.EvaluatedMovesParameter.ActualName = "EvaluatedMoves";
208
209      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
210        AnnealingOperatorParameter.ValidValues.Add(op);
211      ParameterizeAnnealingOperators();
212
213      qualityAnalyzer = new QualityAnalyzer();
214      ParameterizeAnalyzers();
215      UpdateAnalyzers();
216
217      Initialize();
218    }
219
220    public override void Prepare() {
221      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
222        base.Prepare();
223    }
224
225    #region Events
226    protected override void OnProblemChanged() {
227      ParameterizeStochasticOperator(Problem.SolutionCreator);
228      ParameterizeStochasticOperator(Problem.Evaluator);
229      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
230      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
231        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
232      }
233      ParameterizeSolutionsCreator();
234      ParameterizeMainLoop();
235      UpdateMoveGenerator();
236      UpdateMoveParameters();
237      UpdateAnalyzers();
238      ParameterizeMoveEvaluators();
239      ParameterizeMoveMakers();
240      ParameterizeMoveGenerators();
241      ParameterizeAnalyzers();
242      ParameterizeIterationBasedOperators();
243      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
244      base.OnProblemChanged();
245    }
246    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
247      ParameterizeStochasticOperator(Problem.SolutionCreator);
248      ParameterizeSolutionsCreator();
249      base.Problem_SolutionCreatorChanged(sender, e);
250    }
251    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
252      ParameterizeStochasticOperator(Problem.Evaluator);
253      ParameterizeSolutionsCreator();
254      ParameterizeMainLoop();
255      ParameterizeMoveEvaluators();
256      ParameterizeMoveMakers();
257      ParameterizeAnalyzers();
258      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
259      base.Problem_EvaluatorChanged(sender, e);
260    }
261    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
262      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
263      // This may seem pointless, but some operators already have the eventhandler registered, others don't
264      // FIXME: Is there another way to solve this problem?
265      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
266        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
267        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
268      }
269      UpdateMoveGenerator();
270      UpdateMoveParameters();
271      UpdateAnalyzers();
272      ParameterizeMainLoop();
273      ParameterizeMoveEvaluators();
274      ParameterizeMoveMakers();
275      ParameterizeMoveGenerators();
276      ParameterizeIterationBasedOperators();
277      base.Problem_OperatorsChanged(sender, e);
278    }
279    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
280      ParameterizeMainLoop();
281      ParameterizeMoveEvaluators();
282      ParameterizeMoveMakers();
283      ParameterizeAnalyzers();
284    }
285    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
286      UpdateMoveParameters();
287    }
288    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
289      ParameterizeMainLoop();
290      ParameterizeMoveEvaluators();
291      ParameterizeMoveMakers();
292    }
293    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
294      ParameterizeMainLoop();
295      ParameterizeMoveEvaluators();
296      ParameterizeMoveMakers();
297    }
298    #endregion
299
300    #region Helpers
301    private void Initialize() {
302      if (Problem != null) {
303        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
304        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
305          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
306        }
307      }
308      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
309      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
310    }
311    private void UpdateMoveGenerator() {
312      IMultiMoveGenerator oldMoveGenerator = MoveGenerator;
313      MoveGeneratorParameter.ValidValues.Clear();
314      if (Problem != null) {
315        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>().OrderBy(x => x.Name))
316          MoveGeneratorParameter.ValidValues.Add(generator);
317      }
318      if (oldMoveGenerator != null) {
319        IMultiMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
320        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
321      }
322      if (MoveGenerator == null) {
323        ClearMoveParameters();
324      }
325    }
326    private void ParameterizeAnalyzers() {
327      qualityAnalyzer.ResultsParameter.ActualName = "Results";
328      if (Problem != null) {
329        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
330        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
331        qualityAnalyzer.QualityParameter.Depth = 0;
332        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
333      }
334    }
335    private void UpdateMoveParameters() {
336      IMoveMaker oldMoveMaker = MoveMaker;
337      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
338      ClearMoveParameters();
339      if (MoveGenerator != null) {
340        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
341        foreach (Type type in moveTypes.ToList()) {
342          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
343            moveTypes.Remove(type);
344        }
345        foreach (Type type in moveTypes) {
346          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
347          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
348            MoveMakerParameter.ValidValues.Add(moveMaker);
349          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
350            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
351        }
352        if (oldMoveMaker != null) {
353          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
354          if (mm != null) MoveMaker = mm;
355        }
356        if (oldMoveEvaluator != null) {
357          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
358          if (me != null) MoveEvaluator = me;
359        }
360      }
361    }
362    private void ClearMoveParameters() {
363      MoveMakerParameter.ValidValues.Clear();
364      MoveEvaluatorParameter.ValidValues.Clear();
365    }
366    private void ParameterizeSolutionsCreator() {
367      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
368      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
369    }
370    private void ParameterizeMainLoop() {
371      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
372      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
373      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
374      if (MoveEvaluator != null)
375        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
376    }
377    private void ParameterizeStochasticOperator(IOperator op) {
378      if (op is IStochasticOperator)
379        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
380    }
381    private void ParameterizeMoveEvaluators() {
382      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
383        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
384      }
385    }
386    private void ParameterizeMoveMakers() {
387      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
388        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
389        if (MoveEvaluator != null)
390          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
391      }
392    }
393    private void ParameterizeAnnealingOperators() {
394      foreach (IDiscreteDoubleValueModifier op in AnnealingOperatorParameter.ValidValues) {
395        op.IndexParameter.ActualName = "Iterations";
396        op.StartIndexParameter.Value = new IntValue(0);
397        op.EndIndexParameter.ActualName = MaximumIterationsParameter.Name;
398        op.ValueParameter.ActualName = "Temperature";
399        op.StartValueParameter.ActualName = StartTemperatureParameter.Name;
400        op.EndValueParameter.ActualName = EndTemperatureParameter.Name;
401        ParameterizeStochasticOperator(op);
402      }
403    }
404    private void ParameterizeMoveGenerators() {
405      foreach (IMultiMoveGenerator op in Problem.Operators.OfType<IMultiMoveGenerator>()) {
406        op.SampleSizeParameter.ActualName = InnerIterationsParameter.Name;
407      }
408    }
409    private void ParameterizeIterationBasedOperators() {
410      if (Problem != null) {
411        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
412          op.IterationsParameter.ActualName = "Iterations";
413          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
414        }
415      }
416    }
417    private void UpdateAnalyzers() {
418      Analyzer.Operators.Clear();
419      if (Problem != null) {
420        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
421          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
422            param.Depth = 0;
423          Analyzer.Operators.Add(analyzer);
424        }
425      }
426      Analyzer.Operators.Add(qualityAnalyzer);
427    }
428    private SimulatedAnnealingMainLoop FindMainLoop(IOperator start) {
429      IOperator mainLoop = start;
430      while (mainLoop != null && !(mainLoop is SimulatedAnnealingMainLoop))
431        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
432      if (mainLoop == null) return null;
433      else return (SimulatedAnnealingMainLoop)mainLoop;
434    }
435    #endregion
436  }
437}
Note: See TracBrowser for help on using the repository browser.