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

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

Worked on refactoring of algorithm analysis and tracing (#999)

  • adapted GA and TSP
  • removed stuff related to visualizers
File size: 14.9 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.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.LocalSearch {
37  [Item("Local Search", "A local search algorithm.")]
38  [Creatable("Algorithms")]
39  [StorableClass]
40  public sealed class LocalSearch : EngineAlgorithm {
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    }
58    private ConstrainedValueParameter<IMoveGenerator> MoveGeneratorParameter {
59      get { return (ConstrainedValueParameter<IMoveGenerator>)Parameters["MoveGenerator"]; }
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 ValueParameter<IntValue> MaximumIterationsParameter {
68      get { return (ValueParameter<IntValue>)Parameters["MaximumIterations"]; }
69    }
70    private ValueParameter<IntValue> SampleSizeParameter {
71      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
72    }
73    #endregion
74
75    #region Properties
76    public IntValue Seed {
77      get { return SeedParameter.Value; }
78      set { SeedParameter.Value = value; }
79    }
80    public BoolValue SetSeedRandomly {
81      get { return SetSeedRandomlyParameter.Value; }
82      set { SetSeedRandomlyParameter.Value = value; }
83    }
84    public IMoveGenerator MoveGenerator {
85      get { return MoveGeneratorParameter.Value; }
86      set { MoveGeneratorParameter.Value = value; }
87    }
88    public IMoveMaker MoveMaker {
89      get { return MoveMakerParameter.Value; }
90      set { MoveMakerParameter.Value = value; }
91    }
92    public ISingleObjectiveMoveEvaluator MoveEvaluator {
93      get { return MoveEvaluatorParameter.Value; }
94      set { MoveEvaluatorParameter.Value = value; }
95    }
96    public IntValue MaximumIterations {
97      get { return MaximumIterationsParameter.Value; }
98      set { MaximumIterationsParameter.Value = value; }
99    }
100    public IntValue SampleSize {
101      get { return SampleSizeParameter.Value; }
102      set { SampleSizeParameter.Value = value; }
103    }
104    private RandomCreator RandomCreator {
105      get { return (RandomCreator)OperatorGraph.InitialOperator; }
106    }
107    private SolutionsCreator SolutionsCreator {
108      get { return (SolutionsCreator)RandomCreator.Successor; }
109    }
110    private LocalSearchMainLoop MainLoop {
111      get { return (LocalSearchMainLoop)SolutionsCreator.Successor; }
112    }
113    #endregion
114
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    [StorableConstructor]
150    private LocalSearch(bool deserializing) : base(deserializing) { }
151
152    public override IDeepCloneable Clone(Cloner cloner) {
153      LocalSearch clone = (LocalSearch)base.Clone(cloner);
154      clone.Initialize();
155      return clone;
156    }
157
158    public override void Prepare() {
159      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
160        base.Prepare();
161    }
162
163    #region Events
164    protected override void OnProblemChanged() {
165      ParameterizeStochasticOperator(Problem.SolutionCreator);
166      ParameterizeStochasticOperator(Problem.Evaluator);
167      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
168      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
169        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
170      }
171      ParameterizeSolutionsCreator();
172      ParameterizeMainLoop();
173      ParameterizeMoveEvaluators();
174      ParameterizeMoveMakers();
175      UpdateMoveGenerator();
176      UpdateMoveParameters();
177      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
178      base.OnProblemChanged();
179    }
180    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
181      ParameterizeStochasticOperator(Problem.SolutionCreator);
182      ParameterizeSolutionsCreator();
183      base.Problem_SolutionCreatorChanged(sender, e);
184    }
185    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
186      ParameterizeStochasticOperator(Problem.Evaluator);
187      ParameterizeSolutionsCreator();
188      ParameterizeMainLoop();
189      ParameterizeMoveEvaluators();
190      ParameterizeMoveMakers();
191      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
192      base.Problem_EvaluatorChanged(sender, e);
193    }
194    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
195      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
196      // This may seem pointless, but some operators already have the eventhandler registered, others don't
197      // FIXME: Is there another way to solve this problem?
198      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
199        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
200        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
201      }
202      UpdateMoveGenerator();
203      UpdateMoveParameters();
204      ParameterizeMainLoop();
205      ParameterizeMoveEvaluators();
206      ParameterizeMoveMakers();
207      base.Problem_OperatorsChanged(sender, e);
208    }
209    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
210      ParameterizeMainLoop();
211      ParameterizeMoveEvaluators();
212      ParameterizeMoveMakers();
213    }
214    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
215      UpdateMoveParameters();
216    }
217    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
218      ParameterizeMainLoop();
219      ParameterizeMoveEvaluators();
220      ParameterizeMoveMakers();
221    }
222    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
223      ParameterizeMainLoop();
224      ParameterizeMoveEvaluators();
225      ParameterizeMoveMakers();
226    }
227    #endregion
228
229    #region Helpers
230    [StorableHook(HookType.AfterDeserialization)]
231    private void Initialize() {
232      if (Problem != null) {
233        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
234        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
235          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
236        }
237      }
238      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
239      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
240    }
241    private void UpdateMoveGenerator() {
242      IMoveGenerator oldMoveGenerator = MoveGenerator;
243      MoveGeneratorParameter.ValidValues.Clear();
244      if (Problem != null) {
245        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
246          MoveGeneratorParameter.ValidValues.Add(generator);
247      }
248      if (oldMoveGenerator != null) {
249        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
250        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
251      }
252      if (MoveGenerator == null) {
253        ClearMoveParameters();
254      }
255    }
256    private void UpdateMoveParameters() {
257      IMoveMaker oldMoveMaker = MoveMaker;
258      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
259      ClearMoveParameters();
260      if (MoveGenerator != null) {
261        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
262        foreach (Type type in moveTypes.ToList()) {
263          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
264            moveTypes.Remove(type);
265        }
266        foreach (Type type in moveTypes) {
267          var operators = Problem.Operators.Where(x => type.IsAssignableFrom(x.GetType())).OrderBy(x => x.Name);
268          foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>())
269            MoveMakerParameter.ValidValues.Add(moveMaker);
270          foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>())
271            MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
272        }
273        if (oldMoveMaker != null) {
274          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
275          if (mm != null) MoveMaker = mm;
276        }
277        if (oldMoveEvaluator != null) {
278          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
279          if (me != null) MoveEvaluator = me;
280        }
281      }
282    }
283    private void ClearMoveParameters() {
284      MoveMakerParameter.ValidValues.Clear();
285      MoveEvaluatorParameter.ValidValues.Clear();
286    }
287    private void ParameterizeSolutionsCreator() {
288      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
289      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
290    }
291    private void ParameterizeMainLoop() {
292      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
293      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
294      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
295      if (MoveEvaluator != null)
296        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
297    }
298    private void ParameterizeStochasticOperator(IOperator op) {
299      if (op is IStochasticOperator)
300        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
301    }
302    private void ParameterizeMoveEvaluators() {
303      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
304        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
305      }
306    }
307    private void ParameterizeMoveMakers() {
308      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
309        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
310        if (MoveEvaluator != null)
311          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
312      }
313    }
314    #endregion
315  }
316}
Note: See TracBrowser for help on using the repository browser.