Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Algorithms.GRASP/3.3/GRASPWithPathRelinking.cs @ 17607

Last change on this file since 17607 was 16728, checked in by abeham, 6 years ago

#1614: updated to new persistence and .NET 4.6.1

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