Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/01/18 23:52:39 (7 years ago)
Author:
abeham
Message:

#1614:

  • Fixed some bugs
  • Added OSGA
  • Updated ES (added recombination)
  • Reusing operators among algorihtms (RelocateEquipmentManipluator)
  • Rewrote DiscreteLocationCrossover
Location:
branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3
Files:
1 added
9 edited
1 copied

Legend:

Unmodified
Added
Removed
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary/ESContext.cs

    r15563 r15564  
    2020#endregion
    2121
    22 using System.Collections.Generic;
    2322using HeuristicLab.Common;
    2423using HeuristicLab.Core;
     
    5049      get { return normalRand.Value; }
    5150      set { normalRand.Value = value; }
    52     }
    53 
    54     public void ReplacePopulation(IEnumerable<ISingleObjectiveSolutionScope<ESGQAPSolution>> replacement) {
    55       Scope.SubScopes.Replace(replacement);
    5651    }
    5752   
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary/EvolutionStrategy.cs

    r15563 r15564  
    6969      get { return selectionParameter; }
    7070    }
     71    [Storable]
     72    private FixedValueParameter<BoolValue> useRecombinationParameter;
     73    public IFixedValueParameter<BoolValue> UseRecombinationParameter {
     74      get { return useRecombinationParameter; }
     75    }
    7176
    7277    public int Lambda {
     
    8186      get { return selectionParameter.Value.Value; }
    8287      set { selectionParameter.Value.Value = value; }
     88    }
     89    public bool UseRecombination {
     90      get { return useRecombinationParameter.Value.Value; }
     91      set { useRecombinationParameter.Value.Value = value; }
    8392    }
    8493
     
    9099      muParameter = cloner.Clone(original.muParameter);
    91100      selectionParameter = cloner.Clone(original.selectionParameter);
     101      useRecombinationParameter = cloner.Clone(original.useRecombinationParameter);
    92102    }
    93103    public EvolutionStrategy() {
     
    95105      Parameters.Add(muParameter = new FixedValueParameter<IntValue>("Mu", "(μ) The population size.", new IntValue(1)));
    96106      Parameters.Add(selectionParameter= new FixedValueParameter<EnumValue<ESSelection>>("Selection", "The selection strategy: elitist (plus) or generational (comma).", new EnumValue<ESSelection>(ESSelection.Plus)));
    97      
     107      Parameters.Add(useRecombinationParameter = new FixedValueParameter<BoolValue>("Use Recombination", "Whether to create an \"intermediate\" solution to perform the mutation from.", new BoolValue(false)));
     108
    98109      Problem = new GQAP();
    99110    }
     
    116127        Context.EvaluatedSolutions++;
    117128
    118         var ind = new ESGQAPSolution(assign, eval, Context.Random.NextDouble() * 2 - 1);
     129        var min = (1.0 / assign.Length) * 2 - 1; // desired min prob
     130        var max = (4.0 / assign.Length) * 2 - 1; // desired max prob
     131        min = 0.5 * (Math.Log(1 + min) - Math.Log(1 - min)); // arctanh
     132        max = 0.5 * (Math.Log(1 + max) - Math.Log(1 - max));
     133        var ind = new ESGQAPSolution(assign, eval, min + Context.Random.NextDouble() * (max - min));
    119134        var fit = Problem.ProblemInstance.ToSingleObjective(eval);
    120135        Context.AddToPopulation(Context.ToScope(ind, fit));
     
    135150    protected override void Run(CancellationToken cancellationToken) {
    136151      var lastUpdate = ExecutionTime;
     152      var eq = new IntegerVectorEqualityComparer();
    137153
    138154      while (!StoppingCriterion()) {
     
    140156
    141157        for (var l = 0; l < Lambda; l++) {
    142           var m = Context.AtRandomPopulation();
    143 
    144           var offspring = (ESGQAPSolution)m.Solution.Clone();
    145           var count = Mutate(m, offspring);
    146           offspring.SParam += 0.7071 * Context.NormalRand.NextDouble(); //((1.0 / count) - offspring.SParam) / 10.0;
    147 
    148           offspring.Evaluation = Problem.ProblemInstance.Evaluate(offspring.Assignment);
     158          IntegerVector child = null;
     159          var sParam = 0.0;
     160          if (UseRecombination) {
     161            child = DiscreteLocationCrossover.Apply(Context.Random, new ItemArray<IntegerVector>(Context.Population.Select(x => x.Solution.Assignment)), Problem.ProblemInstance.Demands, Problem.ProblemInstance.Capacities);
     162            sParam = Context.Population.Select(x => x.Solution.SParam).Average();
     163          } else {
     164            var m = Context.AtRandomPopulation();
     165            child = (IntegerVector)m.Solution.Assignment.Clone();
     166            sParam = m.Solution.SParam;
     167          }
     168          sParam += 0.7071 * Context.NormalRand.NextDouble();
     169          RelocateEquipmentManipluator.Apply(Context.Random, child,
     170            Problem.ProblemInstance.Capacities.Length, (Math.Tanh(sParam) + 1) / 2.0);
     171          var eval = Problem.ProblemInstance.Evaluate(child);
    149172          Context.EvaluatedSolutions++;
     173
     174          var offspring = new ESGQAPSolution(child, eval, sParam);
     175
    150176          var fit = Problem.ProblemInstance.ToSingleObjective(offspring.Evaluation);
    151           nextGen.Add(Context.ToScope(offspring, fit));
     177          if (Selection == ESSelection.Comma || Context.Population.Select(x => x.Solution.Assignment).All(x => !eq.Equals(child, x)))
     178            nextGen.Add(Context.ToScope(offspring, fit));
    152179
    153180          if (fit < Context.BestQuality) {
     
    160187          Context.ReplacePopulation(nextGen.OrderBy(x => x.Fitness).Take(Mu));
    161188        } else if (Selection == ESSelection.Plus) {
    162           var best = nextGen.Concat(Context.Population).OrderBy(x => x.Fitness).Take(Mu).ToList();
     189          var best = Context.Population.Concat(nextGen).OrderBy(x => x.Fitness).Take(Mu).ToList();
    163190          Context.ReplacePopulation(best);
    164191        } else throw new InvalidOperationException("Unknown Selection strategy: " + Selection);
     
    181208        else Results.Add(new Result("BestSolution", Context.BestSolution));
    182209
    183         Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     210        try {
     211          Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     212        } catch (OperationCanceledException) { }
    184213
    185214        Context.Iterations++;
     
    194223      else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
    195224    }
    196 
    197     private int Mutate(ISingleObjectiveSolutionScope<ESGQAPSolution> m, ESGQAPSolution offspring) {
    198       var stopProb = (Math.Tanh(m.Solution.SParam) + 1) / 2.0; // squash strategy parameter to ]0;1[
    199       var offspringFeasible = offspring.Evaluation.IsFeasible;
    200       double[] slack = null;
    201       if (offspringFeasible) slack = offspring.Evaluation.Slack.ToArray();
    202       var count = 1;
    203       foreach (var equip in Enumerable.Range(0, Problem.ProblemInstance.Demands.Length).Shuffle(Context.Random)) {
    204         var currentLoc = offspring.Assignment[equip];
    205         if (offspringFeasible) {
    206           var demand = Problem.ProblemInstance.Demands[equip];
    207           var feasibleLoc = slack.Select((v, i) => new { Index = i, Value = v })
    208             .Where(x => x.Index != currentLoc
    209             && x.Value >= demand).ToList();
    210           int newLoc = -1;
    211           if (feasibleLoc.Count == 0) {
    212             newLoc = Context.Random.Next(Problem.ProblemInstance.Capacities.Length - 1);
    213             if (newLoc >= currentLoc) newLoc++; // don't reassign to current loc
    214             offspringFeasible = false;
    215           } else {
    216             newLoc = feasibleLoc.SampleRandom(Context.Random).Index;
    217           }
    218           offspring.Assignment[equip] = newLoc;
    219           slack[currentLoc] += demand;
    220           slack[newLoc] -= demand;
    221         } else {
    222           var newLoc = Context.Random.Next(Problem.ProblemInstance.Capacities.Length - 1);
    223           if (newLoc >= currentLoc) newLoc++; // don't reassign to current loc
    224           offspring.Assignment[equip] = newLoc;
    225         }
    226         if (Context.Random.NextDouble() < stopProb) break;
    227         count++;
    228       }
    229 
    230       return count;
    231     }
    232225  }
    233226}
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary/OSGAContext.cs

    r15562 r15564  
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
     25using HeuristicLab.Data;
    2526using HeuristicLab.Parameters;
    2627using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2728
    28 namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.GRASP {
    29   [Item("GRASP+PR (GQAP) Context", "Context for GRASP+PR (GQAP).")]
     29namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.Evolutionary {
     30  [Item("OSGA (GQAP) Context", "Context for OSGA (GQAP).")]
    3031  [StorableClass]
    31   public sealed class GRASPContext : SingleObjectivePopulationContext<ISingleObjectiveSolutionScope<GQAPSolution>> {
     32  public sealed class OSGAContext : SingleObjectivePopulationContext<ISingleObjectiveSolutionScope<GQAPSolution>> {
    3233   
    3334    [Storable]
     
    4445      set { bestSolution.Value = value; }
    4546    }
    46    
     47
     48    [Storable]
     49    private IValueParameter<ItemList<ISingleObjectiveSolutionScope<GQAPSolution>>> nextGeneration;
     50    public ItemList<ISingleObjectiveSolutionScope<GQAPSolution>> NextGeneration {
     51      get { return nextGeneration.Value; }
     52      set { nextGeneration.Value = value; }
     53    }
     54
     55    [Storable]
     56    private IValueParameter<DoubleValue> selectionPressure;
     57    public double SelectionPressure {
     58      get { return selectionPressure.Value.Value; }
     59      set { selectionPressure.Value.Value = value; }
     60    }
     61
     62    [Storable]
     63    private IValueParameter<IntValue> attempts;
     64    public int Attempts {
     65      get { return attempts.Value.Value; }
     66      set { attempts.Value.Value = value; }
     67    }
     68
    4769    public void SortPopulation() {
    4870      Scope.SubScopes.Replace(Scope.SubScopes.OfType<ISingleObjectiveSolutionScope<GQAPSolution>>().OrderBy(x => Problem.Maximization ? -x.Fitness : x.Fitness).ToList());
     
    5072   
    5173    [StorableConstructor]
    52     private GRASPContext(bool deserializing) : base(deserializing) { }
    53     private GRASPContext(GRASPContext original, Cloner cloner)
     74    private OSGAContext(bool deserializing) : base(deserializing) { }
     75    private OSGAContext(OSGAContext original, Cloner cloner)
    5476      : base(original, cloner) {
    5577      problem = cloner.Clone(original.problem);
    5678      bestSolution = cloner.Clone(original.bestSolution);
     79      nextGeneration = cloner.Clone(original.nextGeneration);
     80      selectionPressure = cloner.Clone(original.selectionPressure);
     81      attempts = cloner.Clone(original.attempts);
    5782    }
    58     public GRASPContext() : this("GRASP+PR (GQAP) Context") { }
    59     public GRASPContext(string name) : base(name) {
     83    public OSGAContext() : this("OSGA (GQAP) Context") { }
     84    public OSGAContext(string name) : base(name) {
    6085      Parameters.Add(problem = new ValueParameter<GQAP>("Problem"));
    6186      Parameters.Add(bestSolution = new ValueParameter<GQAPSolution>("BestFoundSolution"));
     87      Parameters.Add(nextGeneration = new ValueParameter<ItemList<ISingleObjectiveSolutionScope<GQAPSolution>>>("NextGeneration"));
     88      Parameters.Add(selectionPressure = new ValueParameter<DoubleValue>("SelectionPressure", new DoubleValue(0)));
     89      Parameters.Add(attempts = new ValueParameter<IntValue>("Attempts", new IntValue(0)));
    6290    }
    6391
    6492    public override IDeepCloneable Clone(Cloner cloner) {
    65       return new GRASPContext(this, cloner);
     93      return new OSGAContext(this, cloner);
    6694    }
    6795
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASP/GRASP.cs

    r15563 r15564  
    167167      while (!StoppingCriterion()) { // line 2 in Algorithm 1
    168168        // next: line 3 in Algorithm 1
    169         var pi_prime_vec = GreedyRandomizedSolutionCreator.CreateSolution(Context.Random, Problem.ProblemInstance, 1000, false, cancellationToken);
     169        IntegerVector pi_prime_vec = null;
     170        try {
     171          pi_prime_vec = GreedyRandomizedSolutionCreator.CreateSolution(Context.Random, Problem.ProblemInstance, 1000, false, cancellationToken);
     172        } catch (OperationCanceledException) { break; }
     173
    170174        if (Context.PopulationCount >= MinimumEliteSetSize) { // line 4 in Algorithm 1
    171175          GQAPSolution pi_prime;
     
    234238        else Results.Add(new Result("BestSolution", Context.BestSolution));
    235239
    236         Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     240        try {
     241          Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     242        } catch (OperationCanceledException) { }
    237243
    238244        Context.Iterations++;
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms-3.3.csproj

    r15563 r15564  
    102102    <Compile Include="Evolutionary\ESGQAPSolution.cs" />
    103103    <Compile Include="Evolutionary\EvolutionStrategy.cs" />
     104    <Compile Include="Evolutionary\OSGAContext.cs" />
     105    <Compile Include="Evolutionary\OSGA.cs" />
    104106    <Compile Include="Infrastructure\Algorithms\StochasticAlgorithm.cs" />
    105107    <Compile Include="Infrastructure\Contexts\SingleObjectiveSingleSolutionContext.cs" />
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Infrastructure/Contexts/PopulationContext.cs

    r15562 r15564  
    4040      Scope.SubScopes[index] = solScope;
    4141    }
     42    public void ReplacePopulation(IEnumerable<TSolutionScope> replacement) {
     43      Scope.SubScopes.Replace(replacement);
     44    }
    4245    public TSolutionScope AtPopulation(int index) {
    4346      return Scope.SubScopes[index] as TSolutionScope;
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LAHC/LAHC.cs

    r15563 r15564  
    156156        else Results.Add(new Result("BestSolution", Context.BestSolution));
    157157
    158         Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
    159        
     158        try {
     159          Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     160        } catch (OperationCanceledException) { }
     161
    160162        if (cancellationToken.IsCancellationRequested) break;
    161163      }
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LAHC/pLAHC.cs

    r15563 r15564  
    187187            result.Value = Context.BestSolution;
    188188          else Results.Add(new Result("BestSolution", Context.BestSolution));
    189           Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     189
     190          try {
     191            Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     192          } catch (OperationCanceledException) { }
    190193
    191194          if (cancellationToken.IsCancellationRequested) break;
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LocalSearch/IteratedLS.cs

    r15563 r15564  
    2525using HeuristicLab.Core;
    2626using HeuristicLab.Data;
    27 using HeuristicLab.Encodings.IntegerVectorEncoding;
    2827using HeuristicLab.Optimization;
     28using HeuristicLab.Parameters;
    2929using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    3030
     
    4848    }
    4949
     50    [Storable]
     51    private IFixedValueParameter<PercentValue> perturbationStrengthParameter;
     52    public IFixedValueParameter<PercentValue> PerturbationStrengthParameter {
     53      get { return perturbationStrengthParameter; }
     54    }
     55
     56    public double PerturbationStrength {
     57      get { return perturbationStrengthParameter.Value.Value; }
     58      set { perturbationStrengthParameter.Value.Value = value; }
     59    }
     60
    5061    [StorableConstructor]
    5162    private IteratedLS(bool deserializing) : base(deserializing) { }
     
    5465    }
    5566    public IteratedLS() {
     67      Parameters.Add(perturbationStrengthParameter = new FixedValueParameter<PercentValue>("PerturbationStrength", "The expected length of the random walk relative to the size of the solution vector.", new PercentValue(0.5)));
    5668
    5769      Problem = new GQAP();
     
    97109        var lsevaluations = 0;
    98110        var candidate = (GQAPSolution)Context.Incumbent.Solution.Clone();
    99         RandomWalk(Context.Random, candidate.Assignment, Problem.ProblemInstance.Capacities.Length, candidate.Assignment.Length);
     111        RelocateEquipmentManipluator.Apply(Context.Random, candidate.Assignment, Problem.ProblemInstance.Capacities.Length, 1.0 / (PerturbationStrength * candidate.Assignment.Length));
    100112        candidate.Evaluation = Problem.ProblemInstance.Evaluate(candidate.Assignment);
    101113        Context.EvaluatedSolutions++;
     
    127139        else Results.Add(new Result("BestSolution", Context.BestSolution));
    128140
    129         Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     141        try {
     142          Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     143        } catch (OperationCanceledException) { }
    130144
    131145        Context.Iterations++;
     
    140154      else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
    141155    }
    142 
    143     private static void RandomWalk(IRandom random, IntegerVector assignment, int locations, int walkLength) {
    144       for (int i = 0; i < walkLength; i++) {
    145         var equipment = random.Next(assignment.Length);
    146         assignment[equipment] = random.Next(locations);
    147         if (random.NextDouble() < 1.0 / walkLength) break;
    148       }
    149     }
    150156  }
    151157}
  • branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LocalSearch/MultistartLS.cs

    r15563 r15564  
    107107        else Results.Add(new Result("BestSolution", Context.BestSolution));
    108108
    109         Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     109        try {
     110          Context.RunOperator(Analyzer, Context.Scope, cancellationToken);
     111        } catch (OperationCanceledException) { }
    110112
    111113        Context.Iterations++;
Note: See TracChangeset for help on using the changeset viewer.