Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/HeuristicLab.Algorithms.VariableNeighborhoodSearch/3.3/VariableNeighborhoodSearch.cs @ 6202

Last change on this file since 6202 was 6195, checked in by abeham, 14 years ago

#1465

  • updated branch with latest version of trunk
File size: 15.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.VariableNeighborhoodSearch {
37  [Item("Variable Neighborhood Search", "A variable neighborhood search algorithm based on the description in Mladenovic, N. and Hansen, P. (1997). Variable neighborhood search. Computers & Operations Research Volume 24, Issue 11, pp. 1097-1100.")]
38  [Creatable("Algorithms")]
39  [StorableClass]
40  public sealed class VariableNeighborhoodSearch : 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 FixedValueParameter<IntValue> SeedParameter {
55      get { return (FixedValueParameter<IntValue>)Parameters["Seed"]; }
56    }
57    private FixedValueParameter<BoolValue> SetSeedRandomlyParameter {
58      get { return (FixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
59    }
60    private ConstrainedValueParameter<ILocalImprovementOperator> LocalImprovementParameter {
61      get { return (ConstrainedValueParameter<ILocalImprovementOperator>)Parameters["LocalImprovement"]; }
62    }
63    private ConstrainedValueParameter<IMultiNeighborhoodShakingOperator> ShakingOperatorParameter {
64      get { return (ConstrainedValueParameter<IMultiNeighborhoodShakingOperator>)Parameters["ShakingOperator"]; }
65    }
66    private FixedValueParameter<IntValue> MaximumIterationsParameter {
67      get { return (FixedValueParameter<IntValue>)Parameters["MaximumIterations"]; }
68    }
69    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
70      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
71    }
72    public FixedValueParameter<IntValue> LocalImprovementMaximumIterationsParameter {
73      get { return (FixedValueParameter<IntValue>)Parameters["LocalImprovementMaximumIterations"]; }
74    }
75    #endregion
76
77    #region Properties
78    private RandomCreator RandomCreator {
79      get { return (RandomCreator)OperatorGraph.InitialOperator; }
80    }
81    public MultiAnalyzer Analyzer {
82      get { return AnalyzerParameter.Value; }
83      set { AnalyzerParameter.Value = value; }
84    }
85    private SolutionsCreator SolutionsCreator {
86      get { return (SolutionsCreator)RandomCreator.Successor; }
87    }
88    private VariableNeighborhoodSearchMainLoop MainLoop {
89      get { return FindMainLoop(SolutionsCreator.Successor); }
90    }
91    #endregion
92
93    [Storable]
94    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
95
96    [StorableConstructor]
97    private VariableNeighborhoodSearch(bool deserializing) : base(deserializing) { }
98    private VariableNeighborhoodSearch(VariableNeighborhoodSearch original, Cloner cloner)
99      : base(original, cloner) {
100      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
101      RegisterEventHandlers();
102    }
103    public VariableNeighborhoodSearch()
104      : base() {
105      Parameters.Add(new FixedValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
106      Parameters.Add(new FixedValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
107      Parameters.Add(new ConstrainedValueParameter<ILocalImprovementOperator>("LocalImprovement", "The local improvement operation"));
108      Parameters.Add(new ConstrainedValueParameter<IMultiNeighborhoodShakingOperator>("ShakingOperator", "The operator that performs the shaking of solutions."));
109      Parameters.Add(new FixedValueParameter<IntValue>("MaximumIterations", "The maximum number of iterations which should be processed.", new IntValue(50)));
110      Parameters.Add(new FixedValueParameter<IntValue>("LocalImprovementMaximumIterations", "The maximum number of iterations which should be performed in the local improvement phase.", new IntValue(50)));
111      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the solution and moves.", new MultiAnalyzer()));
112
113      RandomCreator randomCreator = new RandomCreator();
114      SolutionsCreator solutionsCreator = new SolutionsCreator();
115      VariableCreator variableCreator = new VariableCreator();
116      ResultsCollector resultsCollector = new ResultsCollector();
117      VariableNeighborhoodSearchMainLoop mainLoop = new VariableNeighborhoodSearchMainLoop();
118      OperatorGraph.InitialOperator = randomCreator;
119
120      randomCreator.RandomParameter.ActualName = "Random";
121      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
122      randomCreator.SeedParameter.Value = null;
123      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
124      randomCreator.SetSeedRandomlyParameter.Value = null;
125      randomCreator.Successor = solutionsCreator;
126
127      solutionsCreator.NumberOfSolutions = new IntValue(1);
128      solutionsCreator.Successor = variableCreator;
129
130      variableCreator.Name = "Initialize Evaluated Solutions";
131
132      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
133      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
134      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("CurrentNeighborhoodIndex", new IntValue(0)));
135      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("NeighborhoodCount", new IntValue(0)));
136      variableCreator.Successor = resultsCollector;
137
138      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
139      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Iterations"));
140      resultsCollector.ResultsParameter.ActualName = "Results";
141      resultsCollector.Successor = mainLoop;
142
143      mainLoop.IterationsParameter.ActualName = "Iterations";
144      mainLoop.CurrentNeighborhoodIndexParameter.ActualName = "CurrentNeighborhoodIndex";
145      mainLoop.NeighborhoodCountParameter.ActualName = "NeighborhoodCount";
146      mainLoop.LocalImprovementParameter.ActualName = LocalImprovementParameter.Name;
147      mainLoop.ShakingOperatorParameter.ActualName = ShakingOperatorParameter.Name;
148      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
149      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
150      mainLoop.ResultsParameter.ActualName = "Results";
151      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
152      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
153
154      InitializeLocalImprovementOperators();
155      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
156      ParameterizeAnalyzers();
157      UpdateAnalyzers();
158
159      RegisterEventHandlers();
160    }
161
162    public override IDeepCloneable Clone(Cloner cloner) {
163      return new VariableNeighborhoodSearch(this, cloner);
164    }
165
166    [StorableHook(HookType.AfterDeserialization)]
167    private void AfterDeserialization() {
168      if (Parameters["LocalImprovement"] is ValueParameter<ILocalImprovementOperator>) {
169        ILocalImprovementOperator bla = ((ValueParameter<ILocalImprovementOperator>)Parameters["LocalImprovement"]).Value;
170        Parameters.Remove("LocalImprovement");
171        Parameters.Add(new ConstrainedValueParameter<ILocalImprovementOperator>("LocalImprovement", "The local improvement operation"));
172        LocalImprovementParameter.ValidValues.Add(bla);
173        IMultiNeighborhoodShakingOperator bla2 = ((ValueParameter<IMultiNeighborhoodShakingOperator>)Parameters["Shaking"]).Value;
174        Parameters.Remove("Shaking");
175        Parameters.Add(new ConstrainedValueParameter<IMultiNeighborhoodShakingOperator>("ShakingOperator", "The operator that performs the shaking of solutions."));
176        ShakingOperatorParameter.ValidValues.Add(bla2);
177      }
178      RegisterEventHandlers();
179    }
180
181    public override void Prepare() {
182      if (Problem != null) base.Prepare();
183    }
184
185    private void RegisterEventHandlers() {
186      LocalImprovementParameter.ValueChanged += new EventHandler(LocalImprovementParameter_ValueChanged);
187      if (Problem != null) {
188        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
189      }
190    }
191
192    #region Events
193    protected override void OnProblemChanged() {
194      InitializeLocalImprovementOperators();
195      UpdateShakingOperators();
196      UpdateAnalyzers();
197
198      ParameterizeStochasticOperator(Problem.SolutionCreator);
199      ParameterizeStochasticOperator(Problem.Evaluator);
200      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
201      ParameterizeSolutionsCreator();
202      ParameterizeMainLoop();
203      ParameterizeAnalyzers();
204      ParameterizeIterationBasedOperators();
205      ParameterizeLocalImprovementOperators();
206      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
207      base.OnProblemChanged();
208    }
209    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
210      ParameterizeStochasticOperator(Problem.SolutionCreator);
211      ParameterizeSolutionsCreator();
212      base.Problem_SolutionCreatorChanged(sender, e);
213    }
214    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
215      ParameterizeStochasticOperator(Problem.Evaluator);
216      ParameterizeSolutionsCreator();
217      ParameterizeMainLoop();
218      ParameterizeAnalyzers();
219      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
220      base.Problem_EvaluatorChanged(sender, e);
221    }
222    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
223      UpdateShakingOperators();
224      UpdateAnalyzers();
225      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
226      ParameterizeIterationBasedOperators();
227      base.Problem_OperatorsChanged(sender, e);
228    }
229    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
230      ParameterizeMainLoop();
231      ParameterizeAnalyzers();
232    }
233    private void LocalImprovementParameter_ValueChanged(object sender, EventArgs e) {
234      ParameterizeLocalImprovementOperators();
235    }
236    #endregion
237
238    #region Helpers
239    private void ParameterizeSolutionsCreator() {
240      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
241      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
242    }
243    private void ParameterizeStochasticOperator(IOperator op) {
244      if (op is IStochasticOperator)
245        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
246    }
247    private void ParameterizeMainLoop() {
248      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
249      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
250      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
251    }
252    private void ParameterizeAnalyzers() {
253      qualityAnalyzer.ResultsParameter.ActualName = "Results";
254      if (Problem != null) {
255        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
256        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
257        qualityAnalyzer.QualityParameter.Depth = 1;
258        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
259      }
260    }
261    private void ParameterizeIterationBasedOperators() {
262      if (Problem != null) {
263        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
264          op.IterationsParameter.ActualName = "Iterations";
265          op.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
266        }
267      }
268    }
269    private void ParameterizeLocalImprovementOperators() {
270      foreach (ILocalImprovementOperator op in LocalImprovementParameter.ValidValues) {
271        if (op != LocalImprovementParameter.Value) op.Problem = null;
272        op.MaximumIterationsParameter.Value = null;
273        op.MaximumIterationsParameter.ActualName = LocalImprovementMaximumIterationsParameter.Name;
274      }
275      if (LocalImprovementParameter.Value != null)
276        LocalImprovementParameter.Value.Problem = Problem;
277    }
278    private void InitializeLocalImprovementOperators() {
279      if (Problem == null) {
280        LocalImprovementParameter.ValidValues.Clear();
281      } else {
282        LocalImprovementParameter.ValidValues.RemoveWhere(x => !x.ProblemType.IsAssignableFrom(Problem.GetType()));
283        foreach (ILocalImprovementOperator op in ApplicationManager.Manager.GetInstances<ILocalImprovementOperator>().Where(x => x.ProblemType.IsAssignableFrom(Problem.GetType()))) {
284          if (!LocalImprovementParameter.ValidValues.Any(x => x.GetType() == op.GetType()))
285            LocalImprovementParameter.ValidValues.Add(op);
286        }
287      }
288    }
289    private void UpdateShakingOperators() {
290      ShakingOperatorParameter.ValidValues.Clear();
291      foreach (IMultiNeighborhoodShakingOperator op in Problem.Operators.OfType<IMultiNeighborhoodShakingOperator>()) {
292        ShakingOperatorParameter.ValidValues.Add(op);
293        op.CurrentNeighborhoodIndexParameter.ActualName = "CurrentNeighborhoodIndex";
294        op.NeighborhoodCountParameter.ActualName = "NeighborhoodCount";
295      }
296    }
297    private void UpdateAnalyzers() {
298      Analyzer.Operators.Clear();
299      if (Problem != null) {
300        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
301          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
302            param.Depth = 1;
303          Analyzer.Operators.Add(analyzer);
304        }
305      }
306      Analyzer.Operators.Add(qualityAnalyzer);
307    }
308    private VariableNeighborhoodSearchMainLoop FindMainLoop(IOperator start) {
309      IOperator mainLoop = start;
310      while (mainLoop != null && !(mainLoop is VariableNeighborhoodSearchMainLoop))
311        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
312      if (mainLoop == null) return null;
313      else return (VariableNeighborhoodSearchMainLoop)mainLoop;
314    }
315    #endregion
316  }
317}
Note: See TracBrowser for help on using the repository browser.