Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/09/17 00:36:20 (8 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/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • 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]
Note: See TracChangeset for help on using the changeset viewer.