Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12075 was 11505, checked in by abeham, 10 years ago

#1614: updated to trunk changes

File size: 14.5 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 is ILocalImprovementAlgorithmOperator
231          && ((ILocalImprovementAlgorithmOperator)x).ProblemType.IsInstanceOfType(Problem));
232        InitializeFromProblem(PathRelinkingParameter);
233        InitializeFromProblem(EliteSetReducerParameter);
234      } else {
235        LocalImprovementParameter.ValidValues.Clear();
236        PathRelinkingParameter.ValidValues.Clear();
237        EliteSetReducerParameter.ValidValues.Clear();
238      }
239      Analyzer.Operators.Add(analyzer);
240
241      Parameterize();
242    }
243
244    private void Parameterize() {
245      if (Problem != null) {
246        SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
247        SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
248
249        MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
250        MainLoop.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
251
252        analyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
253
254        if (LocalImprovementParameter.Value != null) {
255          if (LocalImprovementParameter.Value is ILocalImprovementAlgorithmOperator)
256            ((ILocalImprovementAlgorithmOperator)LocalImprovementParameter.Value).Problem = Problem;
257        }
258      }
259      foreach (var localImprovement in LocalImprovementParameter.ValidValues) {
260        localImprovement.MaximumIterationsParameter.ActualName = LocalImprovementMaximumIterationsParameter.Name;
261        localImprovement.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
262        localImprovement.ResultsParameter.ActualName = "Results";
263      }
264      foreach (var reducer in EliteSetReducerParameter.ValidValues) {
265        reducer.MinimumPopulationSizeParameter.ActualName = MinimumEliteSetSizeParameter.Name;
266        reducer.MaximumPopulationSizeParameter.ActualName = EliteSetSizeParameter.Name;
267      }
268    }
269
270    private void InitializeFromProblem<T>(ConstrainedValueParameter<T> parameter) where T : class, INamedItem {
271      InitializeFromProblem<T>(parameter, x => true);
272    }
273    private void InitializeFromProblem<T>(ConstrainedValueParameter<T> parameter, Func<T, bool> condition) where T : class, INamedItem {
274      if (parameter == null) throw new ArgumentNullException("parameter");
275      if (condition == null) throw new ArgumentNullException("condition");
276      string oldName = String.Empty;
277      if (parameter.Value != null) oldName = parameter.Value.Name;
278      parameter.ValidValues.Clear();
279      foreach (var item in Problem.Operators.OfType<T>().Where(condition)) {
280        parameter.ValidValues.Add(item);
281      }
282      var newItem = parameter.ValidValues.FirstOrDefault(x => x.Name == oldName);
283      if (newItem != null) parameter.Value = newItem;
284    }
285    private void InitializeFromInstallation<T>(ConstrainedValueParameter<T> parameter) where T : class, INamedItem {
286      InitializeFromInstallation<T>(parameter, x => true);
287    }
288    private void InitializeFromInstallation<T>(ConstrainedValueParameter<T> parameter, Func<T, bool> condition) where T : class, INamedItem {
289      if (parameter == null) throw new ArgumentNullException("parameter");
290      if (condition == null) throw new ArgumentNullException("condition");
291      string oldName = String.Empty;
292      if (parameter.Value != null) oldName = parameter.Value.Name;
293      parameter.ValidValues.Clear();
294      foreach (var item in ApplicationManager.Manager.GetInstances<T>().Where(condition)) {
295        parameter.ValidValues.Add(item);
296      }
297      var newItem = parameter.ValidValues.FirstOrDefault(x => x.Name == oldName);
298      if (newItem != null) parameter.Value = newItem;
299    }
300    #endregion
301  }
302}
Note: See TracBrowser for help on using the repository browser.