Changeset 14552 for branches/MemPRAlgorithm
- Timestamp:
- 01/09/17 00:36:20 (8 years ago)
- Location:
- branches/MemPRAlgorithm
- Files:
-
- 1 deleted
- 27 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/BinaryMemPR.cs
r14551 r14552 38 38 [StorableClass] 39 39 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)] 40 public class BinaryMemPR : MemPRAlgorithm< SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> {40 public class BinaryMemPR : MemPRAlgorithm<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> { 41 41 [StorableConstructor] 42 42 protected BinaryMemPR(bool deserializing) : base(deserializing) { } … … 66 66 } 67 67 68 protected override ISingleObjectiveSolutionScope<BinaryVector> ToScope(BinaryVector code, double fitness = double.NaN) {69 var creator = Problem.SolutionCreator as IBinaryVectorCreator;70 if (creator == null) throw new InvalidOperationException("Can only solve binary encoded problems with MemPR (binary)");71 return new SingleObjectiveSolutionScope<BinaryVector>(code, creator.BinaryVectorParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {72 Parent = Context.Scope73 };74 }75 76 68 protected override ISolutionSubspace<BinaryVector> CalculateSubspace(IEnumerable<BinaryVector> solutions, bool inverse = false) { 77 69 var pop = solutions.ToList(); … … 92 84 var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null; 93 85 if (double.IsNaN(scope.Fitness)) { 94 Evaluate(scope, token);86 Context.Evaluate(scope, token); 95 87 evaluations++; 96 88 } … … 104 96 var order = Enumerable.Range(0, N).Where(x => subset == null || subset[x]).Shuffle(Context.Random).ToArray(); 105 97 106 var bound = Problem.Maximization ? Context.Population.Max(x => x.Fitness) : Context.Population.Min(x => x.Fitness);98 var bound = Context.Maximization ? Context.Population.Max(x => x.Fitness) : Context.Population.Min(x => x.Fitness); 107 99 var range = Math.Abs(bound - Context.LocalOptimaLevel); 108 100 if (range.IsAlmost(0)) range = Math.Abs(bound * 0.05); … … 122 114 var before = currentScope.Fitness; 123 115 current[idx] = !current[idx]; 124 Evaluate(currentScope, token);116 Context.Evaluate(currentScope, token); 125 117 evaluations++; 126 118 var after = currentScope.Fitness; … … 133 125 } 134 126 } 135 var diff = Problem.Maximization ? after - before : before - after;127 var diff = Context.Maximization ? after - before : before - after; 136 128 if (diff > 0) moved = true; 137 129 else { … … 158 150 var N = p1.Solution.Length; 159 151 160 var probe = ToScope((BinaryVector)p1.Solution.Clone());152 var probe = Context.ToScope((BinaryVector)p1.Solution.Clone()); 161 153 162 154 var cache = new HashSet<BinaryVector>(new BinaryVectorEqualityComparer()); … … 179 171 continue; 180 172 } 181 Evaluate(probe, token);173 Context.Evaluate(probe, token); 182 174 evaluations++; 183 175 cache.Add(c); … … 210 202 var idx = order[i]; 211 203 child[idx] = !child[idx]; // move 212 Evaluate(childScope, token);204 Context.Evaluate(childScope, token); 213 205 evaluations++; 214 206 var s = childScope.Fitness; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/BinaryMemPRContext.cs
r14450 r14552 20 20 #endregion 21 21 22 using System; 22 23 using HeuristicLab.Algorithms.MemPR.Interfaces; 23 24 using HeuristicLab.Common; … … 31 32 [Item("MemPR Population Context (binary)", "MemPR population context for binary encoded problems.")] 32 33 [StorableClass] 33 public sealed class BinaryMemPRPopulationContext : MemPRPopulationContext< SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> {34 public sealed class BinaryMemPRPopulationContext : MemPRPopulationContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> { 34 35 35 36 [StorableConstructor] … … 47 48 return new BinaryMemPRSolutionContext(this, solution); 48 49 } 50 51 public override ISingleObjectiveSolutionScope<BinaryVector> ToScope(BinaryVector code, double fitness = double.NaN) { 52 var creator = Problem.SolutionCreator as IBinaryVectorCreator; 53 if (creator == null) throw new InvalidOperationException("MemPR (binary) context expects a problem with an IBinaryVectorCreator as solution creator."); 54 return new SingleObjectiveSolutionScope<BinaryVector>(code, creator.BinaryVectorParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) { 55 Parent = Scope 56 }; 57 } 49 58 } 50 59 51 60 [Item("MemPR Solution Context (binary)", "MemPR solution context for binary encoded problems.")] 52 61 [StorableClass] 53 public sealed class BinaryMemPRSolutionContext : MemPRSolutionContext< SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext>, IBinaryVectorSubspaceContext {62 public sealed class BinaryMemPRSolutionContext : MemPRSolutionContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext>, IBinaryVectorSubspaceContext { 54 63 55 64 [Storable] -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/ExhaustiveBitflip.cs
r14450 r14552 33 33 [Item("Exhaustive Bitflip Local Search (binary)", "", ExcludeGenericTypeInfo = true)] 34 34 [StorableClass] 35 public class ExhaustiveBitflip<TContext> : NamedItem, ILocalSearch<TContext> where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector> { 35 public class ExhaustiveBitflip<TContext> : NamedItem, ILocalSearch<TContext> 36 where TContext : ISingleSolutionHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector>, 37 IEvaluationServiceContext<BinaryVector> { 36 38 37 39 [StorableConstructor] … … 48 50 49 51 public void Optimize(TContext context) { 50 var evalWrapper = new EvaluationWrapper<BinaryVector>(context.Problem, context.Solution);51 52 var quality = context.Solution.Fitness; 52 53 try { 53 54 var result = ExhaustiveBitflip.Optimize(context.Random, context.Solution.Solution, ref quality, 54 context. Problem.Maximization, evalWrapper.Evaluate, CancellationToken.None);55 context.Maximization, context.Evaluate, CancellationToken.None); 55 56 context.IncrementEvaluatedSolutions(result.Item1); 56 57 context.Iterations = result.Item2; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/ExhaustiveBitflipSubspace.cs
r14466 r14552 34 34 [StorableClass] 35 35 public class ExhaustiveBitflipSubspace<TContext> : NamedItem, ILocalSearch<TContext> 36 where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, IBinaryVectorSubspaceContext { 36 where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, 37 IBinaryVectorSubspaceContext, IEvaluationServiceContext<BinaryVector> { 37 38 38 39 [StorableConstructor] … … 49 50 50 51 public void Optimize(TContext context) { 51 var evalWrapper = new EvaluationWrapper<BinaryVector>(context.Problem, context.Solution);52 52 var quality = context.Solution.Fitness; 53 53 try { 54 54 var result = ExhaustiveBitflip.Optimize(context.Random, context.Solution.Solution, ref quality, 55 context.Problem.Maximization, evalWrapper.Evaluate, CancellationToken.None, context.Subspace.Subspace);55 context.Problem.Maximization, context.Evaluate, CancellationToken.None, context.Subspace.Subspace); 56 56 context.IncrementEvaluatedSolutions(result.Item1); 57 57 context.Iterations = result.Item2; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/StaticAPI/ExhaustiveBitflip.cs
r14450 r14552 30 30 namespace HeuristicLab.Encodings.Binary.LocalSearch { 31 31 public static class ExhaustiveBitflip { 32 public static Tuple<int, int> Optimize(IRandom random, BinaryVector solution, ref double quality, bool maximization, Func<BinaryVector, double> evalFunc, CancellationToken token, bool[] subspace = null) {33 if (double.IsNaN(quality)) quality = evalFunc(solution );32 public static Tuple<int, int> Optimize(IRandom random, BinaryVector solution, ref double quality, bool maximization, Func<BinaryVector, CancellationToken, double> evalFunc, CancellationToken token, bool[] subspace = null) { 33 if (double.IsNaN(quality)) quality = evalFunc(solution, token); 34 34 var improved = false; 35 35 var order = Enumerable.Range(0, solution.Length).Shuffle(random).ToArray(); … … 47 47 // bitflip the solution 48 48 solution[idx] = !solution[idx]; 49 var after = evalFunc(solution );49 var after = evalFunc(solution, token); 50 50 evaluations++; 51 51 if (FitnessComparer.IsBetter(maximization, after, quality)) { -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/SolutionModel/Univariate/BiasedModelTrainer.cs
r14450 r14552 34 34 [StorableClass] 35 35 public class BiasedModelTrainer<TContext> : ParameterizedNamedItem, ISolutionModelTrainer<TContext> 36 where TContext : IPopulationBasedHeuristicAlgorithmContext< SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, ISolutionModelContext<BinaryVector> {36 where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector>, ISolutionModelContext<BinaryVector> { 37 37 38 38 [Storable] … … 58 58 59 59 public void TrainModel(TContext context) { 60 context.Model = Trainer.TrainBiased(ModelBias, context.Random, context. Problem.Maximization, context.Population.Select(x => x.Solution), context.Population.Select(x => x.Fitness));60 context.Model = Trainer.TrainBiased(ModelBias, context.Random, context.Maximization, context.Population.Select(x => x.Solution), context.Population.Select(x => x.Fitness)); 61 61 } 62 62 } -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/SolutionModel/Univariate/UnbiasedModelTrainer.cs
r14450 r14552 32 32 [StorableClass] 33 33 public class UniasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext> 34 where TContext : IPopulationBasedHeuristicAlgorithmContext< SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, ISolutionModelContext<BinaryVector> {34 where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector>, ISolutionModelContext<BinaryVector> { 35 35 36 36 [StorableConstructor] -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/HeuristicLab.Algorithms.MemPR-3.3.csproj
r14544 r14552 129 129 <Compile Include="Properties\AssemblyInfo.cs" /> 130 130 <Compile Include="Util\CkMeans1D.cs" /> 131 <Compile Include="Util\EvaluationWrapper.cs" />132 131 <Compile Include="Util\FitnessComparer.cs" /> 133 132 </ItemGroup> -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Interfaces/Interfaces.cs
r14544 r14552 21 21 22 22 using System.Collections.Generic; 23 using System.Threading; 23 24 using HeuristicLab.Algorithms.MemPR.Binary; 24 25 using HeuristicLab.Algorithms.MemPR.Grouping; … … 63 64 64 65 public interface IHeuristicAlgorithmContext<TProblem, TSolution> : IExecutionContext 65 where TProblem : class, ISingleObjective ProblemDefinition{66 where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem { 66 67 TProblem Problem { get; } 68 bool Maximization { get; } 67 69 IRandom Random { get; } 68 70 int Iterations { get; set; } … … 73 75 } 74 76 77 public interface IEvaluationServiceContext<TSolution> : IExecutionContext { 78 double Evaluate(TSolution solution, CancellationToken token); 79 void Evaluate(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token); 80 } 81 75 82 public interface IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution> : IHeuristicAlgorithmContext<TProblem, TSolution> 76 where TProblem : class, ISingleObjective ProblemDefinition{83 where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem { 77 84 IEnumerable<ISingleObjectiveSolutionScope<TSolution>> Population { get; } 78 85 } 79 86 80 87 public interface ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution> : IHeuristicAlgorithmContext<TProblem, TSolution> 81 where TProblem : class, ISingleObjective ProblemDefinition{88 where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem { 82 89 ISingleObjectiveSolutionScope<TSolution> Solution { get; } 83 90 } -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LinearLinkageMemPR.cs
r14551 r14552 37 37 [StorableClass] 38 38 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)] 39 public class LinearLinkageMemPR : MemPRAlgorithm< SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {39 public class LinearLinkageMemPR : MemPRAlgorithm<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> { 40 40 [StorableConstructor] 41 41 protected LinearLinkageMemPR(bool deserializing) : base(deserializing) { } … … 69 69 } 70 70 71 protected override ISingleObjectiveSolutionScope<LinearLinkage> ToScope(LinearLinkage code, double fitness = double.NaN) {72 var creator = Problem.SolutionCreator as ILinearLinkageCreator;73 if (creator == null) throw new InvalidOperationException("Can only solve linear linkage encoded problems with MemPR (linear linkage)");74 return new SingleObjectiveSolutionScope<LinearLinkage>(code, creator.LLEParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {75 Parent = Context.Scope76 };77 }78 79 71 protected override ISolutionSubspace<LinearLinkage> CalculateSubspace(IEnumerable<LinearLinkage> solutions, bool inverse = false) { 80 72 var pop = solutions.ToList(); … … 95 87 int maxEvals, CancellationToken token, 96 88 ISolutionSubspace<LinearLinkage> sub_space = null) { 97 var maximization = Context. Problem.Maximization;89 var maximization = Context.Maximization; 98 90 var subspace = sub_space is LinearLinkageSolutionSubspace ? ((LinearLinkageSolutionSubspace)sub_space).Subspace : null; 99 91 var evaluations = 0; 100 92 var quality = scope.Fitness; 101 93 if (double.IsNaN(quality)) { 102 Evaluate(scope, token);94 Context.Evaluate(scope, token); 103 95 quality = scope.Fitness; 104 96 evaluations++; … … 168 160 move.Apply(current); 169 161 var qualityToRestore = tabu[i, current[i]]; // current[i] is new next 170 Evaluate(currentScope, token);162 Context.Evaluate(currentScope, token); 171 163 evaluations++; 172 164 var moveF = currentScope.Fitness; … … 255 247 var cachehits = 0; 256 248 var evaluations = 0; 257 var probe = ToScope((LinearLinkage)p1.Solution.Clone());249 var probe = Context.ToScope((LinearLinkage)p1.Solution.Clone()); 258 250 ISingleObjectiveSolutionScope<LinearLinkage> offspring = null; 259 251 while (evaluations < p1.Solution.Length) { … … 268 260 continue; 269 261 } 270 Evaluate(probe, token);262 Context.Evaluate(probe, token); 271 263 evaluations++; 272 264 cache.Add(c); … … 283 275 protected override ISingleObjectiveSolutionScope<LinearLinkage> Link(ISingleObjectiveSolutionScope<LinearLinkage> a, ISingleObjectiveSolutionScope<LinearLinkage> b, CancellationToken token, bool delink = false) { 284 276 var evaluations = 0; 285 if (double.IsNaN(a.Fitness)) {286 Evaluate(a, token);287 evaluations++;288 }289 if (double.IsNaN(b.Fitness)) {290 Evaluate(b, token);291 evaluations++;292 }293 294 277 var probe = (ISingleObjectiveSolutionScope<LinearLinkage>)a.Clone(); 295 278 ISingleObjectiveSolutionScope<LinearLinkage> best = null; … … 306 289 if (delink && distAfter > distBefore || !delink && distAfter < distBefore) { 307 290 var beforeQ = probe.Fitness; 308 Evaluate(probe, token);291 Context.Evaluate(probe, token); 309 292 evaluations++; 310 293 var q = probe.Fitness; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LinearLinkageMemPRContext.cs
r14544 r14552 20 20 #endregion 21 21 22 using System; 23 using System.Runtime.Remoting.Contexts; 22 24 using HeuristicLab.Algorithms.MemPR.Interfaces; 23 25 using HeuristicLab.Common; … … 31 33 [Item("MemPR Population Context (linear linkage)", "MemPR population context for linear linkage encoded problems.")] 32 34 [StorableClass] 33 public sealed class LinearLinkageMemPRPopulationContext : MemPRPopulationContext< SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {35 public sealed class LinearLinkageMemPRPopulationContext : MemPRPopulationContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> { 34 36 35 37 [StorableConstructor] … … 47 49 return new LinearLinkageMemPRSolutionContext(this, solution); 48 50 } 51 52 public override ISingleObjectiveSolutionScope<LinearLinkage> ToScope(LinearLinkage code, double fitness = double.NaN) { 53 var creator = Problem.SolutionCreator as ILinearLinkageCreator; 54 if (creator == null) throw new InvalidOperationException("Can only solve linear linkage encoded problems with MemPR (linear linkage)"); 55 return new SingleObjectiveSolutionScope<LinearLinkage>(code, creator.LLEParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) { 56 Parent = Scope 57 }; 58 } 49 59 } 50 60 51 61 [Item("MemPR Solution Context (linear linkage)", "MemPR solution context for linear linkage encoded problems.")] 52 62 [StorableClass] 53 public sealed class LinearLinkageMemPRSolutionContext : MemPRSolutionContext< SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext>, ILinearLinkageSubspaceContext {63 public sealed class LinearLinkageMemPRSolutionContext : MemPRSolutionContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext>, ILinearLinkageSubspaceContext { 54 64 55 65 [Storable] -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LocalSearch/ExhaustiveSubspace.cs
r14544 r14552 22 22 using System.Threading; 23 23 using HeuristicLab.Algorithms.MemPR.Interfaces; 24 using HeuristicLab.Algorithms.MemPR.Util;25 24 using HeuristicLab.Common; 26 25 using HeuristicLab.Core; … … 33 32 [StorableClass] 34 33 public class ExhaustiveSubspace<TContext> : NamedItem, ILocalSearch<TContext> 35 where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage>, ILinearLinkageSubspaceContext { 34 where TContext : ISingleSolutionHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage>, 35 ILinearLinkageSubspaceContext, IEvaluationServiceContext<LinearLinkage> { 36 36 37 37 [StorableConstructor] … … 48 48 49 49 public void Optimize(TContext context) { 50 var evalWrapper = new EvaluationWrapper<LinearLinkage>(context.Problem, context.Solution);51 50 var quality = context.Solution.Fitness; 52 51 try { 53 52 var result = ExhaustiveLocalSearch.Optimize(context.Random, context.Solution.Solution, ref quality, 54 context. Problem.Maximization, evalWrapper.Evaluate, CancellationToken.None, context.Subspace.Subspace);53 context.Maximization, context.Evaluate, CancellationToken.None, context.Subspace.Subspace); 55 54 context.IncrementEvaluatedSolutions(result.Item1); 56 55 context.Iterations = result.Item2; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LocalSearch/StaticAPI/ExhaustiveLocalSearch.cs
r14544 r14552 21 21 22 22 using System; 23 using System.Collections.Generic; 23 24 using System.Linq; 24 25 using System.Threading; 25 26 using HeuristicLab.Algorithms.MemPR.Util; 26 using HeuristicLab.Collections;27 27 using HeuristicLab.Core; 28 28 using HeuristicLab.Encodings.LinearLinkageEncoding; … … 30 30 namespace HeuristicLab.Algorithms.MemPR.Grouping.LocalSearch { 31 31 public static class ExhaustiveLocalSearch { 32 public static Tuple<int, int> Optimize(IRandom random, LinearLinkage solution, ref double quality, bool maximization, Func<LinearLinkage, IRandom, double> eval, CancellationToken token, bool[] subspace = null) {32 public static Tuple<int, int> Optimize(IRandom random, LinearLinkage solution, ref double quality, bool maximization, Func<LinearLinkage, CancellationToken, double> eval, CancellationToken token, bool[] subspace = null) { 33 33 var evaluations = 0; 34 var current = solution;35 34 if (double.IsNaN(quality)) { 36 quality = eval( current, random);35 quality = eval(solution, token); 37 36 evaluations++; 38 37 } 39 38 var steps = 0; 40 // this dictionary holds the last relevant links 41 var links = new BidirectionalDictionary<int, int>(); 39 var lleb = solution.ToBackLinks(); 42 40 for (var iter = 0; iter < int.MaxValue; iter++) { 43 41 var change = false; 44 // clear the dictionary before a new pass through the array is made 45 links.Clear(); 46 for (var i = 0; i < current.Length; i++) { 47 if (subspace != null && !subspace[i]) { 48 links.RemoveBySecond(i); 49 links.Add(i, current[i]); 50 continue; 51 } 52 var pred = -1; 53 var isFirst = !links.TryGetBySecond(i, out pred); 54 var keepLink = false; 55 if (!isFirst) { 56 keepLink = subspace != null && !subspace[pred]; 57 } 58 var next = current[i]; 59 var isLast = next == i; 60 61 if (!keepLink) { 62 // try to insert current into each previous group 63 // first remove i from its group 64 var linksList = links.Where(x => x.Value != i).ToList(); 65 if (linksList.Count > 0 && !isFirst) current[pred] = isLast ? pred : next; 66 for (var k = 0; k < linksList.Count; k++) { 67 var l = linksList[k]; 68 current[l.Key] = i; 69 current[i] = Math.Max(i, l.Value); 70 var moveF = eval(current, random); 71 evaluations++; 72 if (FitnessComparer.IsBetter(maximization, moveF, quality)) { 73 steps++; 74 quality = moveF; 75 change = true; 76 links.RemoveBySecond(i); 77 links.SetByFirst(l.Key, i); // otherwise the link won't be removed 78 if (!isFirst) links.SetByFirst(pred, isLast ? pred : next); 79 next = current[i]; 80 if (next == i) { isLast = true; } 81 pred = l.Key; 82 isFirst = false; 83 break; 84 } else { // undo 85 current[l.Key] = l.Value; 86 if (k == linksList.Count - 1) { 87 // all attempts unsuccessful 88 if (!isFirst) current[pred] = i; // undo - readd i to its group 89 current[i] = next; 90 } 91 } 92 } 93 } 94 95 if (!isLast) { 96 // try to split group at this point 97 // this is safe even if keepLink was true 98 current[i] = i; 99 var moveF = eval(current, random); 42 var groupItems = new List<int>(); 43 for (var i = 0; i < solution.Length; i++) { 44 foreach (var move in MoveGenerator.GenerateForItem(i, groupItems, solution, lleb).ToList()) { 45 move.Apply(solution); 46 var moveF = eval(solution, token); 100 47 evaluations++; 101 48 if (FitnessComparer.IsBetter(maximization, moveF, quality)) { 49 move.ApplyToLLEb(lleb); 102 50 steps++; 103 51 quality = moveF; 104 52 change = true; 105 isLast = true;106 next = i;107 links.SetBySecond(i, i);108 continue;109 } else current[i] = next; // undo53 break; 54 } else { 55 move.Undo(solution); 56 } 57 if (token.IsCancellationRequested) break; 110 58 } 111 112 if (isFirst && !isLast) { 113 // try merge with all terminated groups 114 foreach (var l in links.Where(x => x.Key == x.Value && (subspace == null || subspace[x.Key]))) { 115 current[l.Key] = i; 116 var moveF = eval(current, random); 117 evaluations++; 118 if (FitnessComparer.IsBetter(maximization, moveF, quality)) { 119 steps++; 120 quality = moveF; 121 change = true; 122 isFirst = false; 123 pred = l.Key; 124 links.SetByFirst(l.Key, i); 125 break; 126 } else { 127 current[l.Key] = l.Value; 128 } 129 } 130 } else if (!isFirst && !keepLink) { 131 // try to extract current into own group 132 current[pred] = isLast ? pred : next; 133 current[i] = i; 134 var moveF = eval(current, random); 135 evaluations++; 136 if (FitnessComparer.IsBetter(maximization, moveF, quality)) { 137 steps++; 138 links.SetByFirst(pred, current[pred]); 139 quality = moveF; 140 change = true; 141 } else { // undo 142 current[pred] = i; 143 current[i] = next; 144 } 145 } 146 links.RemoveBySecond(i); 147 links.Add(i, current[i]); 59 if (lleb[i] != i) 60 groupItems.Remove(lleb[i]); 61 groupItems.Add(i); 148 62 if (token.IsCancellationRequested) break; 149 63 } … … 154 68 } 155 69 156 public static Tuple<int, int> OptimizeSwap Only(IRandom random, LinearLinkage solution, ref double quality, bool maximization, Func<LinearLinkage, IRandom, double> eval, CancellationToken token) {70 public static Tuple<int, int> OptimizeSwap(IRandom random, LinearLinkage solution, ref double quality, bool maximization, Func<LinearLinkage, IRandom, double> eval, CancellationToken token) { 157 71 var evaluations = 0; 158 72 var current = solution; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/SolutionModel/Univariate/UnbiasedModelTrainer.cs
r14544 r14552 32 32 [StorableClass] 33 33 public class UniasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext> 34 where TContext : IPopulationBasedHeuristicAlgorithmContext< SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage>, ISolutionModelContext<LinearLinkage> {34 where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage>, ISolutionModelContext<LinearLinkage> { 35 35 36 36 [StorableConstructor] -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/MemPRAlgorithm.cs
r14551 r14552 39 39 [StorableClass] 40 40 public abstract class MemPRAlgorithm<TProblem, TSolution, TPopulationContext, TSolutionContext> : BasicAlgorithm, INotifyPropertyChanged 41 where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem , ISingleObjectiveProblemDefinition41 where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem 42 42 where TSolution : class, IItem 43 43 where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext>, new() … … 425 425 } 426 426 427 RunOperator(Analyzer, Context.Scope, token);427 Context.RunOperator(Analyzer, Context.Scope, token); 428 428 } 429 429 430 430 protected bool Replace(ISingleObjectiveSolutionScope<TSolution> child, CancellationToken token) { 431 431 if (double.IsNaN(child.Fitness)) { 432 Evaluate(child, token);432 Context.Evaluate(child, token); 433 433 Context.IncrementEvaluatedSolutions(1); 434 434 } … … 524 524 protected abstract bool Eq(TSolution a, TSolution b); 525 525 protected abstract double Dist(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b); 526 protected abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN);527 526 protected abstract ISolutionSubspace<TSolution> CalculateSubspace(IEnumerable<TSolution> solutions, bool inverse = false); 528 protected virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token) {529 var prob = Problem as ISingleObjectiveProblemDefinition;530 if (prob != null) {531 var ind = new SingleEncodingIndividual(prob.Encoding, scope);532 scope.Fitness = prob.Evaluate(ind, Context.Random);533 } else RunOperator(Problem.Evaluator, scope, token);534 }535 527 536 528 #region Create 537 529 protected virtual ISingleObjectiveSolutionScope<TSolution> Create(CancellationToken token) { 538 var child = ToScope(null);539 RunOperator(Problem.SolutionCreator, child, token);530 var child = Context.ToScope(null); 531 Context.RunOperator(Problem.SolutionCreator, child, token); 540 532 return child; 541 533 } … … 545 537 protected virtual int HillClimb(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) { 546 538 if (double.IsNaN(scope.Fitness)) { 547 Evaluate(scope, token);539 Context.Evaluate(scope, token); 548 540 Context.IncrementEvaluatedSolutions(1); 549 541 } … … 560 552 protected virtual void AdaptiveClimb(ISingleObjectiveSolutionScope<TSolution> scope, int maxEvals, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) { 561 553 if (double.IsNaN(scope.Fitness)) { 562 Evaluate(scope, token);554 Context.Evaluate(scope, token); 563 555 Context.IncrementEvaluatedSolutions(1); 564 556 } … … 585 577 586 578 if (double.IsNaN(p1.Fitness)) { 587 Evaluate(p1, token);579 Context.Evaluate(p1, token); 588 580 Context.IncrementEvaluatedSolutions(1); 589 581 } 590 582 if (double.IsNaN(p2.Fitness)) { 591 Evaluate(p2, token);583 Context.Evaluate(p2, token); 592 584 Context.IncrementEvaluatedSolutions(1); 593 585 } … … 597 589 598 590 if (double.IsNaN(offspring.Fitness)) { 599 Evaluate(offspring, token);591 Context.Evaluate(offspring, token); 600 592 Context.IncrementEvaluatedSolutions(1); 601 593 } … … 630 622 var link = PerformRelinking(p1, p2, token, delink: false); 631 623 if (double.IsNaN(link.Fitness)) { 632 Evaluate(link, token);624 Context.Evaluate(link, token); 633 625 Context.IncrementEvaluatedSolutions(1); 634 626 } … … 654 646 var link = PerformRelinking(p1, p2, token, delink: true); 655 647 if (double.IsNaN(link.Fitness)) { 656 Evaluate(link, token);648 Context.Evaluate(link, token); 657 649 Context.IncrementEvaluatedSolutions(1); 658 650 } … … 668 660 669 661 if (double.IsNaN(relink.Fitness)) { 670 Evaluate(relink, token);662 Context.Evaluate(relink, token); 671 663 Context.IncrementEvaluatedSolutions(1); 672 664 } … … 696 688 var tries = 1; 697 689 for (; tries < 100; tries++) { 698 var sample = ToScope(Context.Model.Sample());699 Evaluate(sample, token);690 var sample = Context.ToScope(Context.Model.Sample()); 691 Context.Evaluate(sample, token); 700 692 if (bestSample == null || Context.IsBetter(sample, bestSample)) { 701 693 bestSample = sample; … … 714 706 715 707 protected virtual bool Terminate() { 708 var maximization = ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; 716 709 return MaximumEvaluations.HasValue && Context.EvaluatedSolutions >= MaximumEvaluations.Value 717 710 || MaximumExecutionTime.HasValue && ExecutionTime >= MaximumExecutionTime.Value 718 || TargetQuality.HasValue && ( Problem.Maximization && Context.BestQuality >= TargetQuality.Value719 || ! Problem.Maximization && Context.BestQuality <= TargetQuality.Value);711 || TargetQuality.HasValue && (maximization && Context.BestQuality >= TargetQuality.Value 712 || !maximization && Context.BestQuality <= TargetQuality.Value); 720 713 } 721 714 … … 725 718 if (handler != null) handler(this, new PropertyChangedEventArgs(property)); 726 719 } 727 728 #region Engine Helper729 protected void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {730 var stack = new Stack<IOperation>();731 stack.Push(Context.CreateChildOperation(op, scope));732 733 while (stack.Count > 0) {734 cancellationToken.ThrowIfCancellationRequested();735 736 var next = stack.Pop();737 if (next is OperationCollection) {738 var coll = (OperationCollection)next;739 for (int i = coll.Count - 1; i >= 0; i--)740 if (coll[i] != null) stack.Push(coll[i]);741 } else if (next is IAtomicOperation) {742 var operation = (IAtomicOperation)next;743 try {744 next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);745 } catch (Exception ex) {746 stack.Push(operation);747 if (ex is OperationCanceledException) throw ex;748 else throw new OperatorExecutionException(operation.Operator, ex);749 }750 if (next != null) stack.Push(next);751 }752 }753 }754 #endregion755 720 } 756 721 } -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/MemPRContext.cs
r14550 r14552 41 41 [StorableClass] 42 42 public abstract class MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext> : ParameterizedNamedItem, 43 IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution>, ISolutionModelContext<TSolution> 44 where TProblem : class, IItem, ISingleObjective ProblemDefinition43 IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution>, ISolutionModelContext<TSolution>, IEvaluationServiceContext<TSolution> 44 where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem 45 45 where TSolution : class, IItem 46 46 where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext> … … 70 70 set { problem.Value = value; } 71 71 } 72 public bool Maximization { 73 get { return ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; } 74 } 72 75 73 76 [Storable] … … 182 185 } 183 186 public void SortPopulation() { 184 scope.SubScopes.Replace(scope.SubScopes.OfType<ISingleObjectiveSolutionScope<TSolution>>().OrderBy(x => Problem.Maximization ? -x.Fitness : x.Fitness).ToList());187 scope.SubScopes.Replace(scope.SubScopes.OfType<ISingleObjectiveSolutionScope<TSolution>>().OrderBy(x => Maximization ? -x.Fitness : x.Fitness).ToList()); 185 188 } 186 189 public int PopulationCount { … … 296 299 Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0))); 297 300 Parameters.Add(bestQuality = new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(double.NaN))); 298 Parameters.Add(bestSolution = new ValueParameter<TSolution>("Best Solution"));301 Parameters.Add(bestSolution = new ValueParameter<TSolution>("BestFoundSolution")); 299 302 Parameters.Add(localSearchEvaluations = new ValueParameter<IntValue>("LocalSearchEvaluations", new IntValue(0))); 300 303 Parameters.Add(localOptimaLevel = new ValueParameter<DoubleValue>("LocalOptimaLevel", new DoubleValue(0))); … … 313 316 hillclimbingStat = new List<Tuple<double, double>>(); 314 317 adaptivewalkingStat = new List<Tuple<double, double>>(); 318 } 319 320 public abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN); 321 322 public virtual double Evaluate(TSolution solution, CancellationToken token) { 323 var solScope = ToScope(solution); 324 Evaluate(solScope, token); 325 return solScope.Fitness; 326 } 327 328 public virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> solScope, CancellationToken token) { 329 var pdef = Problem as ISingleObjectiveProblemDefinition; 330 if (pdef != null) { 331 var ind = new SingleEncodingIndividual(pdef.Encoding, solScope); 332 solScope.Fitness = pdef.Evaluate(ind, Random); 333 } else { 334 RunOperator(Problem.Evaluator, solScope, token); 335 } 315 336 } 316 337 … … 509 530 var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single()); 510 531 511 var goal = Problem.Maximization ? Population.Min(x => x.Fitness) : Population.Max(x => x.Fitness);532 var goal = Maximization ? Population.Min(x => x.Fitness) : Population.Max(x => x.Fitness); 512 533 var z = (goal - mean) / sdev; 513 return Problem.Maximization ? 1.0 - Phi(z) /* P(X >= z) */ : Phi(z); // P(X <= z)534 return Maximization ? 1.0 - Phi(z) /* P(X >= z) */ : Phi(z); // P(X <= z) 514 535 } 515 536 … … 519 540 var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single()); 520 541 521 var goal = Problem.Maximization ? Population.Min(x => x.Fitness) : Population.Max(x => x.Fitness);542 var goal = Maximization ? Population.Min(x => x.Fitness) : Population.Max(x => x.Fitness); 522 543 var z = (goal - mean) / sdev; 523 return Problem.Maximization ? 1.0 - Phi(z) /* P(X >= z) */ : Phi(z); // P(X <= z)544 return Maximization ? 1.0 - Phi(z) /* P(X >= z) */ : Phi(z); // P(X <= z) 524 545 } 525 546 … … 531 552 public bool IsBetter(double a, double b) { 532 553 return double.IsNaN(b) && !double.IsNaN(a) 533 || Problem.Maximization && a > b534 || ! Problem.Maximization && a < b;554 || Maximization && a > b 555 || !Maximization && a < b; 535 556 } 536 557 … … 610 631 } 611 632 #endregion 633 634 #region Engine Helper 635 public void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) { 636 var stack = new Stack<IOperation>(); 637 stack.Push(CreateChildOperation(op, scope)); 638 639 while (stack.Count > 0) { 640 cancellationToken.ThrowIfCancellationRequested(); 641 642 var next = stack.Pop(); 643 if (next is OperationCollection) { 644 var coll = (OperationCollection)next; 645 for (int i = coll.Count - 1; i >= 0; i--) 646 if (coll[i] != null) stack.Push(coll[i]); 647 } else if (next is IAtomicOperation) { 648 var operation = (IAtomicOperation)next; 649 try { 650 next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken); 651 } catch (Exception ex) { 652 stack.Push(operation); 653 if (ex is OperationCanceledException) throw ex; 654 else throw new OperatorExecutionException(operation.Operator, ex); 655 } 656 if (next != null) stack.Push(next); 657 } 658 } 659 } 660 #endregion 612 661 } 613 662 … … 615 664 [StorableClass] 616 665 public abstract class MemPRSolutionContext<TProblem, TSolution, TContext, TSolutionContext> : ParameterizedNamedItem, 617 ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution> 618 where TProblem : class, IItem, ISingleObjective ProblemDefinition666 ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution>, IEvaluationServiceContext<TSolution> 667 where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem 619 668 where TSolution : class, IItem 620 669 where TContext : MemPRPopulationContext<TProblem, TSolution, TContext, TSolutionContext> … … 639 688 public TProblem Problem { 640 689 get { return parent.Problem; } 690 } 691 public bool Maximization { 692 get { return parent.Maximization; } 641 693 } 642 694 … … 693 745 EvaluatedSolutions += byEvaluations; 694 746 } 747 public virtual double Evaluate(TSolution solution, CancellationToken token) { 748 return parent.Evaluate(solution, token); 749 } 750 751 public virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> solScope, CancellationToken token) { 752 parent.Evaluate(solScope, token); 753 } 695 754 696 755 #region IExecutionContext members -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/ExhaustiveHillClimb.cs
r14450 r14552 33 33 [StorableClass] 34 34 public class ExhaustiveHillClimb<TContext> : NamedItem, ILocalSearch<TContext> 35 where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation> { 35 where TContext : ISingleSolutionHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation>, 36 IEvaluationServiceContext<Encodings.PermutationEncoding.Permutation> { 36 37 37 38 [StorableConstructor] … … 48 49 49 50 public void Optimize(TContext context) { 50 var evalWrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(context.Problem, context.Solution);51 51 var quality = context.Solution.Fitness; 52 52 try { 53 53 var result = Exhaustive.HillClimb(context.Random, context.Solution.Solution, ref quality, 54 context. Problem.Maximization, evalWrapper.Evaluate, CancellationToken.None);54 context.Maximization, context.Evaluate, CancellationToken.None); 55 55 context.IncrementEvaluatedSolutions(result.Item1); 56 56 context.Iterations = result.Item2; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/ExhaustiveHillClimbSubspace.cs
r14450 r14552 34 34 public class ExhaustiveHillClimbSubspace<TContext> : NamedItem, ILocalSearch<TContext> 35 35 where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation>, 36 IPermutationSubspaceContext {36 IPermutationSubspaceContext, IEvaluationServiceContext<Encodings.PermutationEncoding.Permutation> { 37 37 38 38 [StorableConstructor] … … 49 49 50 50 public void Optimize(TContext context) { 51 var evalWrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(context.Problem, context.Solution);52 51 var quality = context.Solution.Fitness; 53 52 try { 54 53 var result = Exhaustive.HillClimb(context.Random, context.Solution.Solution, ref quality, 55 context.Problem.Maximization, evalWrapper.Evaluate, CancellationToken.None, context.Subspace.Subspace);54 context.Problem.Maximization, context.Evaluate, CancellationToken.None, context.Subspace.Subspace); 56 55 context.IncrementEvaluatedSolutions(result.Item1); 57 56 context.Iterations = result.Item2; -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive.cs
r14456 r14552 34 34 35 35 public static Tuple<int, int> HillClimb(IRandom random, Encodings.PermutationEncoding.Permutation perm, 36 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, double> eval,36 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, 37 37 CancellationToken token, bool[,] subspace = null) { 38 if (double.IsNaN(quality)) quality = eval(perm );38 if (double.IsNaN(quality)) quality = eval(perm, token); 39 39 Tuple<int, int> changes; 40 40 switch (perm.PermutationType) { -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive1Shift.cs
r14456 r14552 31 31 public static class Exhaustive1Shift { 32 32 public static Tuple<int, int> HillClimb(IRandom random, Encodings.PermutationEncoding.Permutation perm, 33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, double> eval,33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, 34 34 CancellationToken token, bool[,] subspace = null) { 35 35 var evaluations = 0; 36 36 var current = perm; 37 37 if (double.IsNaN(quality)) { 38 quality = eval(current );38 quality = eval(current, token); 39 39 evaluations++; 40 40 } … … 59 59 continue; 60 60 TranslocationManipulator.Apply(current, shift.Index1, shift.Index2, shift.Index3); 61 var q = eval(current );61 var q = eval(current, token); 62 62 evaluations++; 63 63 if (FitnessComparer.IsBetter(maximization, q, quality)) { -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive2Opt.cs
r14456 r14552 31 31 public static class Exhaustive2Opt { 32 32 public static Tuple<int, int> HillClimb(IRandom random, Encodings.PermutationEncoding.Permutation perm, 33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, double> eval,33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, 34 34 CancellationToken token, bool[,] subspace = null) { 35 35 var evaluations = 0; 36 36 var current = perm; 37 37 if (double.IsNaN(quality)) { 38 quality = eval(current );38 quality = eval(current, token); 39 39 evaluations++; 40 40 } … … 56 56 57 57 InversionManipulator.Apply(current, opt.Index1, opt.Index2); 58 var q = eval(current );58 var q = eval(current, token); 59 59 evaluations++; 60 60 if (FitnessComparer.IsBetter(maximization, q, quality)) { -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/ExhaustiveSwap2.cs
r14456 r14552 31 31 public static class ExhaustiveSwap2 { 32 32 public static Tuple<int, int> HillClimb(IRandom random, Encodings.PermutationEncoding.Permutation perm, 33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, double> eval,33 ref double quality, bool maximization, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, 34 34 CancellationToken token, bool[,] subspace = null) { 35 35 var evaluations = 0; 36 36 var current = perm; 37 37 if (double.IsNaN(quality)) { 38 quality = eval(current );38 quality = eval(current, token); 39 39 evaluations++; 40 40 } … … 55 55 current[swap.Index1] = current[swap.Index2]; 56 56 current[swap.Index2] = h; 57 var q = eval(current );57 var q = eval(current, token); 58 58 evaluations++; 59 59 if (FitnessComparer.IsBetter(maximization, q, quality)) { -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/PermutationMemPR.cs
r14551 r14552 38 38 [StorableClass] 39 39 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)] 40 public class PermutationMemPR : MemPRAlgorithm< SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext> {40 public class PermutationMemPR : MemPRAlgorithm<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext> { 41 41 #if DEBUG 42 42 private const bool VALIDATE = true; … … 73 73 } 74 74 75 protected override ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> ToScope(Encodings.PermutationEncoding.Permutation code, double fitness = double.NaN) {76 var creator = Problem.SolutionCreator as IPermutationCreator;77 if (creator == null) throw new InvalidOperationException("Can only solve binary encoded problems with MemPR (binary)");78 return new SingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation>(code, creator.PermutationParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {79 Parent = Context.Scope80 };81 }82 83 75 protected override ISolutionSubspace<Encodings.PermutationEncoding.Permutation> CalculateSubspace(IEnumerable<Encodings.PermutationEncoding.Permutation> solutions, bool inverse = false) { 84 var subspace = new bool[Problem.Encoding.Length, Problem.Encoding.PermutationTypeParameter.Value.Value == PermutationTypes.Absolute ? 1 : Problem.Encoding.Length]; 85 86 switch (Problem.Encoding.PermutationTypeParameter.Value.Value) { 76 var solutionsIter = solutions.GetEnumerator(); 77 if (!solutionsIter.MoveNext()) throw new ArgumentException("Cannot calculate sub-space when no solutions are given."); 78 var first = solutionsIter.Current; 79 80 var N = solutionsIter.Current.Length; 81 var type = solutionsIter.Current.PermutationType; 82 var subspace = new bool[N, type == PermutationTypes.Absolute ? 1 : N]; 83 switch (type) { 87 84 case PermutationTypes.Absolute: { 88 85 if (inverse) { … … 90 87 subspace[i, 0] = true; 91 88 } 92 var first = solutions.First();93 foreach (var s in solutions.Skip(1)) {89 while (solutionsIter.MoveNext()) { 90 var s = solutionsIter.Current; 94 91 for (var i = 0; i < s.Length; i++) { 95 92 if (first[i] != s[i]) subspace[i, 0] = !inverse; … … 104 101 subspace[i, j] = true; 105 102 } 106 var first = solutions.First();107 103 var placedFirst = new int[first.Length]; 108 104 for (var i = 0; i < first.Length; i++) { 109 105 placedFirst[first[i]] = i; 110 106 } 111 foreach (var s in solutions.Skip(1)) { 107 while (solutionsIter.MoveNext()) { 108 var s = solutionsIter.Current; 112 109 for (var i = 0; i < s.Length; i++) { 113 110 if (placedFirst[s[i]] - placedFirst[s.GetCircular(i + 1)] != -1) … … 123 120 subspace[i, j] = true; 124 121 } 125 var first = solutions.First();126 122 var placedFirst = new int[first.Length]; 127 123 for (var i = 0; i < first.Length; i++) { 128 124 placedFirst[first[i]] = i; 129 125 } 130 foreach (var s in solutions.Skip(1)) { 126 while (solutionsIter.MoveNext()) { 127 var s = solutionsIter.Current; 131 128 for (var i = 0; i < s.Length; i++) { 132 129 if (Math.Abs(placedFirst[s[i]] - placedFirst[s.GetCircular(i + 1)]) != 1) … … 137 134 break; 138 135 default: 139 throw new ArgumentException(string.Format("Unknown permutation type {0}", Problem.Encoding.PermutationTypeParameter.Value.Value));136 throw new ArgumentException(string.Format("Unknown permutation type {0}", type)); 140 137 } 141 138 return new PermutationSolutionSubspace(subspace); … … 143 140 144 141 protected override void AdaptiveWalk(ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> scope, int maxEvals, CancellationToken token, ISolutionSubspace<Encodings.PermutationEncoding.Permutation> subspace = null) { 145 var wrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(Context.Problem, scope);146 142 var quality = scope.Fitness; 147 143 try { 148 TabuWalk(Context.Random, scope.Solution, wrapper.Evaluate, ref quality, maxEvals, subspace != null ? ((PermutationSolutionSubspace)subspace).Subspace : null);144 TabuWalk(Context.Random, scope.Solution, Context.Evaluate, token, ref quality, maxEvals, subspace != null ? ((PermutationSolutionSubspace)subspace).Subspace : null); 149 145 } finally { 150 146 scope.Fitness = quality; … … 152 148 } 153 149 154 public void TabuWalk(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) {150 public void TabuWalk(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) { 155 151 switch (perm.PermutationType) { 156 152 case PermutationTypes.Absolute: 157 TabuWalkSwap(random, perm, eval, ref quality, maxEvals, subspace);153 TabuWalkSwap(random, perm, eval, token, ref quality, maxEvals, subspace); 158 154 break; 159 155 case PermutationTypes.RelativeDirected: 160 TabuWalkShift(random, perm, eval, ref quality, maxEvals, subspace);156 TabuWalkShift(random, perm, eval, token, ref quality, maxEvals, subspace); 161 157 break; 162 158 case PermutationTypes.RelativeUndirected: 163 TabuWalkOpt(random, perm, eval, ref quality, maxEvals, subspace);159 TabuWalkOpt(random, perm, eval, token, ref quality, maxEvals, subspace); 164 160 break; 165 161 default: throw new ArgumentException(string.Format("Permutation type {0} is not known", perm.PermutationType)); … … 168 164 } 169 165 170 public int TabuWalkSwap(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) {166 public int TabuWalkSwap(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) { 171 167 var evaluations = 0; 172 var maximization = Context. Problem.Maximization;168 var maximization = Context.Maximization; 173 169 if (double.IsNaN(quality)) { 174 quality = eval(perm, random);170 quality = eval(perm, token); 175 171 evaluations++; 176 172 } … … 202 198 current[swap.Index1] = current[swap.Index2]; 203 199 current[swap.Index2] = h; 204 var q = eval(current, random);200 var q = eval(current, token); 205 201 evaluations++; 206 202 if (FitnessComparer.IsBetter(maximization, q, quality)) { … … 261 257 } 262 258 263 public int TabuWalkShift(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) {259 public int TabuWalkShift(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) { 264 260 return 0; 265 261 } 266 262 267 public int TabuWalkOpt(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) {268 var maximization = Context. Problem.Maximization;263 public int TabuWalkOpt(IRandom random, Encodings.PermutationEncoding.Permutation perm, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, ref double quality, int maxEvals = int.MaxValue, bool[,] subspace = null) { 264 var maximization = Context.Maximization; 269 265 var evaluations = 0; 270 266 if (double.IsNaN(quality)) { 271 quality = eval(perm, random);267 quality = eval(perm, token); 272 268 evaluations++; 273 269 } … … 303 299 InversionManipulator.Apply(current, opt.Index1, opt.Index2); 304 300 305 var q = eval(current, random);301 var q = eval(current, token); 306 302 evaluations++; 307 303 if (FitnessComparer.IsBetter(maximization, q, quality)) { … … 414 410 continue; 415 411 } 416 var probe = ToScope(c);417 Evaluate(probe, token);412 var probe = Context.ToScope(c); 413 Context.Evaluate(probe, token); 418 414 evaluations++; 419 415 cache.Add(c); … … 425 421 } 426 422 Context.IncrementEvaluatedSolutions(evaluations); 427 return offspring ;423 return offspring ?? p1; 428 424 } 429 425 … … 449 445 continue; 450 446 } 451 var probe = ToScope(c);452 Evaluate(probe, token);447 var probe = Context.ToScope(c); 448 Context.Evaluate(probe, token); 453 449 evaluations++; 454 450 cache.Add(c); … … 460 456 } 461 457 Context.IncrementEvaluatedSolutions(evaluations); 462 return offspring ;458 return offspring ?? p1; 463 459 } 464 460 … … 484 480 continue; 485 481 } 486 var probe = ToScope(c);487 Evaluate(probe, token);482 var probe = Context.ToScope(c); 483 Context.Evaluate(probe, token); 488 484 evaluations++; 489 485 cache.Add(c); … … 495 491 } 496 492 Context.IncrementEvaluatedSolutions(evaluations); 497 return offspring ;493 return offspring ?? p1; 498 494 } 499 495 500 496 protected override ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> Link(ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> a, ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> b, CancellationToken token, bool delink = false) { 501 var wrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(Problem, ToScope(null));502 497 double quality; 503 return ToScope(Relink(Context.Random, a.Solution, b.Solution, wrapper.Evaluate, delink, out quality));504 } 505 506 public Encodings.PermutationEncoding.Permutation Relink(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, bool delink, out double best) {498 return Context.ToScope(Relink(Context.Random, a.Solution, b.Solution, Context.Evaluate, token, delink, out quality)); 499 } 500 501 public Encodings.PermutationEncoding.Permutation Relink(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, bool delink, out double best) { 507 502 if (p1.PermutationType != p2.PermutationType) throw new ArgumentException(string.Format("Unequal permutation types {0} and {1}", p1.PermutationType, p2.PermutationType)); 508 503 switch (p1.PermutationType) { 509 504 case PermutationTypes.Absolute: 510 return delink ? DelinkSwap(random, p1, p2, eval, out best) : RelinkSwap(random, p1, p2, eval, out best);505 return delink ? DelinkSwap(random, p1, p2, eval, token, out best) : RelinkSwap(random, p1, p2, eval, token, out best); 511 506 case PermutationTypes.RelativeDirected: 512 return RelinkShift(random, p1, p2, eval, delink, out best);507 return RelinkShift(random, p1, p2, eval, token, delink, out best); 513 508 case PermutationTypes.RelativeUndirected: 514 return RelinkOpt(random, p1, p2, eval, delink, out best);509 return RelinkOpt(random, p1, p2, eval, token, delink, out best); 515 510 default: throw new ArgumentException(string.Format("Unknown permutation type {0}", p1.PermutationType)); 516 511 } 517 512 } 518 513 519 public Encodings.PermutationEncoding.Permutation RelinkSwap(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, out double best) {520 var maximization = Context. Problem.Maximization;514 public Encodings.PermutationEncoding.Permutation RelinkSwap(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, out double best) { 515 var maximization = Context.Maximization; 521 516 var evaluations = 0; 522 517 var child = (Encodings.PermutationEncoding.Permutation)p1.Clone(); … … 540 535 } 541 536 Swap(child, invChild[p2[idx]], idx); 542 var moveF = eval(child, random);537 var moveF = eval(child, token); 543 538 evaluations++; 544 539 if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) { … … 565 560 } 566 561 if (bestChild == null) { 567 best = eval(child, random);562 best = eval(child, token); 568 563 evaluations++; 569 564 } … … 576 571 } 577 572 578 public Encodings.PermutationEncoding.Permutation DelinkSwap(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, out double best) {579 var maximization = Context. Problem.Maximization;573 public Encodings.PermutationEncoding.Permutation DelinkSwap(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, out double best) { 574 var maximization = Context.Maximization; 580 575 var evaluations = 0; 581 576 var child = (Encodings.PermutationEncoding.Permutation)p1.Clone(); … … 600 595 if (k == idx) continue; 601 596 Swap(child, k, idx); 602 var moveF = eval(child, random);597 var moveF = eval(child, token); 603 598 evaluations++; 604 599 if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) { … … 624 619 } 625 620 if (bestChild == null) { 626 best = eval(child, random);621 best = eval(child, token); 627 622 evaluations++; 628 623 } … … 634 629 } 635 630 636 public Encodings.PermutationEncoding.Permutation RelinkShift(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, bool delink, out double best) {637 var maximization = Context. Problem.Maximization;631 public Encodings.PermutationEncoding.Permutation RelinkShift(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, bool delink, out double best) { 632 var maximization = Context.Maximization; 638 633 var evaluations = 0; 639 634 var child = (Encodings.PermutationEncoding.Permutation)p1.Clone(); … … 656 651 if (c < n) Shift(child, from: n, to: c + 1); 657 652 else Shift(child, from: c, to: n); 658 var moveF = eval(child, random);653 var moveF = eval(child, token); 659 654 evaluations++; 660 655 if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) { … … 678 673 679 674 if (bestChild == null) { 680 best = eval(child, random);675 best = eval(child, token); 681 676 evaluations++; 682 677 } … … 689 684 } 690 685 691 public Encodings.PermutationEncoding.Permutation RelinkOpt(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, IRandom, double> eval, bool delink, out double best) {692 var maximization = Context. Problem.Maximization;686 public Encodings.PermutationEncoding.Permutation RelinkOpt(IRandom random, Encodings.PermutationEncoding.Permutation p1, Encodings.PermutationEncoding.Permutation p2, Func<Encodings.PermutationEncoding.Permutation, CancellationToken, double> eval, CancellationToken token, bool delink, out double best) { 687 var maximization = Context.Maximization; 693 688 var evaluations = 0; 694 689 var child = (Encodings.PermutationEncoding.Permutation)p1.Clone(); … … 766 761 undoStack.Push(m); 767 762 } 768 var moveF = eval(child, random);763 var moveF = eval(child, token); 769 764 evaluations++; 770 765 if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) { … … 792 787 793 788 if (bestChild == null) { 794 best = eval(child, random);789 best = eval(child, token); 795 790 evaluations++; 796 791 } -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/PermutationMemPRContext.cs
r14450 r14552 20 20 #endregion 21 21 22 using System; 23 using System.Runtime.Remoting.Contexts; 22 24 using HeuristicLab.Algorithms.MemPR.Interfaces; 23 25 using HeuristicLab.Common; … … 31 33 [Item("MemPR Population Context (permutation)", "MemPR population context for permutation encoded problems.")] 32 34 [StorableClass] 33 public sealed class PermutationMemPRPopulationContext : MemPRPopulationContext< SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext> {35 public sealed class PermutationMemPRPopulationContext : MemPRPopulationContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext> { 34 36 35 37 [StorableConstructor] … … 47 49 return new PermutationMemPRSolutionContext(this, solution); 48 50 } 51 52 public override ISingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation> ToScope(Encodings.PermutationEncoding.Permutation code, double fitness = double.NaN) { 53 var creator = Problem.SolutionCreator as IPermutationCreator; 54 if (creator == null) throw new InvalidOperationException("Can only solve binary encoded problems with MemPR (binary)"); 55 return new SingleObjectiveSolutionScope<Encodings.PermutationEncoding.Permutation>(code, creator.PermutationParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) { 56 Parent = Scope 57 }; 58 } 49 59 } 50 60 51 61 [Item("MemPR Solution Context (permutation)", "MemPR solution context for permutation encoded problems.")] 52 62 [StorableClass] 53 public sealed class PermutationMemPRSolutionContext : MemPRSolutionContext< SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext>, IPermutationSubspaceContext {63 public sealed class PermutationMemPRSolutionContext : MemPRSolutionContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation, PermutationMemPRPopulationContext, PermutationMemPRSolutionContext>, IPermutationSubspaceContext { 54 64 55 65 [Storable] -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/SolutionModel/Univariate/BiasedModelTrainer.cs
r14496 r14552 34 34 [StorableClass] 35 35 public class BiasedModelTrainer<TContext> : ParameterizedNamedItem, ISolutionModelTrainer<TContext> 36 where TContext : IPopulationBasedHeuristicAlgorithmContext< SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation>,37 ISolutionModelContext<Encodings.PermutationEncoding.Permutation> {36 where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation>, 37 ISolutionModelContext<Encodings.PermutationEncoding.Permutation>, IEvaluationServiceContext<Encodings.PermutationEncoding.Permutation> { 38 38 39 39 [Storable] … … 59 59 60 60 public void TrainModel(TContext context) { 61 context.Model = Trainer.TrainBiased(ModelBias, context.Random, context. Problem.Maximization, context.Population.Select(x => x.Solution).ToList(), context.Population.Select(x => x.Fitness).ToList(), context.Problem.Encoding.Length);61 context.Model = Trainer.TrainBiased(ModelBias, context.Random, context.Maximization, context.Population.Select(x => x.Solution).ToList(), context.Population.Select(x => x.Fitness).ToList(), context.Population.First().Solution.Length); 62 62 } 63 63 } -
branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/SolutionModel/Univariate/UnbiasedModelTrainer.cs
r14496 r14552 33 33 [StorableClass] 34 34 public class UnbiasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext> 35 where TContext : IPopulationBasedHeuristicAlgorithmContext< SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation>,35 where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation>, 36 36 ISolutionModelContext<Encodings.PermutationEncoding.Permutation> { 37 37 … … 49 49 50 50 public void TrainModel(TContext context) { 51 context.Model = Trainer.TrainUnbiased(context.Random, context.Population.Select(x => x.Solution).ToList(), context.P roblem.Encoding.Length);51 context.Model = Trainer.TrainUnbiased(context.Random, context.Population.Select(x => x.Solution).ToList(), context.Population.First().Solution.Length); 52 52 } 53 53 } -
branches/MemPRAlgorithm/HeuristicLab.Problems.Binary/3.3/AlternatingBitsProblem.cs
r14543 r14552 20 20 #endregion 21 21 22 using System;23 using System.Linq;24 22 using HeuristicLab.Common; 25 23 using HeuristicLab.Core; … … 28 26 29 27 namespace HeuristicLab.Problems.Binary { 30 [Item(" One Max Problem", "Represents a problem whose objective is to maximize the number of true values.")]31 [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 2 10)]28 [Item("Alternating Bits Problem", "Represents a problem whose objective is to achieve an alternating sequence of bits, long sequences of consecutive bits receive a penalty.")] 29 [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 220)] 32 30 [StorableClass] 33 public class OneMaxProblem : BinaryProblem {31 public class AlternatingBitsProblem : BinaryProblem { 34 32 public override bool Maximization { 35 get { return true; }33 get { return false; } 36 34 } 37 35 38 public OneMaxProblem()36 public AlternatingBitsProblem() 39 37 : base() { 40 Encoding.Length = 10;41 BestKnownQuality = Encoding.Length;38 Encoding.Length = 256; 39 BestKnownQuality = 0; 42 40 } 43 41 44 42 [StorableConstructor] 45 protected OneMaxProblem(bool deserializing) : base(deserializing) { } 46 47 protected OneMaxProblem(OneMaxProblem original, Cloner cloner) : base(original, cloner) { } 43 protected AlternatingBitsProblem(bool deserializing) : base(deserializing) { } 44 protected AlternatingBitsProblem(AlternatingBitsProblem original, Cloner cloner) : base(original, cloner) { } 48 45 public override IDeepCloneable Clone(Cloner cloner) { 49 return new OneMaxProblem(this, cloner);46 return new AlternatingBitsProblem(this, cloner); 50 47 } 51 48 52 49 public override double Evaluate(BinaryVector vector, IRandom random) { 53 return vector.Count(b => b); 54 } 55 56 protected override void LengthParameter_ValueChanged(object sender, EventArgs e) { 57 base.LengthParameter_ValueChanged(sender, e); 58 BestKnownQuality = Length; 50 var quality = 0.0; 51 var curr = vector[0]; 52 var lastOk = 0; 53 for (var i = 1; i < vector.Length; i++) { 54 if (curr && !vector[i] || !curr && vector[i]) { 55 lastOk = i; 56 } else quality += (i - lastOk); 57 curr = vector[i]; 58 } 59 return quality; 59 60 } 60 61 } -
branches/MemPRAlgorithm/HeuristicLab.Problems.Binary/3.3/HeuristicLab.Problems.Binary-3.3.csproj
r14420 r14552 87 87 <Compile Include="HIFFProblem.cs" /> 88 88 <Compile Include="BinaryKnapsackProblem.cs" /> 89 <Compile Include="AlternatingBitsProblem.cs" /> 89 90 <Compile Include="OneMaxProblem.cs" /> 90 91 <Compile Include="Plugin.cs" />
Note: See TracChangeset
for help on using the changeset viewer.