Free cookie consent management tool by TermsFeed Policy Generator

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

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

Removed sorting of analyzer provided by problems (#893)

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