Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4437 was 4437, checked in by swagner, 13 years ago

Implemented !IStorableContent separately for each algorithm (#1193)

File size: 20.0 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    public SimulatedAnnealing()
146      : base() {
147      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
148      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
149      Parameters.Add(new ConstrainedValueParameter<IMultiMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
150      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
151      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
152      Parameters.Add(new ConstrainedValueParameter<IDiscreteDoubleValueModifier>("AnnealingOperator", "The operator used to modify the temperature."));
153      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(100)));
154      Parameters.Add(new ValueParameter<IntValue>("InnerIterations", "The amount of inner iterations (number of moves before temperature is adjusted again).", new IntValue(10)));
155      Parameters.Add(new ValueParameter<DoubleValue>("StartTemperature", "The initial temperature.", new DoubleValue(100)));
156      Parameters.Add(new ValueParameter<DoubleValue>("EndTemperature", "The final temperature which should be reached when iterations reaches maximum iterations.", new DoubleValue(1e-6)));
157      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
158
159      RandomCreator randomCreator = new RandomCreator();
160      SolutionsCreator solutionsCreator = new SolutionsCreator();
161      SimulatedAnnealingMainLoop mainLoop = new SimulatedAnnealingMainLoop();
162      OperatorGraph.InitialOperator = randomCreator;
163
164      randomCreator.RandomParameter.ActualName = "Random";
165      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
166      randomCreator.SeedParameter.Value = null;
167      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
168      randomCreator.SetSeedRandomlyParameter.Value = null;
169      randomCreator.Successor = solutionsCreator;
170
171      solutionsCreator.NumberOfSolutions = new IntValue(1);
172      solutionsCreator.Successor = mainLoop;
173
174      mainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
175      mainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
176      mainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
177      mainLoop.AnnealingOperatorParameter.ActualName = AnnealingOperatorParameter.Name;
178      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
179      mainLoop.StartTemperatureParameter.ActualName = StartTemperatureParameter.Name;
180      mainLoop.EndTemperatureParameter.ActualName = EndTemperatureParameter.Name;
181      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
182      mainLoop.ResultsParameter.ActualName = "Results";
183      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
184
185      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
186        AnnealingOperatorParameter.ValidValues.Add(op);
187      ParameterizeAnnealingOperators();
188
189      qualityAnalyzer = new QualityAnalyzer();
190      ParameterizeAnalyzers();
191      UpdateAnalyzers();
192
193      Initialize();
194    }
195
196    public override IDeepCloneable Clone(Cloner cloner) {
197      SimulatedAnnealing clone = (SimulatedAnnealing)base.Clone(cloner);
198      clone.qualityAnalyzer = (QualityAnalyzer)cloner.Clone(qualityAnalyzer);
199      clone.Initialize();
200      return clone;
201    }
202
203    public override void Prepare() {
204      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
205        base.Prepare();
206    }
207
208    #region Events
209    protected override void OnProblemChanged() {
210      ParameterizeStochasticOperator(Problem.SolutionCreator);
211      ParameterizeStochasticOperator(Problem.Evaluator);
212      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
213      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
214        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
215      }
216      ParameterizeSolutionsCreator();
217      ParameterizeMainLoop();
218      UpdateMoveGenerator();
219      UpdateMoveParameters();
220      UpdateAnalyzers();
221      ParameterizeMoveEvaluators();
222      ParameterizeMoveMakers();
223      ParameterizeMoveGenerators();
224      ParameterizeAnalyzers();
225      ParameterizeIterationBasedOperators();
226      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
227      base.OnProblemChanged();
228    }
229    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
230      ParameterizeStochasticOperator(Problem.SolutionCreator);
231      ParameterizeSolutionsCreator();
232      base.Problem_SolutionCreatorChanged(sender, e);
233    }
234    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
235      ParameterizeStochasticOperator(Problem.Evaluator);
236      ParameterizeSolutionsCreator();
237      ParameterizeMainLoop();
238      ParameterizeMoveEvaluators();
239      ParameterizeMoveMakers();
240      ParameterizeAnalyzers();
241      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
242      base.Problem_EvaluatorChanged(sender, e);
243    }
244    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
245      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
246      // This may seem pointless, but some operators already have the eventhandler registered, others don't
247      // FIXME: Is there another way to solve this problem?
248      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
249        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
250        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
251      }
252      UpdateMoveGenerator();
253      UpdateMoveParameters();
254      UpdateAnalyzers();
255      ParameterizeMainLoop();
256      ParameterizeMoveEvaluators();
257      ParameterizeMoveMakers();
258      ParameterizeMoveGenerators();
259      ParameterizeIterationBasedOperators();
260      base.Problem_OperatorsChanged(sender, e);
261    }
262    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
263      ParameterizeMainLoop();
264      ParameterizeMoveEvaluators();
265      ParameterizeMoveMakers();
266      ParameterizeAnalyzers();
267    }
268    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
269      UpdateMoveParameters();
270    }
271    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
272      ParameterizeMainLoop();
273      ParameterizeMoveEvaluators();
274      ParameterizeMoveMakers();
275    }
276    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
277      ParameterizeMainLoop();
278      ParameterizeMoveEvaluators();
279      ParameterizeMoveMakers();
280    }
281    #endregion
282
283    #region Helpers
284    [StorableHook(HookType.AfterDeserialization)]
285    private void Initialize() {
286      if (Problem != null) {
287        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
288        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
289          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
290        }
291      }
292      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
293      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
294    }
295    private void UpdateMoveGenerator() {
296      IMultiMoveGenerator oldMoveGenerator = MoveGenerator;
297      MoveGeneratorParameter.ValidValues.Clear();
298      if (Problem != null) {
299        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>().OrderBy(x => x.Name))
300          MoveGeneratorParameter.ValidValues.Add(generator);
301      }
302      if (oldMoveGenerator != null) {
303        IMultiMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
304        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
305      }
306      if (MoveGenerator == null) {
307        ClearMoveParameters();
308      }
309    }
310    private void ParameterizeAnalyzers() {
311      qualityAnalyzer.ResultsParameter.ActualName = "Results";
312      if (Problem != null) {
313        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
314        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
315        qualityAnalyzer.QualityParameter.Depth = 0;
316        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
317      }
318    }
319    private void UpdateMoveParameters() {
320      IMoveMaker oldMoveMaker = MoveMaker;
321      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
322      ClearMoveParameters();
323      if (MoveGenerator != null) {
324        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
325        foreach (Type type in moveTypes.ToList()) {
326          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
327            moveTypes.Remove(type);
328        }
329        foreach (Type type in moveTypes) {
330          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
331          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
332            MoveMakerParameter.ValidValues.Add(moveMaker);
333          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
334            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
335        }
336        if (oldMoveMaker != null) {
337          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
338          if (mm != null) MoveMaker = mm;
339        }
340        if (oldMoveEvaluator != null) {
341          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
342          if (me != null) MoveEvaluator = me;
343        }
344      }
345    }
346    private void ClearMoveParameters() {
347      MoveMakerParameter.ValidValues.Clear();
348      MoveEvaluatorParameter.ValidValues.Clear();
349    }
350    private void ParameterizeSolutionsCreator() {
351      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
352      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
353    }
354    private void ParameterizeMainLoop() {
355      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
356      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
357      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
358      if (MoveEvaluator != null)
359        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
360    }
361    private void ParameterizeStochasticOperator(IOperator op) {
362      if (op is IStochasticOperator)
363        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
364    }
365    private void ParameterizeMoveEvaluators() {
366      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
367        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
368      }
369    }
370    private void ParameterizeMoveMakers() {
371      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
372        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
373        if (MoveEvaluator != null)
374          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
375      }
376    }
377    private void ParameterizeAnnealingOperators() {
378      foreach (IDiscreteDoubleValueModifier op in AnnealingOperatorParameter.ValidValues) {
379        op.IndexParameter.ActualName = "Iterations";
380        op.StartIndexParameter.Value = new IntValue(0);
381        op.EndIndexParameter.ActualName = MaximumIterationsParameter.Name;
382        op.ValueParameter.ActualName = "Temperature";
383        op.StartValueParameter.ActualName = StartTemperatureParameter.Name;
384        op.EndValueParameter.ActualName = EndTemperatureParameter.Name;
385        ParameterizeStochasticOperator(op);
386      }
387    }
388    private void ParameterizeMoveGenerators() {
389      foreach (IMultiMoveGenerator op in Problem.Operators.OfType<IMultiMoveGenerator>()) {
390        op.SampleSizeParameter.ActualName = InnerIterationsParameter.Name;
391      }
392    }
393    private void ParameterizeIterationBasedOperators() {
394      if (Problem != null) {
395        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
396          op.IterationsParameter.ActualName = "Iterations";
397          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
398        }
399      }
400    }
401    private void UpdateAnalyzers() {
402      Analyzer.Operators.Clear();
403      if (Problem != null) {
404        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
405          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
406            param.Depth = 0;
407          Analyzer.Operators.Add(analyzer);
408        }
409      }
410      Analyzer.Operators.Add(qualityAnalyzer);
411    }
412    #endregion
413  }
414}
Note: See TracBrowser for help on using the repository browser.