Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2937_SymReg_AnalyticalQuotient/HeuristicLab.Algorithms.LocalSearch/3.3/LocalSearch.cs @ 16082

Last change on this file since 16082 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 21.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.LocalSearch {
37  [Item("Local Search (LS)", "A local search algorithm.")]
38  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms, Priority = 100)]
39  [StorableClass]
40  public sealed class LocalSearch : HeuristicOptimizationEngineAlgorithm, IStorableContent {
41    public string Filename { get; set; }
42
43    #region Problem Properties
44    public override Type ProblemType {
45      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
46    }
47    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
48      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
49      set { base.Problem = value; }
50    }
51    #endregion
52
53    #region Parameter Properties
54    private ValueParameter<IntValue> SeedParameter {
55      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
56    }
57    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
58      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
59    }
60    public IConstrainedValueParameter<IMoveGenerator> MoveGeneratorParameter {
61      get { return (IConstrainedValueParameter<IMoveGenerator>)Parameters["MoveGenerator"]; }
62    }
63    public IConstrainedValueParameter<IMoveMaker> MoveMakerParameter {
64      get { return (IConstrainedValueParameter<IMoveMaker>)Parameters["MoveMaker"]; }
65    }
66    public IConstrainedValueParameter<ISingleObjectiveMoveEvaluator> MoveEvaluatorParameter {
67      get { return (IConstrainedValueParameter<ISingleObjectiveMoveEvaluator>)Parameters["MoveEvaluator"]; }
68    }
69    private ValueParameter<IntValue> MaximumIterationsParameter {
70      get { return (ValueParameter<IntValue>)Parameters["MaximumIterations"]; }
71    }
72    private ValueParameter<IntValue> SampleSizeParameter {
73      get { return (ValueParameter<IntValue>)Parameters["SampleSize"]; }
74    }
75    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
76      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
77    }
78    #endregion
79
80    #region Properties
81    public IntValue Seed {
82      get { return SeedParameter.Value; }
83      set { SeedParameter.Value = value; }
84    }
85    public BoolValue SetSeedRandomly {
86      get { return SetSeedRandomlyParameter.Value; }
87      set { SetSeedRandomlyParameter.Value = value; }
88    }
89    public IMoveGenerator MoveGenerator {
90      get { return MoveGeneratorParameter.Value; }
91      set { MoveGeneratorParameter.Value = value; }
92    }
93    public IMoveMaker MoveMaker {
94      get { return MoveMakerParameter.Value; }
95      set { MoveMakerParameter.Value = value; }
96    }
97    public ISingleObjectiveMoveEvaluator MoveEvaluator {
98      get { return MoveEvaluatorParameter.Value; }
99      set { MoveEvaluatorParameter.Value = value; }
100    }
101    public IntValue MaximumIterations {
102      get { return MaximumIterationsParameter.Value; }
103      set { MaximumIterationsParameter.Value = value; }
104    }
105    public IntValue SampleSize {
106      get { return SampleSizeParameter.Value; }
107      set { SampleSizeParameter.Value = value; }
108    }
109    public MultiAnalyzer Analyzer {
110      get { return AnalyzerParameter.Value; }
111      set { AnalyzerParameter.Value = value; }
112    }
113    private RandomCreator RandomCreator {
114      get { return (RandomCreator)OperatorGraph.InitialOperator; }
115    }
116    private SolutionsCreator SolutionsCreator {
117      get { return (SolutionsCreator)RandomCreator.Successor; }
118    }
119    private LocalSearchMainLoop MainLoop {
120      get { return FindMainLoop(SolutionsCreator.Successor); }
121    }
122    [Storable]
123    private BestAverageWorstQualityAnalyzer moveQualityAnalyzer;
124    #endregion
125
126    [StorableConstructor]
127    private LocalSearch(bool deserializing) : base(deserializing) { }
128    [StorableHook(HookType.AfterDeserialization)]
129    private void AfterDeserialization() {
130      Initialize();
131    }
132    private LocalSearch(LocalSearch original, Cloner cloner)
133      : base(original, cloner) {
134      moveQualityAnalyzer = cloner.Clone(original.moveQualityAnalyzer);
135      Initialize();
136    }
137    public override IDeepCloneable Clone(Cloner cloner) {
138      return new LocalSearch(this, cloner);
139    }
140    public LocalSearch()
141      : base() {
142      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
143      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
144      Parameters.Add(new ConstrainedValueParameter<IMoveGenerator>("MoveGenerator", "The operator used to generate moves to the neighborhood of the current solution."));
145      Parameters.Add(new ConstrainedValueParameter<IMoveMaker>("MoveMaker", "The operator used to perform a move."));
146      Parameters.Add(new ConstrainedValueParameter<ISingleObjectiveMoveEvaluator>("MoveEvaluator", "The operator used to evaluate a move."));
147      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of generations which should be processed.", new IntValue(1000)));
148      Parameters.Add(new ValueParameter<IntValue>("SampleSize", "Number of moves that MultiMoveGenerators should create. This is ignored for Exhaustive- and SingleMoveGenerators.", new IntValue(100)));
149      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
150
151      RandomCreator randomCreator = new RandomCreator();
152      SolutionsCreator solutionsCreator = new SolutionsCreator();
153      VariableCreator variableCreator = new VariableCreator();
154      ResultsCollector resultsCollector = new ResultsCollector();
155      LocalSearchMainLoop mainLoop = new LocalSearchMainLoop();
156      OperatorGraph.InitialOperator = randomCreator;
157
158      randomCreator.RandomParameter.ActualName = "Random";
159      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
160      randomCreator.SeedParameter.Value = null;
161      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
162      randomCreator.SetSeedRandomlyParameter.Value = null;
163      randomCreator.Successor = solutionsCreator;
164
165      solutionsCreator.NumberOfSolutions = new IntValue(1);
166      solutionsCreator.Successor = variableCreator;
167
168      variableCreator.Name = "Initialize EvaluatedMoves";
169      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedMoves", new IntValue()));
170      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
171      variableCreator.CollectedValues.Add(new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(0)));
172      variableCreator.Successor = resultsCollector;
173
174      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Moves", null, "EvaluatedMoves"));
175      resultsCollector.ResultsParameter.ActualName = "Results";
176      resultsCollector.Successor = mainLoop;
177
178      mainLoop.MoveGeneratorParameter.ActualName = MoveGeneratorParameter.Name;
179      mainLoop.MoveMakerParameter.ActualName = MoveMakerParameter.Name;
180      mainLoop.MoveEvaluatorParameter.ActualName = MoveEvaluatorParameter.Name;
181      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
182      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
183      mainLoop.ResultsParameter.ActualName = "Results";
184      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
185      mainLoop.EvaluatedMovesParameter.ActualName = "EvaluatedMoves";
186      mainLoop.IterationsParameter.ActualName = "Iterations";
187      mainLoop.BestLocalQualityParameter.ActualName = "BestQuality";
188
189      moveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
190      ParameterizeAnalyzers();
191      UpdateAnalyzers();
192
193      Initialize();
194    }
195
196    public override void Prepare() {
197      if (Problem != null && MoveGenerator != null && MoveMaker != null && MoveEvaluator != null)
198        base.Prepare();
199    }
200
201    #region Events
202    protected override void OnProblemChanged() {
203      ParameterizeStochasticOperator(Problem.SolutionCreator);
204      ParameterizeStochasticOperator(Problem.Evaluator);
205      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
206      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
207        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
208      }
209      ParameterizeSolutionsCreator();
210      ParameterizeMainLoop();
211      UpdateMoveGenerator();
212      UpdateMoveParameters();
213      UpdateAnalyzers();
214      ParameterizeMoveGenerators();
215      ParameterizeMoveEvaluators();
216      ParameterizeMoveMakers();
217      ParameterizeAnalyzers();
218      ParameterizeIterationBasedOperators();
219      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
220      base.OnProblemChanged();
221    }
222    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
223      ParameterizeStochasticOperator(Problem.SolutionCreator);
224      ParameterizeSolutionsCreator();
225      base.Problem_SolutionCreatorChanged(sender, e);
226    }
227    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
228      ParameterizeStochasticOperator(Problem.Evaluator);
229      ParameterizeSolutionsCreator();
230      ParameterizeMainLoop();
231      ParameterizeMoveEvaluators();
232      ParameterizeMoveMakers();
233      ParameterizeAnalyzers();
234      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
235      base.Problem_EvaluatorChanged(sender, e);
236    }
237    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
238      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
239      // This may seem pointless, but some operators already have the eventhandler registered, others don't
240      // FIXME: Is there another way to solve this problem?
241      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
242        op.MoveQualityParameter.ActualNameChanged -= new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
243        op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
244      }
245      UpdateMoveGenerator();
246      UpdateMoveParameters();
247      UpdateAnalyzers();
248      ParameterizeMainLoop();
249      ParameterizeMoveGenerators();
250      ParameterizeMoveEvaluators();
251      ParameterizeMoveMakers();
252      ParameterizeAnalyzers();
253      ParameterizeIterationBasedOperators();
254      base.Problem_OperatorsChanged(sender, e);
255    }
256    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
257      ParameterizeMainLoop();
258      ParameterizeMoveEvaluators();
259      ParameterizeMoveMakers();
260    }
261    private void MoveGeneratorParameter_ValueChanged(object sender, EventArgs e) {
262      UpdateMoveParameters();
263    }
264    private void MoveEvaluatorParameter_ValueChanged(object sender, EventArgs e) {
265      ParameterizeMainLoop();
266      ParameterizeMoveEvaluators();
267      ParameterizeMoveMakers();
268      ParameterizeAnalyzers();
269    }
270    private void MoveEvaluator_MoveQualityParameter_ActualNameChanged(object sender, EventArgs e) {
271      ParameterizeMainLoop();
272      ParameterizeMoveEvaluators();
273      ParameterizeMoveMakers();
274      ParameterizeAnalyzers();
275    }
276    #endregion
277
278    #region Helpers
279    private void Initialize() {
280      if (Problem != null) {
281        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
282        foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
283          op.MoveQualityParameter.ActualNameChanged += new EventHandler(MoveEvaluator_MoveQualityParameter_ActualNameChanged);
284        }
285      }
286      MoveGeneratorParameter.ValueChanged += new EventHandler(MoveGeneratorParameter_ValueChanged);
287      MoveEvaluatorParameter.ValueChanged += new EventHandler(MoveEvaluatorParameter_ValueChanged);
288    }
289    private void UpdateMoveGenerator() {
290      IMoveGenerator oldMoveGenerator = MoveGenerator;
291      IMoveGenerator defaultMoveGenerator = Problem.Operators.OfType<IMoveGenerator>().FirstOrDefault();
292      MoveGeneratorParameter.ValidValues.Clear();
293      if (Problem != null) {
294        foreach (IMoveGenerator generator in Problem.Operators.OfType<IMoveGenerator>().OrderBy(x => x.Name))
295          MoveGeneratorParameter.ValidValues.Add(generator);
296      }
297      if (oldMoveGenerator != null) {
298        IMoveGenerator newMoveGenerator = MoveGeneratorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveGenerator.GetType());
299        if (newMoveGenerator != null) MoveGenerator = newMoveGenerator;
300        else oldMoveGenerator = null;
301      }
302      if (oldMoveGenerator == null && defaultMoveGenerator != null)
303        MoveGenerator = defaultMoveGenerator;
304      if (MoveGenerator == null) {
305        ClearMoveParameters();
306      }
307    }
308    private void UpdateMoveParameters() {
309      IMoveMaker oldMoveMaker = MoveMaker;
310      ISingleObjectiveMoveEvaluator oldMoveEvaluator = MoveEvaluator;
311      ClearMoveParameters();
312      if (MoveGenerator != null) {
313        List<Type> moveTypes = MoveGenerator.GetType().GetInterfaces().Where(x => typeof(IMoveOperator).IsAssignableFrom(x)).ToList();
314        foreach (Type type in moveTypes.ToList()) {
315          if (moveTypes.Any(t => t != type && type.IsAssignableFrom(t)))
316            moveTypes.Remove(type);
317        }
318
319        var operators = Problem.Operators.Where(op => moveTypes.Any(m => m.IsInstanceOfType(op))).ToList();
320        IMoveMaker defaultMoveMaker = operators.OfType<IMoveMaker>().FirstOrDefault();
321        ISingleObjectiveMoveEvaluator defaultMoveEvaluator = operators.OfType<ISingleObjectiveMoveEvaluator>().FirstOrDefault();
322        foreach (IMoveMaker moveMaker in operators.OfType<IMoveMaker>().OrderBy(op => op.Name))
323          MoveMakerParameter.ValidValues.Add(moveMaker);
324        foreach (ISingleObjectiveMoveEvaluator moveEvaluator in operators.OfType<ISingleObjectiveMoveEvaluator>().OrderBy(op => op.Name))
325          MoveEvaluatorParameter.ValidValues.Add(moveEvaluator);
326
327        if (oldMoveMaker != null) {
328          IMoveMaker mm = MoveMakerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveMaker.GetType());
329          if (mm != null) MoveMaker = mm;
330          else oldMoveMaker = null;
331        }
332        if (oldMoveMaker == null && defaultMoveMaker != null)
333          MoveMaker = defaultMoveMaker;
334
335        if (oldMoveEvaluator != null) {
336          ISingleObjectiveMoveEvaluator me = MoveEvaluatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMoveEvaluator.GetType());
337          if (me != null) MoveEvaluator = me;
338          else oldMoveEvaluator = null;
339        }
340        if (oldMoveEvaluator == null && defaultMoveEvaluator != null)
341          MoveEvaluator = defaultMoveEvaluator;
342      }
343    }
344    private void UpdateAnalyzers() {
345      Analyzer.Operators.Clear();
346      if (Problem != null) {
347        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
348          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
349            param.Depth = 0;
350          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
351        }
352      }
353      Analyzer.Operators.Add(moveQualityAnalyzer, moveQualityAnalyzer.EnabledByDefault);
354    }
355    private void ClearMoveParameters() {
356      MoveMakerParameter.ValidValues.Clear();
357      MoveEvaluatorParameter.ValidValues.Clear();
358    }
359    private void ParameterizeSolutionsCreator() {
360      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
361      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
362    }
363    private void ParameterizeMainLoop() {
364      if (Problem != null) {
365        MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
366        MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
367        MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
368      }
369      if (MoveEvaluator != null)
370        MainLoop.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
371    }
372    private void ParameterizeStochasticOperator(IOperator op) {
373      if (op is IStochasticOperator) {
374        IStochasticOperator stOp = (IStochasticOperator)op;
375        stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
376        stOp.RandomParameter.Hidden = true;
377      }
378    }
379    private void ParameterizeMoveGenerators() {
380      if (Problem != null) {
381        foreach (IMultiMoveGenerator generator in Problem.Operators.OfType<IMultiMoveGenerator>()) {
382          generator.SampleSizeParameter.ActualName = SampleSizeParameter.Name;
383          generator.SampleSizeParameter.Hidden = true;
384        }
385      }
386    }
387    private void ParameterizeMoveEvaluators() {
388      foreach (ISingleObjectiveMoveEvaluator op in Problem.Operators.OfType<ISingleObjectiveMoveEvaluator>()) {
389        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
390        op.QualityParameter.Hidden = true;
391      }
392    }
393    private void ParameterizeMoveMakers() {
394      foreach (IMoveMaker op in Problem.Operators.OfType<IMoveMaker>()) {
395        op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
396        op.QualityParameter.Hidden = true;
397        if (MoveEvaluator != null) {
398          op.MoveQualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
399          op.MoveQualityParameter.Hidden = true;
400        } else {
401          op.MoveQualityParameter.Hidden = false;
402        }
403      }
404    }
405    private void ParameterizeAnalyzers() {
406      moveQualityAnalyzer.ResultsParameter.ActualName = "Results";
407      moveQualityAnalyzer.ResultsParameter.Hidden = true;
408      if (Problem != null) {
409        moveQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
410        moveQualityAnalyzer.MaximizationParameter.Hidden = true;
411        if (MoveEvaluator != null) {
412          moveQualityAnalyzer.QualityParameter.ActualName = MoveEvaluator.MoveQualityParameter.ActualName;
413          moveQualityAnalyzer.QualityParameter.Hidden = true;
414        } else moveQualityAnalyzer.QualityParameter.Hidden = false;
415        moveQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
416        moveQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
417      } else {
418        moveQualityAnalyzer.MaximizationParameter.Hidden = false;
419        moveQualityAnalyzer.BestKnownQualityParameter.Hidden = false;
420      }
421    }
422    private void ParameterizeIterationBasedOperators() {
423      if (Problem != null) {
424        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
425          op.IterationsParameter.ActualName = "Iterations";
426          op.IterationsParameter.Hidden = true;
427          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
428          op.MaximumIterationsParameter.Hidden = true;
429        }
430      }
431    }
432    private LocalSearchMainLoop FindMainLoop(IOperator start) {
433      IOperator mainLoop = start;
434      while (mainLoop != null && !(mainLoop is LocalSearchMainLoop))
435        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
436      if (mainLoop == null) return null;
437      else return (LocalSearchMainLoop)mainLoop;
438    }
439    #endregion
440  }
441}
Note: See TracBrowser for help on using the repository browser.