Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASPWithPathRelinking.cs @ 11255

Last change on this file since 11255 was 7833, checked in by abeham, 13 years ago

#1614

  • made GRASP+PR an IStorableContent
  • fixed bug in GreedyRandomizedSolutionCreator
File size: 14.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Optimization;
29using HeuristicLab.Optimization.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Problems.GeneralizedQuadraticAssignment.Common;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms {
37  /// <summary>
38  /// The algorithm combines the Greedy Randomized Adaptive Search Procedure (GRASP) with Path Relinking and is described in Mateus, G., Resende, M., and Silva, R. 2011. GRASP with path-relinking for the generalized quadratic assignment problem. Journal of Heuristics 17, Springer Netherlands, pp. 527-565.
39  /// </summary>
40  [Item("GRASP+PR", "The algorithm combines the Greedy Randomized Adaptive Search Procedure (GRASP) with Path Relinking and is described in Mateus, G., Resende, M., and Silva, R. 2011. GRASP with path-relinking for the generalized quadratic assignment problem. Journal of Heuristics 17, Springer Netherlands, pp. 527-565.")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public sealed class GRASPWithPathRelinking : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
49    }
50    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
51      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
57    private IValueParameter<BoolValue> SetSeedRandomlyParameter {
58      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
59    }
60    private IValueParameter<IntValue> SeedParameter {
61      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
62    }
63    private IValueParameter<MultiAnalyzer> AnalyzerParameter {
64      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
65    }
66    public IValueParameter<IntValue> MaximumIterationsParameter {
67      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
68    }
69    private IFixedValueParameter<IntValue> EliteSetSizeParameter {
70      get { return (IFixedValueParameter<IntValue>)Parameters["EliteSetSize"]; }
71    }
72    private IFixedValueParameter<IntValue> LocalImprovementMaximumIterationsParameter {
73      get { return (IFixedValueParameter<IntValue>)Parameters["LocalImprovementMaximumIterations"]; }
74    }
75    private ConstrainedValueParameter<ILocalImprovementOperator> LocalImprovementParameter {
76      get { return (ConstrainedValueParameter<ILocalImprovementOperator>)Parameters["LocalImprovement"]; }
77    }
78    public IFixedValueParameter<IntValue> MinimumEliteSetSizeParameter {
79      get { return (IFixedValueParameter<IntValue>)Parameters["MinimumEliteSetSize"]; }
80    }
81    public ConstrainedValueParameter<ICrossover> PathRelinkingParameter {
82      get { return (ConstrainedValueParameter<ICrossover>)Parameters["PathRelinking"]; }
83    }
84    public ConstrainedValueParameter<IPopulationReducer> EliteSetReducerParameter {
85      get { return (ConstrainedValueParameter<IPopulationReducer>)Parameters["EliteSetReducer"]; }
86    }
87    #endregion
88
89    #region Properties
90    public BoolValue SetSeedRandomly {
91      get { return SetSeedRandomlyParameter.Value; }
92      set { SetSeedRandomlyParameter.Value = value; }
93    }
94    public IntValue Seed {
95      get { return SeedParameter.Value; }
96      set { SeedParameter.Value = value; }
97    }
98    public MultiAnalyzer Analyzer {
99      get { return AnalyzerParameter.Value; }
100      set { AnalyzerParameter.Value = value; }
101    }
102    public IntValue EliteSetSize {
103      get { return EliteSetSizeParameter.Value; }
104      set { EliteSetSizeParameter.Value.Value = value.Value; }
105    }
106    public IntValue LocalImprovementMaximumIterations {
107      get { return LocalImprovementMaximumIterationsParameter.Value; }
108      set { LocalImprovementMaximumIterationsParameter.Value.Value = value.Value; }
109    }
110
111    private RandomCreator RandomCreator {
112      get { return (RandomCreator)OperatorGraph.InitialOperator; }
113    }
114    private SolutionsCreator SolutionsCreator {
115      get { return (SolutionsCreator)RandomCreator.Successor; }
116    }
117    private GRASPWithPathRelinkingMainLoop MainLoop {
118      get { return SolutionsCreator.Successor as GRASPWithPathRelinkingMainLoop; }
119    }
120    #endregion
121
122    [Storable]
123    private BestAverageWorstQualityAnalyzer analyzer;
124
125    [StorableConstructor]
126    private GRASPWithPathRelinking(bool deserializing) : base(deserializing) { }
127    private GRASPWithPathRelinking(GRASPWithPathRelinking original, Cloner cloner)
128      : base(original, cloner) {
129      analyzer = cloner.Clone(original.analyzer);
130      RegisterEventHandlers();
131    }
132    public GRASPWithPathRelinking()
133      : base() {
134      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
135      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator."));
136      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each iteration.", new MultiAnalyzer()));
137      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of iterations that the algorithm should run.", new IntValue(1000)));
138      Parameters.Add(new FixedValueParameter<IntValue>("EliteSetSize", "The elite set stores the best found solutions.", new IntValue(10)));
139      Parameters.Add(new FixedValueParameter<IntValue>("LocalImprovementMaximumIterations", "The maximum number of iterations performed by the local improvement operator.", new IntValue(1000)));
140      Parameters.Add(new ConstrainedValueParameter<ILocalImprovementOperator>("LocalImprovement", "Performs a local search on the solution."));
141      Parameters.Add(new FixedValueParameter<IntValue>("MinimumEliteSetSize", "(ρ) The minimum amount of elites for performing path relinking.", new IntValue(2)));
142      Parameters.Add(new ConstrainedValueParameter<ICrossover>("PathRelinking", "The operator that performs the path relinking."));
143      Parameters.Add(new ConstrainedValueParameter<IPopulationReducer>("EliteSetReducer", "The operator that reduces the old elite set and the new solution(s) to a new elite set."));
144
145      analyzer = new BestAverageWorstQualityAnalyzer();
146      Analyzer.Operators.Add(analyzer);
147
148      var randomCreator = new RandomCreator();
149      OperatorGraph.InitialOperator = randomCreator;
150
151      randomCreator.RandomParameter.ActualName = "Random";
152      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
153      randomCreator.SeedParameter.Value = null;
154      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
155      randomCreator.SetSeedRandomlyParameter.Value = null;
156
157      var solutionsCreator = new SolutionsCreator();
158      solutionsCreator.NumberOfSolutionsParameter.ActualName = MinimumEliteSetSizeParameter.Name;
159      solutionsCreator.ParallelParameter.Value = new BoolValue(true);
160      randomCreator.Successor = solutionsCreator;
161
162      var mainLoop = new GRASPWithPathRelinkingMainLoop();
163      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
164      mainLoop.EliteSetReducerParameter.ActualName = EliteSetReducerParameter.Name;
165      mainLoop.EliteSetSizeParameter.ActualName = EliteSetSizeParameter.Name;
166      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
167      mainLoop.LocalImprovementParameter.ActualName = LocalImprovementParameter.Name;
168      mainLoop.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
169      mainLoop.PathRelinkingParameter.ActualName = PathRelinkingParameter.Name;
170      mainLoop.ResultsParameter.ActualName = "Results";
171      solutionsCreator.Successor = mainLoop;
172
173      InitializeOperators();
174      RegisterEventHandlers();
175    }
176
177    public override IDeepCloneable Clone(Cloner cloner) {
178      return new GRASPWithPathRelinking(this, cloner);
179    }
180
181    public override void Prepare() {
182      if (Problem != null) base.Prepare();
183    }
184
185    #region Events
186    protected override void OnProblemChanged() {
187      InitializeOperators();
188      base.OnProblemChanged();
189    }
190
191    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
192      Parameterize();
193      base.Problem_SolutionCreatorChanged(sender, e);
194    }
195    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
196      Parameterize();
197      base.Problem_EvaluatorChanged(sender, e);
198    }
199    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
200      InitializeOperators();
201      base.Problem_OperatorsChanged(sender, e);
202    }
203
204    private void LocalImprovementParameter_ValueChanged(object sender, EventArgs e) {
205      Parameterize();
206    }
207    #endregion
208
209    #region Helpers
210    [StorableHook(HookType.AfterDeserialization)]
211    private void AfterDeserialization() {
212      if (Problem != null) {
213      }
214      RegisterEventHandlers();
215    }
216
217    private void RegisterEventHandlers() {
218      LocalImprovementParameter.ValueChanged += new EventHandler(LocalImprovementParameter_ValueChanged);
219    }
220
221    private void InitializeOperators() {
222      Analyzer.Operators.Clear();
223      if (Problem != null) {
224        foreach (IAnalyzer a in Problem.Operators.OfType<IAnalyzer>()) {
225          foreach (var param in a.Parameters.OfType<IScopeTreeLookupParameter>())
226            param.Depth = 1;
227          Analyzer.Operators.Add(a);
228          Analyzer.Operators.SetItemCheckedState(a, a.EnabledByDefault);
229        }
230        InitializeFromInstallation(LocalImprovementParameter, x => x.ProblemType.IsAssignableFrom(Problem.GetType()));
231        InitializeFromProblem(PathRelinkingParameter);
232        InitializeFromProblem(EliteSetReducerParameter);
233      } else {
234        LocalImprovementParameter.ValidValues.Clear();
235        PathRelinkingParameter.ValidValues.Clear();
236        EliteSetReducerParameter.ValidValues.Clear();
237      }
238      Analyzer.Operators.Add(analyzer);
239
240      Parameterize();
241    }
242
243    private void Parameterize() {
244      if (Problem != null) {
245        SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
246        SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
247
248        MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
249        MainLoop.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
250
251        analyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
252
253        if (LocalImprovementParameter.Value != null)
254          LocalImprovementParameter.Value.Problem = Problem;
255      }
256      foreach (var localImprovement in LocalImprovementParameter.ValidValues) {
257        localImprovement.MaximumIterationsParameter.ActualName = LocalImprovementMaximumIterationsParameter.Name;
258        localImprovement.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
259        localImprovement.ResultsParameter.ActualName = "Results";
260      }
261      foreach (var reducer in EliteSetReducerParameter.ValidValues) {
262        reducer.MinimumPopulationSizeParameter.ActualName = MinimumEliteSetSizeParameter.Name;
263        reducer.MaximumPopulationSizeParameter.ActualName = EliteSetSizeParameter.Name;
264      }
265    }
266
267    private void InitializeFromProblem<T>(ConstrainedValueParameter<T> parameter) where T : class, INamedItem {
268      InitializeFromProblem<T>(parameter, x => true);
269    }
270    private void InitializeFromProblem<T>(ConstrainedValueParameter<T> parameter, Func<T, bool> condition) where T : class, INamedItem {
271      if (parameter == null) throw new ArgumentNullException("parameter");
272      if (condition == null) throw new ArgumentNullException("condition");
273      string oldName = String.Empty;
274      if (parameter.Value != null) oldName = parameter.Value.Name;
275      parameter.ValidValues.Clear();
276      foreach (var item in Problem.Operators.OfType<T>().Where(condition)) {
277        parameter.ValidValues.Add(item);
278      }
279      var newItem = parameter.ValidValues.FirstOrDefault(x => x.Name == oldName);
280      if (newItem != null) parameter.Value = newItem;
281    }
282    private void InitializeFromInstallation<T>(ConstrainedValueParameter<T> parameter) where T : class, INamedItem {
283      InitializeFromInstallation<T>(parameter, x => true);
284    }
285    private void InitializeFromInstallation<T>(ConstrainedValueParameter<T> parameter, Func<T, bool> condition) where T : class, INamedItem {
286      if (parameter == null) throw new ArgumentNullException("parameter");
287      if (condition == null) throw new ArgumentNullException("condition");
288      string oldName = String.Empty;
289      if (parameter.Value != null) oldName = parameter.Value.Name;
290      parameter.ValidValues.Clear();
291      foreach (var item in ApplicationManager.Manager.GetInstances<T>().Where(condition)) {
292        parameter.ValidValues.Add(item);
293      }
294      var newItem = parameter.ValidValues.FirstOrDefault(x => x.Name == oldName);
295      if (newItem != null) parameter.Value = newItem;
296    }
297    #endregion
298  }
299}
Note: See TracBrowser for help on using the repository browser.