Free cookie consent management tool by TermsFeed Policy Generator

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

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

Sorted usings and removed unused usings in entire solution (#1094)

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