Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.LocalSearch/3.3/LocalSearch.cs @ 3201

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

Added missing StorableClass attributes (#548).

File size: 15.7 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.LocalSearch {
35  [Item("LocalSearch", "A local search algorithm.")]
36  [Creatable("Algorithms")]
37  [StorableClass]
38  public sealed class LocalSearch : 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<IMoveGenerator> MoveGeneratorParameter {
57      get { return (ConstrainedValueParameter<IMoveGenerator>)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 ValueParameter<IntValue> MaximumIterationsParameter {
66      get { return (ValueParameter<IntValue>)Parameters["MaximumIterations"]; }
67    }
68    private ValueParameter<IntValue> SampleSizeParameter {
69      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
70    }
71    #endregion
72
73    #region Properties
74    public IntValue Seed {
75      get { return SeedParameter.Value; }
76      set { SeedParameter.Value = value; }
77    }
78    public BoolValue SetSeedRandomly {
79      get { return SetSeedRandomlyParameter.Value; }
80      set { SetSeedRandomlyParameter.Value = value; }
81    }
82    public IMoveGenerator MoveGenerator {
83      get { return MoveGeneratorParameter.Value; }
84      set { MoveGeneratorParameter.Value = value; }
85    }
86    public IMoveMaker MoveMaker {
87      get { return MoveMakerParameter.Value; }
88      set { MoveMakerParameter.Value = value; }
89    }
90    public ISingleObjectiveMoveEvaluator MoveEvaluator {
91      get { return MoveEvaluatorParameter.Value; }
92      set { MoveEvaluatorParameter.Value = value; }
93    }
94    public IntValue MaximumIterations {
95      get { return MaximumIterationsParameter.Value; }
96      set { MaximumIterationsParameter.Value = value; }
97    }
98    public IntValue SampleSize {
99      get { return SampleSizeParameter.Value; }
100      set { SampleSizeParameter.Value = value; }
101    }
102    private RandomCreator RandomCreator {
103      get { return (RandomCreator)OperatorGraph.InitialOperator; }
104    }
105    private SolutionsCreator SolutionsCreator {
106      get { return (SolutionsCreator)RandomCreator.Successor; }
107    }
108    private LocalSearchMainLoop MainLoop {
109      get { return (LocalSearchMainLoop)SolutionsCreator.Successor; }
110    }
111    #endregion
112
113    [StorableConstructor]
114    private LocalSearch(bool deserializing) : base() { }
115    public LocalSearch()
116      : base() {
117      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
118      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
119      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
120      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
121      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
122      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
123      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
124
125      RandomCreator randomCreator = new RandomCreator();
126      SolutionsCreator solutionsCreator = new SolutionsCreator();
127      LocalSearchMainLoop lsMainLoop = new LocalSearchMainLoop();
128      OperatorGraph.InitialOperator = randomCreator;
129
130      randomCreator.RandomParameter.ActualName = "Random";
131      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
132      randomCreator.SeedParameter.Value = null;
133      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
134      randomCreator.SetSeedRandomlyParameter.Value = null;
135      randomCreator.Successor = solutionsCreator;
136
137      solutionsCreator.NumberOfSolutions = new IntValue(1);
138      solutionsCreator.Successor = lsMainLoop;
139
140      lsMainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
141      lsMainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
142      lsMainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
143      lsMainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
144      lsMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
145      lsMainLoop.ResultsParameter.ActualName = "Results";
146
147      Initialize();
148    }
149
150    public override IDeepCloneable Clone(Cloner cloner) {
151      LocalSearch clone = (LocalSearch)base.Clone(cloner);
152      clone.Initialize();
153      return clone;
154    }
155
156    protected override void OnPrepared() {
157      base.OnPrepared();
158      if (Engine != null) {
159        if (Problem == null || MoveGenerator == null || MoveMaker == null || MoveEvaluator == null)
160          Engine.Prepare(null);
161      }
162    }
163
164    #region Events
165    protected override void OnProblemChanged() {
166      ParameterizeStochasticOperator(Problem.SolutionCreator);
167      ParameterizeStochasticOperator(Problem.Evaluator);
168      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
169      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
170        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
171      }
172      ParameterizeSolutionsCreator();
173      ParameterizeMainLoop();
174      ParameterizeMoveEvaluators();
175      ParameterizeMoveMakers();
176      UpdateMoveGenerator();
177      UpdateMoveParameters();
178      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
179      base.OnProblemChanged();
180    }
181    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
182      ParameterizeStochasticOperator(Problem.SolutionCreator);
183      ParameterizeSolutionsCreator();
184      base.Problem_SolutionCreatorChanged(sender, e);
185    }
186    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
187      ParameterizeStochasticOperator(Problem.Evaluator);
188      ParameterizeSolutionsCreator();
189      ParameterizeMainLoop();
190      ParameterizeMoveEvaluators();
191      ParameterizeMoveMakers();
192      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
193      base.Problem_EvaluatorChanged(sender, e);
194    }
195    protected override void Problem_VisualizerChanged(object sender, EventArgs e) {
196      ParameterizeStochasticOperator(Problem.Visualizer);
197      ParameterizeMainLoop();
198      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
199      base.Problem_VisualizerChanged(sender, e);
200    }
201    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
202      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
203      // This may seem pointless, but some operators already have the eventhandler registered, others don't
204      // FIXME: Is there another way to solve this problem?
205      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
206        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
207        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
208      }
209      UpdateMoveGenerator();
210      UpdateMoveParameters();
211      ParameterizeMainLoop();
212      ParameterizeMoveEvaluators();
213      ParameterizeMoveMakers();
214      base.Problem_OperatorsChanged(sender, e);
215    }
216    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
217      ParameterizeMainLoop();
218      ParameterizeMoveEvaluators();
219      ParameterizeMoveMakers();
220    }
221    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
222      UpdateMoveParameters();
223    }
224    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
225      ParameterizeMainLoop();
226      ParameterizeMoveEvaluators();
227      ParameterizeMoveMakers();
228    }
229    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
230      ParameterizeMainLoop();
231      ParameterizeMoveEvaluators();
232      ParameterizeMoveMakers();
233    }
234    private void Visualizer_VisualizationParameter_ActualNameChanged(object sender, EventArgs e) {
235      ParameterizeMainLoop();
236    }
237    #endregion
238
239    #region Helpers
240    [StorableHook(HookType.AfterDeserialization)]
241    private void Initialize() {
242      if (Problem != null) {
243        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
244        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
245          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
246        }
247      }
248      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
249      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
250    }
251    private void UpdateMoveGenerator() {
252      IMoveGenerator oldMoveGenerator = MoveGenerator;
253      MoveGeneratorParameter.ValidValues.Clear();
254      if (Problem != null) {
255        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
256          MoveGeneratorParameter.ValidValues.Add(generator);
257      }
258      if (oldMoveGenerator != null) {
259        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
260        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
261      }
262      if (MoveGenerator == null) {
263        ClearMoveParameters();
264      }
265    }
266    private void UpdateMoveParameters() {
267      IMoveMaker oldMoveMaker = MoveMaker;
268      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
269      ClearMoveParameters();
270      if (MoveGenerator != null) {
271        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
272        foreach (Type type in moveTypes.ToList()) {
273          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
274            moveTypes.Remove(type);
275        }
276        foreach (Type type in moveTypes) {
277          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
278          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
279            MoveMakerParameter.ValidValues.Add(moveMaker);
280          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
281            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
282        }
283        if (oldMoveMaker != null) {
284          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
285          if (mm != null) MoveMaker = mm;
286        }
287        if (oldMoveEvaluator != null) {
288          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
289          if (me != null) MoveEvaluator = me;
290        }
291      }
292    }
293    private void ClearMoveParameters() {
294      MoveMakerParameter.ValidValues.Clear();
295      MoveEvaluatorParameter.ValidValues.Clear();
296    }
297    private void ParameterizeSolutionsCreator() {
298      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
299      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
300    }
301    private void ParameterizeMainLoop() {
302      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
303      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
304      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
305      if (MoveEvaluator != null)
306        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
307      MainLoop.VisualizerParameter.ActualName = Problem.VisualizerParameter.Name;
308      if (Problem.Visualizer != null)
309        MainLoop.VisualizationParameter.ActualName = Problem.Visualizer.VisualizationParameter.ActualName;
310    }
311    private void ParameterizeStochasticOperator(IOperator op) {
312      if (op is IStochasticOperator)
313        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
314    }
315    private void ParameterizeMoveEvaluators() {
316      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
317        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
318      }
319    }
320    private void ParameterizeMoveMakers() {
321      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
322        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
323        if (MoveEvaluator != null)
324          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
325      }
326    }
327    #endregion
328  }
329}
Note: See TracBrowser for help on using the repository browser.