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

Last change on this file since 3671 was 3671, checked in by abeham, 12 years ago

#999

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