Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
04/19/10 21:13:35 (15 years ago)
Author:
abeham
Message:

Moved TabuMaker from Optimization to Optimization.Operators (and updated references)
Added StochasticMultiBranch
Implemented MultiCrossover and PermutationMultiCrossover
#976, #840

Location:
trunk/sources/HeuristicLab.Operators/3.3
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Operators/3.3/HeuristicLab.Operators-3.3.csproj

    r3407 r3418  
    9797    <Compile Include="ScopeCleaner.cs" />
    9898    <Compile Include="StochasticBranch.cs" />
     99    <Compile Include="StochasticMultiBranch.cs" />
    99100    <Compile Include="SubScopesCreator.cs" />
    100101    <Compile Include="SubScopesMixer.cs" />
  • trunk/sources/HeuristicLab.Operators/3.3/StochasticMultiBranch.cs

    r1530 r3418  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2222using System;
    2323using System.Collections.Generic;
    24 using System.Text;
     24using System.Collections.ObjectModel;
     25using System.Linq;
     26using HeuristicLab.Collections;
     27using HeuristicLab.Common;
    2528using HeuristicLab.Core;
    2629using HeuristicLab.Data;
     30using HeuristicLab.Parameters;
     31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2732
    2833namespace HeuristicLab.Operators {
     
    3035  /// Branch of operators that have different probabilities to get executed.
    3136  /// </summary>
    32   public class StochasticMultiBranch : OperatorBase {
    33     ///<inheritdoc select="summary"/>
    34     public override string Description {
    35       get { return @"TODO\r\nOperator description still missing ..."; }
     37  [Item("StochasticMultiBranch", "Branch of operators that have different probabilities to get executed.")]
     38  [StorableClass]
     39  public class StochasticMultiBranch : MultiOperator<IOperator> {
     40    public ValueLookupParameter<DoubleArray> ProbabilitiesParameter {
     41      get { return (ValueLookupParameter<DoubleArray>)Parameters["Probabilities"]; }
     42    }
     43    public ILookupParameter<IRandom> RandomParameter {
     44      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
    3645    }
    3746
     47    public DoubleArray Probabilities {
     48      get { return ProbabilitiesParameter.Value; }
     49      set { ProbabilitiesParameter.Value = value; }
     50    }
     51
     52    [StorableConstructor]
     53    public StochasticMultiBranch(bool deserializing) : base() { }
    3854    /// <summary>
    39     /// Initializes a new instance of <see cref="StochasticMultiBranch"/> with two variable infos
     55    /// Initializes a new instance of <see cref="StochasticMultiBranch"/> with two parameters
    4056    /// (<c>Probabilities</c> and <c>Random</c>).
    4157    /// </summary>
    4258    public StochasticMultiBranch()
    4359      : base() {
    44       AddVariableInfo(new VariableInfo("Probabilities", "The probabilities, that define how likely each suboperator/graph is executed. This array must sum to 1", typeof(DoubleArrayData), VariableKind.In));
    45       AddVariableInfo(new VariableInfo("Random", "The pseudo random-generator, used for any random-decision.", typeof(IRandom), VariableKind.In));
     60      Parameters.Add(new ValueLookupParameter<DoubleArray>("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
     61      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator to use."));
     62      Initialize();
     63    }
     64
     65    [StorableHook(HookType.AfterDeserialization)]
     66    private void Initialize() {
     67      Operators.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsAdded);
     68      Operators.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsRemoved);
     69      Operators.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsMoved);
     70    }
     71
     72    void Operators_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
     73      if (Probabilities != null) {
     74        DoubleArray oldProb = (DoubleArray)Probabilities.Clone();
     75        foreach (IndexedItem<IOperator> old in e.OldItems) {
     76          foreach (IndexedItem<IOperator> item in e.Items) {
     77            if (old.Value == item.Value && item.Index < Probabilities.Length && old.Index < oldProb.Length)
     78              Probabilities[item.Index] = oldProb[old.Index];
     79          }
     80        }
     81      }
     82    }
     83
     84    void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
     85      if (Probabilities != null && Probabilities.Length > Operators.Count) {
     86        List<double> probs = new List<double>(Probabilities.Cast<DoubleValue>().Select(x => x.Value));
     87        var sorted = e.Items.OrderByDescending(x => x.Index);
     88        foreach (IndexedItem<IOperator> item in sorted)
     89          if (probs.Count > item.Index) probs.RemoveAt(item.Index);
     90        Probabilities = new DoubleArray(probs.ToArray());
     91      }
     92    }
     93
     94    private void Operators_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
     95      if (Probabilities != null && Probabilities.Length < Operators.Count) {
     96        DoubleArray probs = new DoubleArray(Operators.Count);
     97        double avg = 0;
     98        if (Probabilities.Length > 0) {
     99          for (int i = 0; i < Probabilities.Length; i++)
     100            avg += Probabilities[i];
     101          avg /= (double)Probabilities.Length;
     102        } else avg = 1;
     103
     104        var added = e.Items.OrderBy(x => x.Index).ToList();
     105        int insertCount = 0;
     106        for (int i = 0; i < Operators.Count; i++) {
     107          if (insertCount < added.Count && i == added[insertCount].Index) {
     108            probs[i] = avg;
     109            insertCount++;
     110          } else if (i - insertCount < Probabilities.Length) {
     111            probs[i] = Probabilities[i - insertCount];
     112          } else probs[i] = avg;
     113        }
     114        Probabilities = probs;
     115      }
    46116    }
    47117
    48118    /// <summary>
    49     /// Applies an operator of the branches to the specified <paramref name="scope"/> with a
     119    /// Applies an operator of the branches to the current scope with a
    50120    /// specific probability.
    51121    /// </summary>
    52122    /// <exception cref="InvalidOperationException">Thrown when the list of probabilites does not
    53     /// match the number of operators or if there was another problem with the list of probabilities.</exception>
    54     /// <param name="scope">The scope to apply the operators on.</param>
    55     /// <returns>A new <see cref="AtomicOperation"/> with a specific operator, depending
    56     /// on its probability, applied on the given <paramref name="scope"/>.</returns>
    57     public override IOperation Apply(IScope scope) {
    58       IRandom random = GetVariableValue<IRandom>("Random", scope, true);
    59       DoubleArrayData probabilities = GetVariableValue<DoubleArrayData>("Probabilities", scope, true);
    60       if(probabilities.Data.Length != SubOperators.Count) {
     123    /// match the number of operators.</exception>
     124    /// <returns>A new operation with the operator that was selected followed by the current operator's successor.</returns>
     125    public override IOperation Apply() {
     126      IRandom random = RandomParameter.ActualValue;
     127      DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
     128      if(probabilities.Length != Operators.Count) {
    61129        throw new InvalidOperationException("StochasticMultiBranch: The list of probabilities has to match the number of operators");
    62130      }
    63131      double sum = 0;
    64       foreach(double prob in probabilities.Data) {
    65         sum+=prob;
     132      for (int i = 0; i < Operators.Count; i++) {
     133        sum += probabilities[i];
    66134      }
    67       double r = random.NextDouble()*sum;
     135      double r = random.NextDouble() * sum;
    68136      sum = 0;
    69137      IOperator successor = null;
    70       for(int i = 0; i < SubOperators.Count; i++) {
    71         sum += probabilities.Data[i];
     138      for(int i = 0; i < Operators.Count; i++) {
     139        sum += probabilities[i];
    72140        if(sum > r) {
    73           successor = SubOperators[i];
     141          successor = Operators[i];
    74142          break;
    75143        }
    76144      }
    77       if(successor == null) {
    78         throw new InvalidOperationException("StochasticMultiBranch: There was a problem with the list of probabilities");
     145      OperationCollection next = new OperationCollection(base.Apply());
     146      if (successor != null) {
     147        next.Insert(0, ExecutionContext.CreateOperation(successor));
    79148      }
    80       return new AtomicOperation(successor, scope);
     149      return next;
    81150    }
    82151  }
Note: See TracChangeset for help on using the changeset viewer.