Changeset 15562 for branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASP/GRASP.cs
- Timestamp:
- 12/29/17 23:56:43 (6 years ago)
- Location:
- branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASP
- Files:
-
- 1 added
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASP/GRASP.cs
r15561 r15562 23 23 using System.Linq; 24 24 using System.Threading; 25 using HeuristicLab.Analysis;26 25 using HeuristicLab.Common; 27 26 using HeuristicLab.Core; … … 31 30 using HeuristicLab.Parameters; 32 31 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 33 using HeuristicLab.Random;34 32 35 33 namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.GRASP { … … 41 39 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms)] 42 40 [StorableClass] 43 public class GRASP : BasicAlgorithm{41 public sealed class GRASP : StochasticAlgorithm<GRASPContext> { 44 42 45 43 public override bool SupportsPause { … … 57 55 58 56 [Storable] 59 private ValueParameter<IAnalyzer> analyzerParameter;60 public IValueParameter<IAnalyzer> AnalyzerParameter {61 get { return analyzerParameter; }62 }63 64 [Storable]65 private FixedValueParameter<BoolValue> setSeedRandomlyParameter;66 private IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {67 get { return setSeedRandomlyParameter; }68 }69 [Storable]70 private FixedValueParameter<IntValue> seedParameter;71 private IFixedValueParameter<IntValue> SeedParameter {72 get { return seedParameter; }73 }74 [Storable]75 57 private FixedValueParameter<IntValue> eliteSetSizeParameter; 76 58 private IFixedValueParameter<IntValue> EliteSetSizeParameter { … … 83 65 } 84 66 [Storable] 85 private FixedValueParameter<IntValue> maximumIterationsParameter;86 public IFixedValueParameter<IntValue> MaximumIterationsParameter {87 get { return maximumIterationsParameter; }88 }89 [Storable]90 67 private FixedValueParameter<IntValue> maximumLocalSearchIterationsParameter; 91 68 public IFixedValueParameter<IntValue> MaximumLocalSearchIterationsParameter { 92 get { return maximum IterationsParameter; }69 get { return maximumLocalSearchIterationsParameter; } 93 70 } 94 71 [Storable] … … 113 90 } 114 91 115 public bool SetSeedRandomly {116 get { return setSeedRandomlyParameter.Value.Value; }117 set { setSeedRandomlyParameter.Value.Value = value; }118 }119 public int Seed {120 get { return seedParameter.Value.Value; }121 set { seedParameter.Value.Value = value; }122 }123 92 public int EliteSetSize { 124 93 get { return eliteSetSizeParameter.Value.Value; } … … 129 98 set { minimiumEliteSetSizeParameter.Value.Value = value; } 130 99 } 131 public int MaximumIterations {132 get { return maximumIterationsParameter.Value.Value; }133 set { maximumIterationsParameter.Value.Value = value; }134 }135 100 public int MaximumLocalSearchIterations { 136 101 get { return maximumLocalSearchIterationsParameter.Value.Value; } … … 155 120 156 121 [StorableConstructor] 157 pr otectedGRASP(bool deserializing) : base(deserializing) { }158 pr otectedGRASP(GRASP original, Cloner cloner)122 private GRASP(bool deserializing) : base(deserializing) { } 123 private GRASP(GRASP original, Cloner cloner) 159 124 : base(original, cloner) { 160 setSeedRandomlyParameter = cloner.Clone(original.setSeedRandomlyParameter);161 seedParameter = cloner.Clone(original.seedParameter);162 analyzerParameter = cloner.Clone(original.analyzerParameter);163 125 eliteSetSizeParameter = cloner.Clone(original.eliteSetSizeParameter); 164 126 minimiumEliteSetSizeParameter = cloner.Clone(original.minimiumEliteSetSizeParameter); 165 maximumIterationsParameter = cloner.Clone(original.maximumIterationsParameter);166 127 maximumLocalSearchIterationsParameter = cloner.Clone(original.maximumLocalSearchIterationsParameter); 167 128 candidateSizeFactorParameter = cloner.Clone(original.candidateSizeFactorParameter); … … 169 130 oneMoveProbabilityParameter = cloner.Clone(original.oneMoveProbabilityParameter); 170 131 minimumDifferenceParameter = cloner.Clone(original.minimumDifferenceParameter); 171 context = cloner.Clone(original.context);172 132 } 173 133 public GRASP() { 174 Parameters.Add(setSeedRandomlyParameter = new FixedValueParameter<BoolValue>("SetSeedRandomly", "Whether to overwrite the seed with a random value each time the algorithm is run.", new BoolValue(true)));175 Parameters.Add(seedParameter = new FixedValueParameter<IntValue>("Seed", "The random seed that is used in the stochastic algorithm", new IntValue(0)));176 Parameters.Add(analyzerParameter = new ValueParameter<IAnalyzer>("Analyzer", "The analyzers that are used to perform an analysis of the solutions.", new MultiAnalyzer()));177 134 Parameters.Add(eliteSetSizeParameter = new FixedValueParameter<IntValue>("EliteSetSize", "The (maximum) size of the elite set.", new IntValue(10))); 178 135 Parameters.Add(minimiumEliteSetSizeParameter = new FixedValueParameter<IntValue>("MinimumEliteSetSize", "(ρ) The minimal size of the elite set, before local search and path relinking are applied.", new IntValue(2))); 179 Parameters.Add(maximumIterationsParameter = new FixedValueParameter<IntValue>("MaximumIterations", "The number of iterations that the algorithm should run.", new IntValue(1000)));180 136 Parameters.Add(maximumLocalSearchIterationsParameter = new FixedValueParameter<IntValue>("MaximumLocalSearchIteration", "The maximum number of iterations that the approximate local search should run", new IntValue(100))); 181 137 Parameters.Add(candidateSizeFactorParameter = new FixedValueParameter<PercentValue>("CandidateSizeFactor", "(η) Determines the size of the set of feasible moves in each path - relinking step relative to the maximum size.A value of 50 % means that only half of all possible moves are considered each step.", new PercentValue(0.5))); … … 183 139 Parameters.Add(oneMoveProbabilityParameter = new FixedValueParameter<PercentValue>("OneMoveProbability", "The probability for performing a 1-move, which is the opposite of performing a 2-move.", new PercentValue(.5))); 184 140 Parameters.Add(minimumDifferenceParameter = new FixedValueParameter<IntValue>("MinimumDifference", "The minimum amount of difference between two solutions so that they are both accepted in the elite set.", new IntValue(4))); 141 185 142 Problem = new GQAP(); 186 143 } … … 190 147 } 191 148 192 public override void Prepare() {193 base.Prepare();194 Results.Clear();195 context = null;196 }197 198 [Storable]199 private GRASPContext context;200 201 149 protected override void Initialize(CancellationToken cancellationToken) { 202 150 base.Initialize(cancellationToken); 203 context = new GRASPContext(); 204 context.Problem = Problem; 205 context.Scope.Variables.Add(new Variable("Results", Results)); 206 207 IExecutionContext ctxt = null; 208 foreach (var item in Problem.ExecutionContextItems) 209 ctxt = new Core.ExecutionContext(ctxt, item, context.Scope); 210 ctxt = new Core.ExecutionContext(ctxt, this, context.Scope); 211 context.Parent = ctxt; 212 213 if (SetSeedRandomly) { 214 var rnd = new System.Random(); 215 Seed = rnd.Next(); 216 } 217 context.Random = new MersenneTwister((uint)Seed); 218 context.Iterations = 0; 219 context.EvaluatedSolutions = 0; 220 context.BestQuality = double.NaN; 221 context.BestSolution = null; 222 223 context.Initialized = true; 224 225 Results.Add(new Result("Iterations", new IntValue(context.Iterations))); 226 Results.Add(new Result("EvaluatedSolutions", new IntValue(context.EvaluatedSolutions))); 227 Results.Add(new Result("BestQuality", new DoubleValue(context.BestQuality))); 151 152 Context.Problem = Problem; 153 Context.BestQuality = double.NaN; 154 Context.BestSolution = null; 155 156 Results.Add(new Result("Iterations", new IntValue(Context.Iterations))); 157 Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions))); 158 Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality))); 228 159 Results.Add(new Result("BestSolution", typeof(GQAPSolution))); 229 160 230 context.RunOperator(analyzerParameter.Value, context.Scope, cancellationToken);161 Context.RunOperator(Analyzer, Context.Scope, cancellationToken); 231 162 } 232 163 … … 235 166 while (!StoppingCriterion()) { // line 2 in Algorithm 1 236 167 // next: line 3 in Algorithm 1 237 var pi_prime_vec = GreedyRandomizedSolutionCreator.CreateSolution( context.Random, Problem.ProblemInstance, 1000, false, cancellationToken);238 if ( context.PopulationCount >= MinimumEliteSetSize) { // line 4 in Algorithm 1168 var pi_prime_vec = GreedyRandomizedSolutionCreator.CreateSolution(Context.Random, Problem.ProblemInstance, 1000, false, cancellationToken); 169 if (Context.PopulationCount >= MinimumEliteSetSize) { // line 4 in Algorithm 1 239 170 GQAPSolution pi_prime; 240 171 if (!Problem.ProblemInstance.IsFeasible(pi_prime_vec)) // line 5 in Algorithm 1 241 pi_prime = context.AtPopulation(context.Random.Next(context.PopulationCount)).Solution; // line 6 in Algorithm 1172 pi_prime = Context.AtPopulation(Context.Random.Next(Context.PopulationCount)).Solution; // line 6 in Algorithm 1 242 173 else { 243 174 // This is necessary, because pi_prime has not been evaluated yet and such details are not covered in Algorithm 1 244 175 pi_prime = Problem.ProblemInstance.ToEvaluatedSolution(pi_prime_vec); 245 context.EvaluatedSolutions++;176 Context.EvaluatedSolutions++; 246 177 } 247 178 248 179 ApproxLocalSearch(pi_prime); // line 8 in Algorithm 1 249 var pi_plus = context.AtPopulation(context.Random.Next(context.PopulationCount)); // line 9 in Algorithm 1180 var pi_plus = Context.AtPopulation(Context.Random.Next(Context.PopulationCount)); // line 9 in Algorithm 1 250 181 pi_prime = PathRelinking(pi_prime, pi_plus.Solution); // line 10 in Algorithm 1 251 182 ApproxLocalSearch(pi_prime); // line 11 in Algorithm 1 252 183 var fitness = Problem.ProblemInstance.ToSingleObjective(pi_prime.Evaluation); 253 184 // Book-keeping 254 if ( context.BestQuality > fitness) {255 context.BestQuality = fitness;256 context.BestSolution = (GQAPSolution)pi_prime.Clone();257 } 258 259 if ( context.PopulationCount == EliteSetSize) { // line 12 in Algorithm 1185 if (Context.BestQuality > fitness) { 186 Context.BestQuality = fitness; 187 Context.BestSolution = (GQAPSolution)pi_prime.Clone(); 188 } 189 190 if (Context.PopulationCount == EliteSetSize) { // line 12 in Algorithm 1 260 191 var fit = Problem.ProblemInstance.ToSingleObjective(pi_prime.Evaluation); 261 double[] similarities = context.Population.Select(x => HammingSimilarityCalculator.CalculateSimilarity(x.Solution.Assignment, pi_prime.Assignment)).ToArray();192 double[] similarities = Context.Population.Select(x => HammingSimilarityCalculator.CalculateSimilarity(x.Solution.Assignment, pi_prime.Assignment)).ToArray(); 262 193 if (similarities.Max() <= 1.0 - (MinimumDifference / (double)pi_prime.Assignment.Length)) { // cond. 2 of line 13 in Algorithm 1 263 var replacement = context.Population.Select((v, i) => new { V = v, Index = i })194 var replacement = Context.Population.Select((v, i) => new { V = v, Index = i }) 264 195 .Where(x => x.V.Fitness >= fit).ToArray(); 265 196 if (replacement.Length > 0) { // cond. 1 of line 13 in Algorithm 1 266 197 // next two lines: line 14 in Algorithm 1 267 198 replacement = replacement.OrderBy(x => similarities[x.Index]).ToArray(); 268 context.ReplaceAtPopulation(replacement.Last().Index, context.ToScope(pi_prime, fit));199 Context.ReplaceAtPopulation(replacement.Last().Index, Context.ToScope(pi_prime, fit)); 269 200 } 270 201 } 271 202 } else if (IsSufficientlyDifferent(pi_prime.Assignment)) { // line 17 in Algorithm 1 272 context.AddToPopulation(context.ToScope(pi_prime, Problem.ProblemInstance.ToSingleObjective(pi_prime.Evaluation))); // line 18 in Algorithm 1203 Context.AddToPopulation(Context.ToScope(pi_prime, Problem.ProblemInstance.ToSingleObjective(pi_prime.Evaluation))); // line 18 in Algorithm 1 273 204 } 274 205 } else if (Problem.ProblemInstance.IsFeasible(pi_prime_vec) /* cond. 1 of line 21 in Algorithm 1 */ 275 206 && IsSufficientlyDifferent(pi_prime_vec)) /* cond. 2 of line 21 in Algorithm 1 */ { 276 207 var pi_prime = Problem.ProblemInstance.ToEvaluatedSolution(pi_prime_vec); 277 context.EvaluatedSolutions++;208 Context.EvaluatedSolutions++; 278 209 var fitness = Problem.ProblemInstance.ToSingleObjective(pi_prime.Evaluation); 279 context.AddToPopulation(context.ToScope(pi_prime, fitness)); /* line 22 in Algorithm 1 */210 Context.AddToPopulation(Context.ToScope(pi_prime, fitness)); /* line 22 in Algorithm 1 */ 280 211 // Book-keeping 281 if ( context.PopulationCount == 1 || context.BestQuality > fitness) {282 context.BestQuality = fitness;283 context.BestSolution = (GQAPSolution)pi_prime.Clone();212 if (Context.PopulationCount == 1 || Context.BestQuality > fitness) { 213 Context.BestQuality = fitness; 214 Context.BestSolution = (GQAPSolution)pi_prime.Clone(); 284 215 } 285 216 } … … 287 218 IResult result; 288 219 if (Results.TryGetValue("Iterations", out result)) 289 ((IntValue)result.Value).Value = context.Iterations;290 else Results.Add(new Result("Iterations", new IntValue( context.Iterations)));220 ((IntValue)result.Value).Value = Context.Iterations; 221 else Results.Add(new Result("Iterations", new IntValue(Context.Iterations))); 291 222 if (Results.TryGetValue("EvaluatedSolutions", out result)) 292 ((IntValue)result.Value).Value = context.EvaluatedSolutions;293 else Results.Add(new Result("EvaluatedSolutions", new IntValue( context.EvaluatedSolutions)));223 ((IntValue)result.Value).Value = Context.EvaluatedSolutions; 224 else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions))); 294 225 if (Results.TryGetValue("BestQuality", out result)) 295 ((DoubleValue)result.Value).Value = context.BestQuality;296 else Results.Add(new Result("BestQuality", new DoubleValue( context.BestQuality)));226 ((DoubleValue)result.Value).Value = Context.BestQuality; 227 else Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality))); 297 228 if (Results.TryGetValue("BestSolution", out result)) 298 result.Value = context.BestSolution; 299 else Results.Add(new Result("BestSolution", context.BestSolution)); 300 301 context.RunOperator(analyzerParameter.Value, context.Scope, cancellationToken); 302 303 context.Iterations++; 229 result.Value = Context.BestSolution; 230 else Results.Add(new Result("BestSolution", Context.BestSolution)); 231 232 Context.RunOperator(Analyzer, Context.Scope, cancellationToken); 233 234 Context.Iterations++; 235 if (cancellationToken.IsCancellationRequested) break; 304 236 } 305 237 } 306 238 307 239 private bool IsSufficientlyDifferent(IntegerVector vec) { 308 return context.Population.All(x =>240 return Context.Population.All(x => 309 241 HammingSimilarityCalculator.CalculateSimilarity(vec, x.Solution.Assignment) <= 1.0 - (MinimumDifference / (double)vec.Length) 310 242 ); … … 327 259 int evaluatedSolutions; 328 260 // lines 2-36 of Algorithm 4 are implemented in the following call 329 var pi_star = GQAPPathRelinking.Apply( context.Random, source, sourceEval,261 var pi_star = GQAPPathRelinking.Apply(Context.Random, source, sourceEval, 330 262 target, targetEval, Problem.ProblemInstance, CandidateSizeFactor, 331 263 out evaluatedSolutions); 332 context.EvaluatedSolutions += evaluatedSolutions;264 Context.EvaluatedSolutions += evaluatedSolutions; 333 265 return pi_star; 334 266 } … … 336 268 private void ApproxLocalSearch(GQAPSolution pi_prime) { 337 269 var localSearchEvaluations = 0; 338 ApproximateLocalSearch.Apply( context.Random, pi_prime, MaximumCandidateListSize,270 ApproximateLocalSearch.Apply(Context.Random, pi_prime, MaximumCandidateListSize, 339 271 OneMoveProbability, MaximumLocalSearchIterations, Problem.ProblemInstance, out localSearchEvaluations); 340 context.EvaluatedSolutions += localSearchEvaluations; 341 } 342 343 private bool StoppingCriterion() { 344 return context.Iterations > MaximumIterations; 272 Context.EvaluatedSolutions += localSearchEvaluations; 345 273 } 346 274 }
Note: See TracChangeset
for help on using the changeset viewer.