Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3155 was 3145, checked in by abeham, 15 years ago

fixed some things in trajectory based algorithms #933

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