Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3303 was 3303, checked in by swagner, 12 years ago

Removed unnecessary checks if the application manager is not null (#954).

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