Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
12/29/17 23:56:43 (6 years ago)
Author:
abeham
Message:

#1614: added additional algorithms

Location:
branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary
Files:
1 added
1 copied

Legend:

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

    r15558 r15562  
    2020#endregion
    2121
    22 using System;
    2322using System.Collections.Generic;
    24 using System.Linq;
    25 using System.Runtime.CompilerServices;
    26 using System.Threading;
    2723using HeuristicLab.Common;
    2824using HeuristicLab.Core;
    29 using HeuristicLab.Data;
    30 using HeuristicLab.Optimization;
    3125using HeuristicLab.Parameters;
    3226using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    33 using HeuristicLab.Random;
    3427
    35 namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.GRASP {
    36   [Item("GRASP+PR (GQAP) Context", "Context for GRASP+PR (GQAP).")]
     28namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.Evolutionary {
     29  [Item("Evolution Strategy (GQAP) Context", "Context for Evolution Strategies (GQAP).")]
    3730  [StorableClass]
    38   public sealed class GRASPContext : ParameterizedNamedItem, IExecutionContext {
     31  public sealed class ESContext : SingleObjectivePopulationContext<ISingleObjectiveSolutionScope<ESGQAPSolution>> {
    3932   
    40     private IExecutionContext parent;
    41     public IExecutionContext Parent {
    42       get { return parent; }
    43       set { parent = value; }
    44     }
    45 
    46     [Storable]
    47     private IScope scope;
    48     public IScope Scope {
    49       get { return scope; }
    50       private set { scope = value; }
    51     }
    52 
    53     IKeyedItemCollection<string, IParameter> IExecutionContext.Parameters {
    54       get { return Parameters; }
    55     }
    56 
    5733    [Storable]
    5834    private IValueParameter<GQAP> problem;
     
    6137      set { problem.Value = value; }
    6238    }
    63     public bool Maximization {
    64       get { return Problem.Maximization; }
    65     }
    6639
    6740    [Storable]
    68     private IValueParameter<BoolValue> initialized;
    69     public bool Initialized {
    70       get { return initialized.Value.Value; }
    71       set { initialized.Value.Value = value; }
    72     }
    73 
    74     [Storable]
    75     private IValueParameter<IntValue> iterations;
    76     public int Iterations {
    77       get { return iterations.Value.Value; }
    78       set { iterations.Value.Value = value; }
    79     }
    80 
    81     [Storable]
    82     private IValueParameter<IntValue> evaluatedSolutions;
    83     public int EvaluatedSolutions {
    84       get { return evaluatedSolutions.Value.Value; }
    85       set { evaluatedSolutions.Value.Value = value; }
    86     }
    87 
    88     [Storable]
    89     private IValueParameter<DoubleValue> bestQuality;
    90     public double BestQuality {
    91       get { return bestQuality.Value.Value; }
    92       set { bestQuality.Value.Value = value; }
    93     }
    94 
    95     [Storable]
    96     private IValueParameter<GQAPSolution> bestSolution;
    97     public GQAPSolution BestSolution {
     41    private IValueParameter<ESGQAPSolution> bestSolution;
     42    public ESGQAPSolution BestSolution {
    9843      get { return bestSolution.Value; }
    9944      set { bestSolution.Value = value; }
    10045    }
    10146
    102     [Storable]
    103     private IValueParameter<IntValue> localSearchEvaluations;
    104     public int LocalSearchEvaluations {
    105       get { return localSearchEvaluations.Value.Value; }
    106       set { localSearchEvaluations.Value.Value = value; }
    107     }
    108    
    109     [Storable]
    110     private IValueParameter<IRandom> random;
    111     public IRandom Random {
    112       get { return random.Value; }
    113       set { random.Value = value; }
    114     }
    115 
    116     public IEnumerable<ISingleObjectiveSolutionScope<GQAPSolution>> Population {
    117       get { return scope.SubScopes.OfType<ISingleObjectiveSolutionScope<GQAPSolution>>(); }
    118     }
    119     public void AddToPopulation(ISingleObjectiveSolutionScope<GQAPSolution> solScope) {
    120       scope.SubScopes.Add(solScope);
    121     }
    122     public void ReplaceAtPopulation(int index, ISingleObjectiveSolutionScope<GQAPSolution> solScope) {
    123       scope.SubScopes[index] = solScope;
    124     }
    125     public ISingleObjectiveSolutionScope<GQAPSolution> AtPopulation(int index) {
    126       return scope.SubScopes[index] as ISingleObjectiveSolutionScope<GQAPSolution>;
    127     }
    128     public void SortPopulation() {
    129       scope.SubScopes.Replace(scope.SubScopes.OfType<ISingleObjectiveSolutionScope<GQAPSolution>>().OrderBy(x => Maximization ? -x.Fitness : x.Fitness).ToList());
    130     }
    131     public int PopulationCount {
    132       get { return scope.SubScopes.Count; }
     47    public void ReplacePopulation(IEnumerable<ISingleObjectiveSolutionScope<ESGQAPSolution>> replacement) {
     48      Scope.SubScopes.Replace(replacement);
    13349    }
    13450   
    13551    [StorableConstructor]
    136     private GRASPContext(bool deserializing) : base(deserializing) { }
    137     private GRASPContext(GRASPContext original, Cloner cloner)
     52    private ESContext(bool deserializing) : base(deserializing) { }
     53    private ESContext(ESContext original, Cloner cloner)
    13854      : base(original, cloner) {
    139       scope = cloner.Clone(original.scope);
    14055      problem = cloner.Clone(original.problem);
    141       initialized = cloner.Clone(original.initialized);
    142       iterations = cloner.Clone(original.iterations);
    143       evaluatedSolutions = cloner.Clone(original.evaluatedSolutions);
    144       bestQuality = cloner.Clone(original.bestQuality);
    14556      bestSolution = cloner.Clone(original.bestSolution);
    146       localSearchEvaluations = cloner.Clone(original.localSearchEvaluations);
    147       random = cloner.Clone(original.random);
    14857    }
    149     public GRASPContext() : this("GRASP+PR (GQAP) Context") { }
    150     public GRASPContext(string name) : base(name) {
    151       scope = new Scope("Global");
    152 
     58    public ESContext() : this("Evolution Strategy (GQAP) Context") { }
     59    public ESContext(string name) : base(name) {
    15360      Parameters.Add(problem = new ValueParameter<GQAP>("Problem"));
    154       Parameters.Add(initialized = new ValueParameter<BoolValue>("Initialized", new BoolValue(false)));
    155       Parameters.Add(iterations = new ValueParameter<IntValue>("Iterations", new IntValue(0)));
    156       Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
    157       Parameters.Add(bestQuality = new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(double.NaN)));
    158       Parameters.Add(bestSolution = new ValueParameter<GQAPSolution>("BestFoundSolution"));
    159       Parameters.Add(localSearchEvaluations = new ValueParameter<IntValue>("LocalSearchEvaluations", new IntValue(0)));
    160       Parameters.Add(random = new ValueParameter<IRandom>("Random", new MersenneTwister()));
     61      Parameters.Add(bestSolution = new ValueParameter<ESGQAPSolution>("BestFoundSolution"));
    16162    }
    16263
    16364    public override IDeepCloneable Clone(Cloner cloner) {
    164       return new GRASPContext(this, cloner);
     65      return new ESContext(this, cloner);
    16566    }
    16667
    167     public ISingleObjectiveSolutionScope<GQAPSolution> ToScope(GQAPSolution code, double fitness = double.NaN) {
     68    public ISingleObjectiveSolutionScope<ESGQAPSolution> ToScope(ESGQAPSolution code, double fitness = double.NaN) {
    16869      var name = Problem.Encoding.Name;
    169       var scope = new SingleObjectiveSolutionScope<GQAPSolution>(code,
     70      var scope = new SingleObjectiveSolutionScope<ESGQAPSolution>(code,
    17071        name + "Solution", fitness, Problem.Evaluator.QualityParameter.ActualName) {
    17172        Parent = Scope
     
    17576      return scope;
    17677    }
    177 
    178     public void IncrementEvaluatedSolutions(int byEvaluations) {
    179       if (byEvaluations < 0) throw new ArgumentException("Can only increment and not decrement evaluated solutions.");
    180       EvaluatedSolutions += byEvaluations;
    181     }
    182    
    183     private static void ExecuteAlgorithm(IAlgorithm algorithm) {
    184       using (var evt = new AutoResetEvent(false)) {
    185         EventHandler exeStateChanged = (o, args) => {
    186           if (algorithm.ExecutionState != ExecutionState.Started)
    187             evt.Set();
    188         };
    189         algorithm.ExecutionStateChanged += exeStateChanged;
    190         if (algorithm.ExecutionState != ExecutionState.Prepared) {
    191           algorithm.Prepare(true);
    192           evt.WaitOne();
    193         }
    194         algorithm.Start();
    195         evt.WaitOne();
    196         algorithm.ExecutionStateChanged -= exeStateChanged;
    197       }
    198     }
    199     [MethodImpl(MethodImplOptions.AggressiveInlining)]
    200     public bool IsBetter(ISingleObjectiveSolutionScope<GQAPSolution> a, ISingleObjectiveSolutionScope<GQAPSolution> b) {
    201       return IsBetter(a.Fitness, b.Fitness);
    202     }
    203     [MethodImpl(MethodImplOptions.AggressiveInlining)]
    204     public bool IsBetter(double a, double b) {
    205       return double.IsNaN(b) && !double.IsNaN(a)
    206         || Maximization && a > b
    207         || !Maximization && a < b;
    208     }
    209 
    210     #region IExecutionContext members
    211     public IAtomicOperation CreateOperation(IOperator op) {
    212       return new Core.ExecutionContext(this, op, Scope);
    213     }
    214 
    215     public IAtomicOperation CreateOperation(IOperator op, IScope s) {
    216       return new Core.ExecutionContext(this, op, s);
    217     }
    218 
    219     public IAtomicOperation CreateChildOperation(IOperator op) {
    220       return new Core.ExecutionContext(this, op, Scope);
    221     }
    222 
    223     public IAtomicOperation CreateChildOperation(IOperator op, IScope s) {
    224       return new Core.ExecutionContext(this, op, s);
    225     }
    226     #endregion
    227 
    228     #region Engine Helper
    229     public void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
    230       var stack = new Stack<IOperation>();
    231       stack.Push(CreateChildOperation(op, scope));
    232 
    233       while (stack.Count > 0) {
    234         cancellationToken.ThrowIfCancellationRequested();
    235 
    236         var next = stack.Pop();
    237         if (next is OperationCollection) {
    238           var coll = (OperationCollection)next;
    239           for (int i = coll.Count - 1; i >= 0; i--)
    240             if (coll[i] != null) stack.Push(coll[i]);
    241         } else if (next is IAtomicOperation) {
    242           var operation = (IAtomicOperation)next;
    243           try {
    244             next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
    245           } catch (Exception ex) {
    246             stack.Push(operation);
    247             if (ex is OperationCanceledException) throw ex;
    248             else throw new OperatorExecutionException(operation.Operator, ex);
    249           }
    250           if (next != null) stack.Push(next);
    251         }
    252       }
    253     }
    254     #endregion
    25578  }
    25679}
Note: See TracChangeset for help on using the changeset viewer.