Free cookie consent management tool by TermsFeed Policy Generator

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

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

Continued work on algorithm batch processing (#947).

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