Free cookie consent management tool by TermsFeed Policy Generator

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

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

Merged cloning refactoring branch back into trunk (#922)

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