Changeset 14552


Ignore:
Timestamp:
01/09/17 00:36:20 (3 years ago)
Author:
abeham
Message:

#2701:

  • Added alternating bits binary test Problem
  • Refactored MemPR to work with programmable problem in current trunk
  • fixed a bug in permutation MemPR when crossover doesn't assign an offspring
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  
    3838  [StorableClass]
    3939  [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> {
    4141    [StorableConstructor]
    4242    protected BinaryMemPR(bool deserializing) : base(deserializing) { }
     
    6666    }
    6767
    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.Scope
    73       };
    74     }
    75 
    7668    protected override ISolutionSubspace<BinaryVector> CalculateSubspace(IEnumerable<BinaryVector> solutions, bool inverse = false) {
    7769      var pop = solutions.ToList();
     
    9284      var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
    9385      if (double.IsNaN(scope.Fitness)) {
    94         Evaluate(scope, token);
     86        Context.Evaluate(scope, token);
    9587        evaluations++;
    9688      }
     
    10496      var order = Enumerable.Range(0, N).Where(x => subset == null || subset[x]).Shuffle(Context.Random).ToArray();
    10597
    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);
    10799      var range = Math.Abs(bound - Context.LocalOptimaLevel);
    108100      if (range.IsAlmost(0)) range = Math.Abs(bound * 0.05);
     
    122114          var before = currentScope.Fitness;
    123115          current[idx] = !current[idx];
    124           Evaluate(currentScope, token);
     116          Context.Evaluate(currentScope, token);
    125117          evaluations++;
    126118          var after = currentScope.Fitness;
     
    133125            }
    134126          }
    135           var diff = Problem.Maximization ? after - before : before - after;
     127          var diff = Context.Maximization ? after - before : before - after;
    136128          if (diff > 0) moved = true;
    137129          else {
     
    158150      var N = p1.Solution.Length;
    159151
    160       var probe = ToScope((BinaryVector)p1.Solution.Clone());
     152      var probe = Context.ToScope((BinaryVector)p1.Solution.Clone());
    161153
    162154      var cache = new HashSet<BinaryVector>(new BinaryVectorEqualityComparer());
     
    179171          continue;
    180172        }
    181         Evaluate(probe, token);
     173        Context.Evaluate(probe, token);
    182174        evaluations++;
    183175        cache.Add(c);
     
    210202          var idx = order[i];
    211203          child[idx] = !child[idx]; // move
    212           Evaluate(childScope, token);
     204          Context.Evaluate(childScope, token);
    213205          evaluations++;
    214206          var s = childScope.Fitness;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/BinaryMemPRContext.cs

    r14450 r14552  
    2020#endregion
    2121
     22using System;
    2223using HeuristicLab.Algorithms.MemPR.Interfaces;
    2324using HeuristicLab.Common;
     
    3132  [Item("MemPR Population Context (binary)", "MemPR population context for binary encoded problems.")]
    3233  [StorableClass]
    33   public sealed class BinaryMemPRPopulationContext : MemPRPopulationContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> {
     34  public sealed class BinaryMemPRPopulationContext : MemPRPopulationContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> {
    3435
    3536    [StorableConstructor]
     
    4748      return new BinaryMemPRSolutionContext(this, solution);
    4849    }
     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    }
    4958  }
    5059
    5160  [Item("MemPR Solution Context (binary)", "MemPR solution context for binary encoded problems.")]
    5261  [StorableClass]
    53   public sealed class BinaryMemPRSolutionContext : MemPRSolutionContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext>, IBinaryVectorSubspaceContext {
     62  public sealed class BinaryMemPRSolutionContext : MemPRSolutionContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext>, IBinaryVectorSubspaceContext {
    5463
    5564    [Storable]
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/ExhaustiveBitflip.cs

    r14450 r14552  
    3333  [Item("Exhaustive Bitflip Local Search (binary)", "", ExcludeGenericTypeInfo = true)]
    3434  [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> {
    3638   
    3739    [StorableConstructor]
     
    4850
    4951    public void Optimize(TContext context) {
    50       var evalWrapper = new EvaluationWrapper<BinaryVector>(context.Problem, context.Solution);
    5152      var quality = context.Solution.Fitness;
    5253      try {
    5354        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);
    5556        context.IncrementEvaluatedSolutions(result.Item1);
    5657        context.Iterations = result.Item2;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/ExhaustiveBitflipSubspace.cs

    r14466 r14552  
    3434  [StorableClass]
    3535  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> {
    3738
    3839    [StorableConstructor]
     
    4950
    5051    public void Optimize(TContext context) {
    51       var evalWrapper = new EvaluationWrapper<BinaryVector>(context.Problem, context.Solution);
    5252      var quality = context.Solution.Fitness;
    5353      try {
    5454        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);
    5656        context.IncrementEvaluatedSolutions(result.Item1);
    5757        context.Iterations = result.Item2;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/LocalSearch/StaticAPI/ExhaustiveBitflip.cs

    r14450 r14552  
    3030namespace HeuristicLab.Encodings.Binary.LocalSearch {
    3131  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);
    3434      var improved = false;
    3535      var order = Enumerable.Range(0, solution.Length).Shuffle(random).ToArray();
     
    4747          // bitflip the solution
    4848          solution[idx] = !solution[idx];
    49           var after = evalFunc(solution);
     49          var after = evalFunc(solution, token);
    5050          evaluations++;
    5151          if (FitnessComparer.IsBetter(maximization, after, quality)) {
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/SolutionModel/Univariate/BiasedModelTrainer.cs

    r14450 r14552  
    3434  [StorableClass]
    3535  public class BiasedModelTrainer<TContext> : ParameterizedNamedItem, ISolutionModelTrainer<TContext>
    36     where TContext : IPopulationBasedHeuristicAlgorithmContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, ISolutionModelContext<BinaryVector> {
     36    where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector>, ISolutionModelContext<BinaryVector> {
    3737   
    3838    [Storable]
     
    5858
    5959    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));
    6161    }
    6262  }
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/SolutionModel/Univariate/UnbiasedModelTrainer.cs

    r14450 r14552  
    3232  [StorableClass]
    3333  public class UniasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext>
    34     where TContext : IPopulationBasedHeuristicAlgorithmContext<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector>, ISolutionModelContext<BinaryVector> {
     34    where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, BinaryVector>, ISolutionModelContext<BinaryVector> {
    3535   
    3636    [StorableConstructor]
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/HeuristicLab.Algorithms.MemPR-3.3.csproj

    r14544 r14552  
    129129    <Compile Include="Properties\AssemblyInfo.cs" />
    130130    <Compile Include="Util\CkMeans1D.cs" />
    131     <Compile Include="Util\EvaluationWrapper.cs" />
    132131    <Compile Include="Util\FitnessComparer.cs" />
    133132  </ItemGroup>
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Interfaces/Interfaces.cs

    r14544 r14552  
    2121 
    2222using System.Collections.Generic;
     23using System.Threading;
    2324using HeuristicLab.Algorithms.MemPR.Binary;
    2425using HeuristicLab.Algorithms.MemPR.Grouping;
     
    6364
    6465  public interface IHeuristicAlgorithmContext<TProblem, TSolution> : IExecutionContext
    65       where TProblem : class, ISingleObjectiveProblemDefinition {
     66      where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem {
    6667    TProblem Problem { get; }
     68    bool Maximization { get; }
    6769    IRandom Random { get; }
    6870    int Iterations { get; set; }
     
    7375  }
    7476
     77  public interface IEvaluationServiceContext<TSolution> : IExecutionContext {
     78    double Evaluate(TSolution solution, CancellationToken token);
     79    void Evaluate(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token);
     80  }
     81
    7582  public interface IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution> : IHeuristicAlgorithmContext<TProblem, TSolution>
    76       where TProblem : class, ISingleObjectiveProblemDefinition {
     83      where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem {
    7784    IEnumerable<ISingleObjectiveSolutionScope<TSolution>> Population { get; }
    7885  }
    7986
    8087  public interface ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution> : IHeuristicAlgorithmContext<TProblem, TSolution>
    81       where TProblem : class, ISingleObjectiveProblemDefinition {
     88      where TProblem : class, ISingleObjectiveHeuristicOptimizationProblem {
    8289    ISingleObjectiveSolutionScope<TSolution> Solution { get; }
    8390  }
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LinearLinkageMemPR.cs

    r14551 r14552  
    3737  [StorableClass]
    3838  [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> {
    4040    [StorableConstructor]
    4141    protected LinearLinkageMemPR(bool deserializing) : base(deserializing) { }
     
    6969    }
    7070
    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.Scope
    76       };
    77     }
    78 
    7971    protected override ISolutionSubspace<LinearLinkage> CalculateSubspace(IEnumerable<LinearLinkage> solutions, bool inverse = false) {
    8072      var pop = solutions.ToList();
     
    9587        int maxEvals, CancellationToken token,
    9688        ISolutionSubspace<LinearLinkage> sub_space = null) {
    97       var maximization = Context.Problem.Maximization;
     89      var maximization = Context.Maximization;
    9890      var subspace = sub_space is LinearLinkageSolutionSubspace ? ((LinearLinkageSolutionSubspace)sub_space).Subspace : null;
    9991      var evaluations = 0;
    10092      var quality = scope.Fitness;
    10193      if (double.IsNaN(quality)) {
    102         Evaluate(scope, token);
     94        Context.Evaluate(scope, token);
    10395        quality = scope.Fitness;
    10496        evaluations++;
     
    168160              move.Apply(current);
    169161              var qualityToRestore = tabu[i, current[i]]; // current[i] is new next
    170               Evaluate(currentScope, token);
     162              Context.Evaluate(currentScope, token);
    171163              evaluations++;
    172164              var moveF = currentScope.Fitness;
     
    255247      var cachehits = 0;
    256248      var evaluations = 0;
    257       var probe = ToScope((LinearLinkage)p1.Solution.Clone());
     249      var probe = Context.ToScope((LinearLinkage)p1.Solution.Clone());
    258250      ISingleObjectiveSolutionScope<LinearLinkage> offspring = null;
    259251      while (evaluations < p1.Solution.Length) {
     
    268260          continue;
    269261        }
    270         Evaluate(probe, token);
     262        Context.Evaluate(probe, token);
    271263        evaluations++;
    272264        cache.Add(c);
     
    283275    protected override ISingleObjectiveSolutionScope<LinearLinkage> Link(ISingleObjectiveSolutionScope<LinearLinkage> a, ISingleObjectiveSolutionScope<LinearLinkage> b, CancellationToken token, bool delink = false) {
    284276      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 
    294277      var probe = (ISingleObjectiveSolutionScope<LinearLinkage>)a.Clone();
    295278      ISingleObjectiveSolutionScope<LinearLinkage> best = null;
     
    306289          if (delink && distAfter > distBefore || !delink && distAfter < distBefore) {
    307290            var beforeQ = probe.Fitness;
    308             Evaluate(probe, token);
     291            Context.Evaluate(probe, token);
    309292            evaluations++;
    310293            var q = probe.Fitness;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LinearLinkageMemPRContext.cs

    r14544 r14552  
    2020#endregion
    2121
     22using System;
     23using System.Runtime.Remoting.Contexts;
    2224using HeuristicLab.Algorithms.MemPR.Interfaces;
    2325using HeuristicLab.Common;
     
    3133  [Item("MemPR Population Context (linear linkage)", "MemPR population context for linear linkage encoded problems.")]
    3234  [StorableClass]
    33   public sealed class LinearLinkageMemPRPopulationContext : MemPRPopulationContext<SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {
     35  public sealed class LinearLinkageMemPRPopulationContext : MemPRPopulationContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {
    3436
    3537    [StorableConstructor]
     
    4749      return new LinearLinkageMemPRSolutionContext(this, solution);
    4850    }
     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    }
    4959  }
    5060
    5161  [Item("MemPR Solution Context (linear linkage)", "MemPR solution context for linear linkage encoded problems.")]
    5262  [StorableClass]
    53   public sealed class LinearLinkageMemPRSolutionContext : MemPRSolutionContext<SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext>, ILinearLinkageSubspaceContext {
     63  public sealed class LinearLinkageMemPRSolutionContext : MemPRSolutionContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext>, ILinearLinkageSubspaceContext {
    5464
    5565    [Storable]
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LocalSearch/ExhaustiveSubspace.cs

    r14544 r14552  
    2222using System.Threading;
    2323using HeuristicLab.Algorithms.MemPR.Interfaces;
    24 using HeuristicLab.Algorithms.MemPR.Util;
    2524using HeuristicLab.Common;
    2625using HeuristicLab.Core;
     
    3332  [StorableClass]
    3433  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> {
    3636
    3737    [StorableConstructor]
     
    4848
    4949    public void Optimize(TContext context) {
    50       var evalWrapper = new EvaluationWrapper<LinearLinkage>(context.Problem, context.Solution);
    5150      var quality = context.Solution.Fitness;
    5251      try {
    5352        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);
    5554        context.IncrementEvaluatedSolutions(result.Item1);
    5655        context.Iterations = result.Item2;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LocalSearch/StaticAPI/ExhaustiveLocalSearch.cs

    r14544 r14552  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
    2425using System.Threading;
    2526using HeuristicLab.Algorithms.MemPR.Util;
    26 using HeuristicLab.Collections;
    2727using HeuristicLab.Core;
    2828using HeuristicLab.Encodings.LinearLinkageEncoding;
     
    3030namespace HeuristicLab.Algorithms.MemPR.Grouping.LocalSearch {
    3131  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) {
    3333      var evaluations = 0;
    34       var current = solution;
    3534      if (double.IsNaN(quality)) {
    36         quality = eval(current, random);
     35        quality = eval(solution, token);
    3736        evaluations++;
    3837      }
    3938      var steps = 0;
    40       // this dictionary holds the last relevant links
    41       var links = new BidirectionalDictionary<int, int>();
     39      var lleb = solution.ToBackLinks();
    4240      for (var iter = 0; iter < int.MaxValue; iter++) {
    4341        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);
    10047            evaluations++;
    10148            if (FitnessComparer.IsBetter(maximization, moveF, quality)) {
     49              move.ApplyToLLEb(lleb);
    10250              steps++;
    10351              quality = moveF;
    10452              change = true;
    105               isLast = true;
    106               next = i;
    107               links.SetBySecond(i, i);
    108               continue;
    109             } else current[i] = next; // undo
     53              break;
     54            } else {
     55              move.Undo(solution);
     56            }
     57            if (token.IsCancellationRequested) break;
    11058          }
    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);
    14862          if (token.IsCancellationRequested) break;
    14963        }
     
    15468    }
    15569
    156     public static Tuple<int, int> OptimizeSwapOnly(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) {
    15771      var evaluations = 0;
    15872      var current = solution;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/SolutionModel/Univariate/UnbiasedModelTrainer.cs

    r14544 r14552  
    3232  [StorableClass]
    3333  public class UniasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext>
    34     where TContext : IPopulationBasedHeuristicAlgorithmContext<SingleObjectiveBasicProblem<LinearLinkageEncoding>, LinearLinkage>, ISolutionModelContext<LinearLinkage> {
     34    where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage>, ISolutionModelContext<LinearLinkage> {
    3535   
    3636    [StorableConstructor]
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/MemPRAlgorithm.cs

    r14551 r14552  
    3939  [StorableClass]
    4040  public abstract class MemPRAlgorithm<TProblem, TSolution, TPopulationContext, TSolutionContext> : BasicAlgorithm, INotifyPropertyChanged
    41       where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem, ISingleObjectiveProblemDefinition
     41      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem
    4242      where TSolution : class, IItem
    4343      where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext>, new()
     
    425425      }
    426426
    427       RunOperator(Analyzer, Context.Scope, token);
     427      Context.RunOperator(Analyzer, Context.Scope, token);
    428428    }
    429429
    430430    protected bool Replace(ISingleObjectiveSolutionScope<TSolution> child, CancellationToken token) {
    431431      if (double.IsNaN(child.Fitness)) {
    432         Evaluate(child, token);
     432        Context.Evaluate(child, token);
    433433        Context.IncrementEvaluatedSolutions(1);
    434434      }
     
    524524    protected abstract bool Eq(TSolution a, TSolution b);
    525525    protected abstract double Dist(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b);
    526     protected abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN);
    527526    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     }
    535527
    536528    #region Create
    537529    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);
    540532      return child;
    541533    }
     
    545537    protected virtual int HillClimb(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
    546538      if (double.IsNaN(scope.Fitness)) {
    547         Evaluate(scope, token);
     539        Context.Evaluate(scope, token);
    548540        Context.IncrementEvaluatedSolutions(1);
    549541      }
     
    560552    protected virtual void AdaptiveClimb(ISingleObjectiveSolutionScope<TSolution> scope, int maxEvals, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
    561553      if (double.IsNaN(scope.Fitness)) {
    562         Evaluate(scope, token);
     554        Context.Evaluate(scope, token);
    563555        Context.IncrementEvaluatedSolutions(1);
    564556      }
     
    585577
    586578      if (double.IsNaN(p1.Fitness)) {
    587         Evaluate(p1, token);
     579        Context.Evaluate(p1, token);
    588580        Context.IncrementEvaluatedSolutions(1);
    589581      }
    590582      if (double.IsNaN(p2.Fitness)) {
    591         Evaluate(p2, token);
     583        Context.Evaluate(p2, token);
    592584        Context.IncrementEvaluatedSolutions(1);
    593585      }
     
    597589
    598590        if (double.IsNaN(offspring.Fitness)) {
    599           Evaluate(offspring, token);
     591          Context.Evaluate(offspring, token);
    600592          Context.IncrementEvaluatedSolutions(1);
    601593        }
     
    630622      var link = PerformRelinking(p1, p2, token, delink: false);
    631623      if (double.IsNaN(link.Fitness)) {
    632         Evaluate(link, token);
     624        Context.Evaluate(link, token);
    633625        Context.IncrementEvaluatedSolutions(1);
    634626      }
     
    654646      var link = PerformRelinking(p1, p2, token, delink: true);
    655647      if (double.IsNaN(link.Fitness)) {
    656         Evaluate(link, token);
     648        Context.Evaluate(link, token);
    657649        Context.IncrementEvaluatedSolutions(1);
    658650      }
     
    668660
    669661      if (double.IsNaN(relink.Fitness)) {
    670         Evaluate(relink, token);
     662        Context.Evaluate(relink, token);
    671663        Context.IncrementEvaluatedSolutions(1);
    672664      }
     
    696688        var tries = 1;
    697689        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);
    700692          if (bestSample == null || Context.IsBetter(sample, bestSample)) {
    701693            bestSample = sample;
     
    714706
    715707    protected virtual bool Terminate() {
     708      var maximization = ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value;
    716709      return MaximumEvaluations.HasValue && Context.EvaluatedSolutions >= MaximumEvaluations.Value
    717710        || MaximumExecutionTime.HasValue && ExecutionTime >= MaximumExecutionTime.Value
    718         || TargetQuality.HasValue && (Problem.Maximization && Context.BestQuality >= TargetQuality.Value
    719                                   || !Problem.Maximization && Context.BestQuality <= TargetQuality.Value);
     711        || TargetQuality.HasValue && (maximization && Context.BestQuality >= TargetQuality.Value
     712                                  || !maximization && Context.BestQuality <= TargetQuality.Value);
    720713    }
    721714
     
    725718      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
    726719    }
    727 
    728     #region Engine Helper
    729     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     #endregion
    755720  }
    756721}
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/MemPRContext.cs

    r14550 r14552  
    4141  [StorableClass]
    4242  public abstract class MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext> : ParameterizedNamedItem,
    43     IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution>, ISolutionModelContext<TSolution>
    44       where TProblem : class, IItem, ISingleObjectiveProblemDefinition
     43    IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution>, ISolutionModelContext<TSolution>, IEvaluationServiceContext<TSolution>
     44      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem
    4545      where TSolution : class, IItem
    4646      where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext>
     
    7070      set { problem.Value = value; }
    7171    }
     72    public bool Maximization {
     73      get { return ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; }
     74    }
    7275
    7376    [Storable]
     
    182185    }
    183186    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());
    185188    }
    186189    public int PopulationCount {
     
    296299      Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
    297300      Parameters.Add(bestQuality = new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(double.NaN)));
    298       Parameters.Add(bestSolution = new ValueParameter<TSolution>("BestSolution"));
     301      Parameters.Add(bestSolution = new ValueParameter<TSolution>("BestFoundSolution"));
    299302      Parameters.Add(localSearchEvaluations = new ValueParameter<IntValue>("LocalSearchEvaluations", new IntValue(0)));
    300303      Parameters.Add(localOptimaLevel = new ValueParameter<DoubleValue>("LocalOptimaLevel", new DoubleValue(0)));
     
    313316      hillclimbingStat = new List<Tuple<double, double>>();
    314317      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      }
    315336    }
    316337
     
    509530      var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single());
    510531
    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);
    512533      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)
    514535    }
    515536
     
    519540      var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single());
    520541
    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);
    522543      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)
    524545    }
    525546
     
    531552    public bool IsBetter(double a, double b) {
    532553      return double.IsNaN(b) && !double.IsNaN(a)
    533         || Problem.Maximization && a > b
    534         || !Problem.Maximization && a < b;
     554        || Maximization && a > b
     555        || !Maximization && a < b;
    535556    }
    536557
     
    610631    }
    611632    #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
    612661  }
    613662
     
    615664  [StorableClass]
    616665  public abstract class MemPRSolutionContext<TProblem, TSolution, TContext, TSolutionContext> : ParameterizedNamedItem,
    617     ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution>
    618       where TProblem : class, IItem, ISingleObjectiveProblemDefinition
     666    ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution>, IEvaluationServiceContext<TSolution>
     667      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem
    619668      where TSolution : class, IItem
    620669      where TContext : MemPRPopulationContext<TProblem, TSolution, TContext, TSolutionContext>
     
    639688    public TProblem Problem {
    640689      get { return parent.Problem; }
     690    }
     691    public bool Maximization {
     692      get { return parent.Maximization; }
    641693    }
    642694
     
    693745      EvaluatedSolutions += byEvaluations;
    694746    }
     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    }
    695754
    696755    #region IExecutionContext members
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/ExhaustiveHillClimb.cs

    r14450 r14552  
    3333  [StorableClass]
    3434  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> {
    3637
    3738    [StorableConstructor]
     
    4849
    4950    public void Optimize(TContext context) {
    50       var evalWrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(context.Problem, context.Solution);
    5151      var quality = context.Solution.Fitness;
    5252      try {
    5353        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);
    5555        context.IncrementEvaluatedSolutions(result.Item1);
    5656        context.Iterations = result.Item2;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/ExhaustiveHillClimbSubspace.cs

    r14450 r14552  
    3434  public class ExhaustiveHillClimbSubspace<TContext> : NamedItem, ILocalSearch<TContext>
    3535      where TContext : ISingleSolutionHeuristicAlgorithmContext<SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation>,
    36                        IPermutationSubspaceContext {
     36                       IPermutationSubspaceContext, IEvaluationServiceContext<Encodings.PermutationEncoding.Permutation> {
    3737
    3838    [StorableConstructor]
     
    4949
    5050    public void Optimize(TContext context) {
    51       var evalWrapper = new EvaluationWrapper<Encodings.PermutationEncoding.Permutation>(context.Problem, context.Solution);
    5251      var quality = context.Solution.Fitness;
    5352      try {
    5453        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);
    5655        context.IncrementEvaluatedSolutions(result.Item1);
    5756        context.Iterations = result.Item2;
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive.cs

    r14456 r14552  
    3434
    3535    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,
    3737      CancellationToken token, bool[,] subspace = null) {
    38       if (double.IsNaN(quality)) quality = eval(perm);
     38      if (double.IsNaN(quality)) quality = eval(perm, token);
    3939      Tuple<int, int> changes;
    4040      switch (perm.PermutationType) {
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive1Shift.cs

    r14456 r14552  
    3131  public static class Exhaustive1Shift {
    3232    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,
    3434      CancellationToken token, bool[,] subspace = null) {
    3535      var evaluations = 0;
    3636      var current = perm;
    3737      if (double.IsNaN(quality)) {
    38         quality = eval(current);
     38        quality = eval(current, token);
    3939        evaluations++;
    4040      }
     
    5959            continue;
    6060          TranslocationManipulator.Apply(current, shift.Index1, shift.Index2, shift.Index3);
    61           var q = eval(current);
     61          var q = eval(current, token);
    6262          evaluations++;
    6363          if (FitnessComparer.IsBetter(maximization, q, quality)) {
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/Exhaustive2Opt.cs

    r14456 r14552  
    3131  public static class Exhaustive2Opt {
    3232    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,
    3434      CancellationToken token, bool[,] subspace = null) {
    3535      var evaluations = 0;
    3636      var current = perm;
    3737      if (double.IsNaN(quality)) {
    38         quality = eval(current);
     38        quality = eval(current, token);
    3939        evaluations++;
    4040      }
     
    5656
    5757          InversionManipulator.Apply(current, opt.Index1, opt.Index2);
    58           var q = eval(current);
     58          var q = eval(current, token);
    5959          evaluations++;
    6060          if (FitnessComparer.IsBetter(maximization, q, quality)) {
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/LocalSearch/StaticAPI/ExhaustiveSwap2.cs

    r14456 r14552  
    3131  public static class ExhaustiveSwap2 {
    3232    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,
    3434      CancellationToken token, bool[,] subspace = null) {
    3535      var evaluations = 0;
    3636      var current = perm;
    3737      if (double.IsNaN(quality)) {
    38         quality = eval(current);
     38        quality = eval(current, token);
    3939        evaluations++;
    4040      }
     
    5555          current[swap.Index1] = current[swap.Index2];
    5656          current[swap.Index2] = h;
    57           var q = eval(current);
     57          var q = eval(current, token);
    5858          evaluations++;
    5959          if (FitnessComparer.IsBetter(maximization, q, quality)) {
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/PermutationMemPR.cs

    r14551 r14552  
    3838  [StorableClass]
    3939  [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> {
    4141#if DEBUG
    4242    private const bool VALIDATE = true;
     
    7373    }
    7474
    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.Scope
    80       };
    81     }
    82 
    8375    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) {
    8784        case PermutationTypes.Absolute: {
    8885            if (inverse) {
     
    9087                subspace[i, 0] = true;
    9188            }
    92             var first = solutions.First();
    93             foreach (var s in solutions.Skip(1)) {
     89            while (solutionsIter.MoveNext()) {
     90              var s = solutionsIter.Current;
    9491              for (var i = 0; i < s.Length; i++) {
    9592                if (first[i] != s[i]) subspace[i, 0] = !inverse;
     
    104101                  subspace[i, j] = true;
    105102            }
    106             var first = solutions.First();
    107103            var placedFirst = new int[first.Length];
    108104            for (var i = 0; i < first.Length; i++) {
    109105              placedFirst[first[i]] = i;
    110106            }
    111             foreach (var s in solutions.Skip(1)) {
     107            while (solutionsIter.MoveNext()) {
     108              var s = solutionsIter.Current;
    112109              for (var i = 0; i < s.Length; i++) {
    113110                if (placedFirst[s[i]] - placedFirst[s.GetCircular(i + 1)] != -1)
     
    123120                  subspace[i, j] = true;
    124121            }
    125             var first = solutions.First();
    126122            var placedFirst = new int[first.Length];
    127123            for (var i = 0; i < first.Length; i++) {
    128124              placedFirst[first[i]] = i;
    129125            }
    130             foreach (var s in solutions.Skip(1)) {
     126            while (solutionsIter.MoveNext()) {
     127              var s = solutionsIter.Current;
    131128              for (var i = 0; i < s.Length; i++) {
    132129                if (Math.Abs(placedFirst[s[i]] - placedFirst[s.GetCircular(i + 1)]) != 1)
     
    137134          break;
    138135        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));
    140137      }
    141138      return new PermutationSolutionSubspace(subspace);
     
    143140
    144141    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);
    146142      var quality = scope.Fitness;
    147143      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);
    149145      } finally {
    150146        scope.Fitness = quality;
     
    152148    }
    153149
    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) {
    155151      switch (perm.PermutationType) {
    156152        case PermutationTypes.Absolute:
    157           TabuWalkSwap(random, perm, eval, ref quality, maxEvals, subspace);
     153          TabuWalkSwap(random, perm, eval, token, ref quality, maxEvals, subspace);
    158154          break;
    159155        case PermutationTypes.RelativeDirected:
    160           TabuWalkShift(random, perm, eval, ref quality, maxEvals, subspace);
     156          TabuWalkShift(random, perm, eval, token, ref quality, maxEvals, subspace);
    161157          break;
    162158        case PermutationTypes.RelativeUndirected:
    163           TabuWalkOpt(random, perm, eval, ref quality, maxEvals, subspace);
     159          TabuWalkOpt(random, perm, eval, token, ref quality, maxEvals, subspace);
    164160          break;
    165161        default: throw new ArgumentException(string.Format("Permutation type {0} is not known", perm.PermutationType));
     
    168164    }
    169165
    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) {
    171167      var evaluations = 0;
    172       var maximization = Context.Problem.Maximization;
     168      var maximization = Context.Maximization;
    173169      if (double.IsNaN(quality)) {
    174         quality = eval(perm, random);
     170        quality = eval(perm, token);
    175171        evaluations++;
    176172      }
     
    202198          current[swap.Index1] = current[swap.Index2];
    203199          current[swap.Index2] = h;
    204           var q = eval(current, random);
     200          var q = eval(current, token);
    205201          evaluations++;
    206202          if (FitnessComparer.IsBetter(maximization, q, quality)) {
     
    261257    }
    262258
    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) {
    264260      return 0;
    265261    }
    266262
    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;
    269265      var evaluations = 0;
    270266      if (double.IsNaN(quality)) {
    271         quality = eval(perm, random);
     267        quality = eval(perm, token);
    272268        evaluations++;
    273269      }
     
    303299          InversionManipulator.Apply(current, opt.Index1, opt.Index2);
    304300
    305           var q = eval(current, random);
     301          var q = eval(current, token);
    306302          evaluations++;
    307303          if (FitnessComparer.IsBetter(maximization, q, quality)) {
     
    414410          continue;
    415411        }
    416         var probe = ToScope(c);
    417         Evaluate(probe, token);
     412        var probe = Context.ToScope(c);
     413        Context.Evaluate(probe, token);
    418414        evaluations++;
    419415        cache.Add(c);
     
    425421      }
    426422      Context.IncrementEvaluatedSolutions(evaluations);
    427       return offspring;
     423      return offspring ?? p1;
    428424    }
    429425
     
    449445          continue;
    450446        }
    451         var probe = ToScope(c);
    452         Evaluate(probe, token);
     447        var probe = Context.ToScope(c);
     448        Context.Evaluate(probe, token);
    453449        evaluations++;
    454450        cache.Add(c);
     
    460456      }
    461457      Context.IncrementEvaluatedSolutions(evaluations);
    462       return offspring;
     458      return offspring ?? p1;
    463459    }
    464460
     
    484480          continue;
    485481        }
    486         var probe = ToScope(c);
    487         Evaluate(probe, token);
     482        var probe = Context.ToScope(c);
     483        Context.Evaluate(probe, token);
    488484        evaluations++;
    489485        cache.Add(c);
     
    495491      }
    496492      Context.IncrementEvaluatedSolutions(evaluations);
    497       return offspring;
     493      return offspring ?? p1;
    498494    }
    499495
    500496    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));
    502497      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) {
    507502      if (p1.PermutationType != p2.PermutationType) throw new ArgumentException(string.Format("Unequal permutation types {0} and {1}", p1.PermutationType, p2.PermutationType));
    508503      switch (p1.PermutationType) {
    509504        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);
    511506        case PermutationTypes.RelativeDirected:
    512           return RelinkShift(random, p1, p2, eval, delink, out best);
     507          return RelinkShift(random, p1, p2, eval, token, delink, out best);
    513508        case PermutationTypes.RelativeUndirected:
    514           return RelinkOpt(random, p1, p2, eval, delink, out best);
     509          return RelinkOpt(random, p1, p2, eval, token, delink, out best);
    515510        default: throw new ArgumentException(string.Format("Unknown permutation type {0}", p1.PermutationType));
    516511      }
    517512    }
    518513
    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;
    521516      var evaluations = 0;
    522517      var child = (Encodings.PermutationEncoding.Permutation)p1.Clone();
     
    540535          }
    541536          Swap(child, invChild[p2[idx]], idx);
    542           var moveF = eval(child, random);
     537          var moveF = eval(child, token);
    543538          evaluations++;
    544539          if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) {
     
    565560      }
    566561      if (bestChild == null) {
    567         best = eval(child, random);
     562        best = eval(child, token);
    568563        evaluations++;
    569564      }
     
    576571    }
    577572
    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;
    580575      var evaluations = 0;
    581576      var child = (Encodings.PermutationEncoding.Permutation)p1.Clone();
     
    600595            if (k == idx) continue;
    601596            Swap(child, k, idx);
    602             var moveF = eval(child, random);
     597            var moveF = eval(child, token);
    603598            evaluations++;
    604599            if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) {
     
    624619      }
    625620      if (bestChild == null) {
    626         best = eval(child, random);
     621        best = eval(child, token);
    627622        evaluations++;
    628623      }
     
    634629    }
    635630
    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;
    638633      var evaluations = 0;
    639634      var child = (Encodings.PermutationEncoding.Permutation)p1.Clone();
     
    656651          if (c < n) Shift(child, from: n, to: c + 1);
    657652          else Shift(child, from: c, to: n);
    658           var moveF = eval(child, random);
     653          var moveF = eval(child, token);
    659654          evaluations++;
    660655          if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) {
     
    678673
    679674      if (bestChild == null) {
    680         best = eval(child, random);
     675        best = eval(child, token);
    681676        evaluations++;
    682677      }
     
    689684    }
    690685
    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;
    693688      var evaluations = 0;
    694689      var child = (Encodings.PermutationEncoding.Permutation)p1.Clone();
     
    766761            undoStack.Push(m);
    767762          }
    768           var moveF = eval(child, random);
     763          var moveF = eval(child, token);
    769764          evaluations++;
    770765          if (FitnessComparer.IsBetter(maximization, moveF, bestChange)) {
     
    792787
    793788      if (bestChild == null) {
    794         best = eval(child, random);
     789        best = eval(child, token);
    795790        evaluations++;
    796791      }
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/PermutationMemPRContext.cs

    r14450 r14552  
    2020#endregion
    2121
     22using System;
     23using System.Runtime.Remoting.Contexts;
    2224using HeuristicLab.Algorithms.MemPR.Interfaces;
    2325using HeuristicLab.Common;
     
    3133  [Item("MemPR Population Context (permutation)", "MemPR population context for permutation encoded problems.")]
    3234  [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> {
    3436
    3537    [StorableConstructor]
     
    4749      return new PermutationMemPRSolutionContext(this, solution);
    4850    }
     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    }
    4959  }
    5060
    5161  [Item("MemPR Solution Context (permutation)", "MemPR solution context for permutation encoded problems.")]
    5262  [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 {
    5464
    5565    [Storable]
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/SolutionModel/Univariate/BiasedModelTrainer.cs

    r14496 r14552  
    3434  [StorableClass]
    3535  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> {
    3838
    3939    [Storable]
     
    5959
    6060    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);
    6262    }
    6363  }
  • branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Permutation/SolutionModel/Univariate/UnbiasedModelTrainer.cs

    r14496 r14552  
    3333  [StorableClass]
    3434  public class UnbiasedModelTrainer<TContext> : NamedItem, ISolutionModelTrainer<TContext>
    35     where TContext : IPopulationBasedHeuristicAlgorithmContext<SingleObjectiveBasicProblem<PermutationEncoding>, Encodings.PermutationEncoding.Permutation>,
     35    where TContext : IPopulationBasedHeuristicAlgorithmContext<ISingleObjectiveHeuristicOptimizationProblem, Encodings.PermutationEncoding.Permutation>,
    3636    ISolutionModelContext<Encodings.PermutationEncoding.Permutation> {
    3737   
     
    4949
    5050    public void TrainModel(TContext context) {
    51       context.Model = Trainer.TrainUnbiased(context.Random, context.Population.Select(x => x.Solution).ToList(), context.Problem.Encoding.Length);
     51      context.Model = Trainer.TrainUnbiased(context.Random, context.Population.Select(x => x.Solution).ToList(), context.Population.First().Solution.Length);
    5252    }
    5353  }
  • branches/MemPRAlgorithm/HeuristicLab.Problems.Binary/3.3/AlternatingBitsProblem.cs

    r14543 r14552  
    2020#endregion
    2121
    22 using System;
    23 using System.Linq;
    2422using HeuristicLab.Common;
    2523using HeuristicLab.Core;
     
    2826
    2927namespace 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 = 210)]
     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)]
    3230  [StorableClass]
    33   public class OneMaxProblem : BinaryProblem {
     31  public class AlternatingBitsProblem : BinaryProblem {
    3432    public override bool Maximization {
    35       get { return true; }
     33      get { return false; }
    3634    }
    3735
    38     public OneMaxProblem()
     36    public AlternatingBitsProblem()
    3937      : base() {
    40       Encoding.Length = 10;
    41       BestKnownQuality = Encoding.Length;
     38      Encoding.Length = 256;
     39      BestKnownQuality = 0;
    4240    }
    4341
    4442    [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) { }
    4845    public override IDeepCloneable Clone(Cloner cloner) {
    49       return new OneMaxProblem(this, cloner);
     46      return new AlternatingBitsProblem(this, cloner);
    5047    }
    5148
    5249    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;
    5960    }
    6061  }
  • branches/MemPRAlgorithm/HeuristicLab.Problems.Binary/3.3/HeuristicLab.Problems.Binary-3.3.csproj

    r14420 r14552  
    8787    <Compile Include="HIFFProblem.cs" />
    8888    <Compile Include="BinaryKnapsackProblem.cs" />
     89    <Compile Include="AlternatingBitsProblem.cs" />
    8990    <Compile Include="OneMaxProblem.cs" />
    9091    <Compile Include="Plugin.cs" />
Note: See TracChangeset for help on using the changeset viewer.