public override IOperation Apply() {
   Permutation p = PermutationParameter.ActualValue;
   TranslocationMove[] moves = GenerateMoves(p);
   Scope[] moveScopes = new Scope[moves.Length];
   for (int i = 0; i < moveScopes.Length; i++) {
     moveScopes[i] = new Scope(i.ToString());
     moveScopes[i].Variables.Add(new Variable(TranslocationMoveParameter.ActualName, moves[i]));
   }
   CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);
   return base.Apply();
 }
 public sealed override IOperation Apply() {
   ItemArray<IItem> relinkedSolutions = Relink(Parents, RelinkingAccuracy);
   var offspringScope = new Scope("Offspring");
   foreach (var solution in relinkedSolutions) {
     var scope = new Scope();
     scope.Variables.Add(new Variable(ParentsParameter.ActualName, solution));
     offspringScope.SubScopes.Add(scope);
   }
   CurrentScope.SubScopes.Add(offspringScope);
   return base.Apply();
 }
Пример #3
0
 public override IOperation Apply() {
   var lle = LLEParameter.ActualValue;
   var moves = GenerateMoves(lle);
   var moveScopes = new Scope[moves.Length];
   for (var i = 0; i < moveScopes.Length; i++) {
     moveScopes[i] = new Scope(i.ToString());
     moveScopes[i].Variables.Add(new Variable(Swap2MoveParameter.ActualName, moves[i]));
   }
   ExecutionContext.Scope.SubScopes.AddRange(moveScopes);
   return base.Apply();
 }
Пример #4
0
 private Scope(Scope original, Cloner cloner)
   : base(original, cloner) {
   if (original.variables.Count > 0) variables = cloner.Clone(original.variables);
   else variables = new VariableCollection();
   if (original.subScopes.Count > 0) {
     subScopes = cloner.Clone(original.subScopes);
     foreach (IScope child in SubScopes)
       child.Parent = this;
   } else subScopes = new ScopeList();
   RegisterSubScopesEvents();
 }
Пример #5
0
 public override IOperation Apply() {
   BinaryVector v = BinaryVectorParameter.ActualValue;
   OneBitflipMove[] moves = GenerateMoves(v);
   Scope[] moveScopes = new Scope[moves.Length];
   for (int i = 0; i < moveScopes.Length; i++) {
     moveScopes[i] = new Scope(i.ToString());
     moveScopes[i].Variables.Add(new Variable(OneBitflipMoveParameter.ActualName, moves[i]));
   }
   CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);
   return base.Apply();
 }
 public override IOperation Apply() {
   var p = PermutationParameter.ActualValue;
   var moves = GenerateMoves(p);
   var moveScopes = new Scope[moves.Length];
   for (int i = 0; i < moveScopes.Length; i++) {
     moveScopes[i] = new Scope(i.ToString());
     moveScopes[i].Variables.Add(new Variable(TwoPointFiveMoveParameter.ActualName, moves[i]));
   }
   ExecutionContext.Scope.SubScopes.AddRange(moveScopes);
   return base.Apply();
 }
Пример #7
0
 public override IOperation Apply() {
   RealVector vector = RealVectorParameter.ActualValue;
   DoubleMatrix bounds = BoundsParameter.ActualValue;
   AdditiveMove[] moves = GenerateMoves(RandomParameter.ActualValue, vector, bounds);
   Scope[] moveScopes = new Scope[moves.Length];
   for (int i = 0; i < moveScopes.Length; i++) {
     moveScopes[i] = new Scope(i.ToString());
     moveScopes[i].Variables.Add(new Variable(AdditiveMoveParameter.ActualName, moves[i]));
   }
   CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);
   return base.Apply();
 }
Пример #8
0
 public override IOperation Apply() {
   var child = new Scope();
   child.Variables.AddRange(CurrentScope.Variables);
   var offspringScope = new Scope();
   offspringScope.SubScopes.Add(child);
   var parents = CurrentScope.SubScopes.ToArray();
   CurrentScope.Variables.Clear();
   CurrentScope.SubScopes.Clear();
   CurrentScope.SubScopes.AddRange(parents);
   CurrentScope.SubScopes.Add(offspringScope);
   return base.Apply();
 }
Пример #9
0
    public sealed override IOperation InstrumentedApply() {
      List<IScope> scopes = new List<IScope>(CurrentScope.SubScopes);
      IScope[] selected = Select(scopes);

      CurrentScope.SubScopes.Clear();
      IScope remainingScope = new Scope("Remaining");
      remainingScope.SubScopes.AddRange(scopes);
      CurrentScope.SubScopes.Add(remainingScope);
      IScope selectedScope = new Scope("Selected");
      selectedScope.SubScopes.AddRange(selected);
      CurrentScope.SubScopes.Add(selectedScope);

      return base.InstrumentedApply();
    }
    public override IOperation InstrumentedApply() {
      IOperation next = base.InstrumentedApply();

      PotvinEncoding individual = VRPToursParameter.ActualValue as PotvinEncoding;
      PotvinPDShiftMove[] moves = GenerateMoves(individual, ProblemInstance);
      Scope[] moveScopes = new Scope[moves.Length];
      for (int i = 0; i < moveScopes.Length; i++) {
        moveScopes[i] = new Scope(i.ToString());
        moveScopes[i].Variables.Add(new Variable(PDShiftMoveParameter.ActualName, moves[i]));
      }
      CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);

      return next;
    }
Пример #11
0
    public override IOperation Apply() {
      int nChildren = CurrentScope.SubScopes.Count;

      for (int i = 0; i < nChildren; i++) {
        IScope child = CurrentScope.SubScopes[i];
        if (child.SubScopes.Count > 0) throw new ArgumentException("The sub-scope that should be cloned has further sub-scopes.");

        IScope childCopy = new Scope(i.ToString());
        var cloner = new Cloner();
        foreach (IVariable var in child.Variables)
          childCopy.Variables.Add(cloner.Clone(var));

        child.SubScopes.Add(childCopy);
      }
      return base.Apply();
    }
    public override IOperation Apply() {
      var random = RandomParameter.ActualValue;
      var sampleSize = SampleSizeParameter.ActualValue.Value;
      var encoding = EncodingParameter.ActualValue;
      var individual = encoding.GetIndividual(ExecutionContext.Scope);
      var nbhood = GetNeighborsFunc(individual, random).Take(sampleSize).ToList();

      var moveScopes = new Scope[nbhood.Count];
      for (int i = 0; i < moveScopes.Length; i++) {
        moveScopes[i] = new Scope(i.ToString(CultureInfo.InvariantCulture.NumberFormat));
        nbhood[i].CopyToScope(moveScopes[i]);
      }
      ExecutionContext.Scope.SubScopes.AddRange(moveScopes);

      return base.Apply();
    }
Пример #13
0
    public override IOperation Apply() {
      int parentsPerChild = ParentsPerChildParameter.ActualValue.Value;
      int parents = CurrentScope.SubScopes.Count;
      if (parents % parentsPerChild > 0) throw new InvalidOperationException("Number of parents is not an integral multiple of ParentsPerChild.");
      int children = parents / parentsPerChild;

      for (int i = 0; i < children; i++) {
        IScope child = new Scope(i.ToString());
        for (int j = 0; j < parentsPerChild; j++) {
          IScope parent = CurrentScope.SubScopes[0];
          CurrentScope.SubScopes.RemoveAt(0);
          child.SubScopes.Add(parent);
        }
        CurrentScope.SubScopes.Add(child);
      }
      return base.Apply();
    }
    private static void SymbolicDataAnalysisCrossoverPerformanceTest(ISymbolicDataAnalysisExpressionCrossover<IRegressionProblemData> crossover) {
      var twister = new MersenneTwister(31415);
      var dataset = Util.CreateRandomDataset(twister, Rows, Columns);
      var grammar = new FullFunctionalExpressionGrammar();
      var stopwatch = new Stopwatch();

      grammar.MaximumFunctionArguments = 0;
      grammar.MaximumFunctionDefinitions = 0;
      grammar.MinimumFunctionArguments = 0;
      grammar.MinimumFunctionDefinitions = 0;

      var trees = Util.CreateRandomTrees(twister, dataset, grammar, PopulationSize, 1, MaxTreeLength, 0, 0);
      foreach (ISymbolicExpressionTree tree in trees) {
        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
      }
      var problemData = new RegressionProblemData(dataset, dataset.VariableNames, dataset.VariableNames.Last());
      var problem = new SymbolicRegressionSingleObjectiveProblem();
      problem.ProblemData = problemData;

      var globalScope = new Scope("Global Scope");
      globalScope.Variables.Add(new Core.Variable("Random", twister));
      var context = new ExecutionContext(null, problem, globalScope);
      context = new ExecutionContext(context, crossover, globalScope);

      stopwatch.Start();
      for (int i = 0; i != PopulationSize; ++i) {
        var parent0 = (ISymbolicExpressionTree)trees.SampleRandom(twister).Clone();
        var scopeParent0 = new Scope();
        scopeParent0.Variables.Add(new Core.Variable(crossover.ParentsParameter.ActualName, parent0));
        context.Scope.SubScopes.Add(scopeParent0);

        var parent1 = (ISymbolicExpressionTree)trees.SampleRandom(twister).Clone();
        var scopeParent1 = new Scope();
        scopeParent1.Variables.Add(new Core.Variable(crossover.ParentsParameter.ActualName, parent1));
        context.Scope.SubScopes.Add(scopeParent1);

        crossover.Execute(context, new CancellationToken());

        context.Scope.SubScopes.Remove(scopeParent0); // clean the scope in preparation for the next iteration
        context.Scope.SubScopes.Remove(scopeParent1); // clean the scope in preparation for the next iteration
      }
      stopwatch.Stop();
      double msPerCrossover = 2 * stopwatch.ElapsedMilliseconds / (double)PopulationSize;
      Console.WriteLine(crossover.Name + ": " + Environment.NewLine +
                        msPerCrossover + " ms per crossover (~" + Math.Round(1000.0 / (msPerCrossover)) + " crossover operations / s)");

      foreach (var tree in trees)
        HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Tests.Util.IsValid(tree);
    }
Пример #15
0
    public override IOperation Apply() {
      bool dominateOnEqualQualities = DominateOnEqualQualitiesParameter.ActualValue.Value;
      bool[] maximization = MaximizationParameter.ActualValue.ToArray();
      double[][] qualities = QualitiesParameter.ActualValue.Select(x => x.ToArray()).ToArray();
      if (qualities == null) throw new InvalidOperationException(Name + ": No qualities found.");

      IScope scope = ExecutionContext.Scope;
      int populationSize = scope.SubScopes.Count;

      List<ScopeList> fronts = new List<ScopeList>();
      Dictionary<IScope, List<int>> dominatedScopes = new Dictionary<IScope, List<int>>();
      int[] dominationCounter = new int[populationSize];
      ItemArray<IntValue> rank = new ItemArray<IntValue>(populationSize);

      for (int pI = 0; pI < populationSize - 1; pI++) {
        IScope p = scope.SubScopes[pI];
        List<int> dominatedScopesByp;
        if (!dominatedScopes.TryGetValue(p, out dominatedScopesByp))
          dominatedScopes[p] = dominatedScopesByp = new List<int>();
        for (int qI = pI + 1; qI < populationSize; qI++) {
          DominationResult test = Dominates(qualities[pI], qualities[qI], maximization, dominateOnEqualQualities);
          if (test == DominationResult.Dominates) {
            dominatedScopesByp.Add(qI);
            dominationCounter[qI] += 1;
          } else if (test == DominationResult.IsDominated) {
            dominationCounter[pI] += 1;
            if (!dominatedScopes.ContainsKey(scope.SubScopes[qI]))
              dominatedScopes.Add(scope.SubScopes[qI], new List<int>());
            dominatedScopes[scope.SubScopes[qI]].Add(pI);
          }
          if (pI == populationSize - 2
            && qI == populationSize - 1
            && dominationCounter[qI] == 0) {
            rank[qI] = new IntValue(0);
            AddToFront(scope.SubScopes[qI], fronts, 0);
          }
        }
        if (dominationCounter[pI] == 0) {
          rank[pI] = new IntValue(0);
          AddToFront(p, fronts, 0);
        }
      }
      int i = 0;
      while (i < fronts.Count && fronts[i].Count > 0) {
        ScopeList nextFront = new ScopeList();
        foreach (IScope p in fronts[i]) {
          List<int> dominatedScopesByp;
          if (dominatedScopes.TryGetValue(p, out dominatedScopesByp)) {
            for (int k = 0; k < dominatedScopesByp.Count; k++) {
              int dominatedScope = dominatedScopesByp[k];
              dominationCounter[dominatedScope] -= 1;
              if (dominationCounter[dominatedScope] == 0) {
                rank[dominatedScope] = new IntValue(i + 1);
                nextFront.Add(scope.SubScopes[dominatedScope]);
              }
            }
          }
        }
        i += 1;
        fronts.Add(nextFront);
      }

      RankParameter.ActualValue = rank;

      scope.SubScopes.Clear();

      for (i = 0; i < fronts.Count; i++) {
        Scope frontScope = new Scope("Front " + i);
        foreach (var p in fronts[i])
          frontScope.SubScopes.Add(p);
        if (frontScope.SubScopes.Count > 0)
          scope.SubScopes.Add(frontScope);
      }
      return base.Apply();
    }
    public override IOperation Apply() {
      if (CurrentScope.SubScopes.Any()) { // offspring created
        if (!OffspringList.Any()) OffspringList.AddRange(CurrentScope.SubScopes);
        else { // stored offspring exists
          var storedOffspringScope = new Scope();
          storedOffspringScope.SubScopes.AddRange(OffspringList);
          var similarityMatrix = SimilarityCalculatorParameter.ActualValue.CalculateSolutionCrowdSimilarity(CurrentScope, storedOffspringScope);

          var createdOffspring = CurrentScope.SubScopes.ToArray();

          int i = 0;
          // as long as offspring is available and not enough offspring has been preserved
          while (i < createdOffspring.Length && OffspringList.Count < MaximumPopulationSize.Value - Elites.Value) {
            if (similarityMatrix[i].Any(x => x.IsAlmost(1.0))) createdOffspring[i] = null; // discard duplicates
            else OffspringList.Add(createdOffspring[i]);
            i++;
          }

          // discard remaining offspring
          while (i < createdOffspring.Length) createdOffspring[i++] = null;

          // clean current scope
          CurrentScope.SubScopes.Replace(createdOffspring.Where(x => x != null));
        }
      }
      return base.Apply();
    }
Пример #17
0
    /// <summary>
    /// Implements the tabu selection with the default aspiration criteria (choose a tabu move when it is better than the best so far).
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when the neighborhood contained too little moves which are not tabu.</exception>
    /// <param name="scopes">The scopes from which to select.</param>
    /// <returns>The selected scopes.</returns>
    protected override IScope[] Select(List<IScope> scopes) {
      bool copy = CopySelectedParameter.Value.Value;
      bool aspiration = AspirationParameter.ActualValue.Value;
      bool maximization = MaximizationParameter.ActualValue.Value;
      double bestQuality = BestQualityParameter.ActualValue.Value;
      ItemArray<DoubleValue> moveQualities = MoveQualityParameter.ActualValue;
      ItemArray<BoolValue> moveTabus = MoveTabuParameter.ActualValue;

      IScope[] selected = new IScope[1];

      // remember scopes that should be removed
      List<int> scopesToRemove = new List<int>();
      for (int i = 0; i < scopes.Count; i++) {
        if (!moveTabus[i].Value
          || aspiration && IsBetter(maximization, moveQualities[i].Value, bestQuality)) {
          scopesToRemove.Add(i);
          if (copy) selected[0] = (IScope)scopes[i].Clone();
          else selected[0] = scopes[i];
          break;
        }
      }

      if (selected[0] == null) {
        EmptyNeighborhoodParameter.ActualValue = new BoolValue(true);
        selected[0] = new Scope("All moves are tabu.");
      } else EmptyNeighborhoodParameter.ActualValue = new BoolValue(false);

      // remove from last to first so that the stored indices remain the same
      if (!copy) {
        while (scopesToRemove.Count > 0) {
          scopes.RemoveAt(scopesToRemove[scopesToRemove.Count - 1]);
          scopesToRemove.RemoveAt(scopesToRemove.Count - 1);
        }
      }

      return selected;
    }
    /// <summary>
    /// Sets how many sub-scopes male and female selectors should select.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when <see cref="NumberOfSelectedSubScopesParameter"/> returns an odd number.</exception>
    /// <returns>Returns Apply of <see cref="AlgorithmOperator"/>.</returns>
    public override IOperation Apply() {
      #region set number of selected subscopes
      int count = NumberOfSelectedSubScopesParameter.ActualValue.Value;
      int operators = CheckedSelectors.Count();
      int numberOfSelected = count / operators;
      int remaining = count % operators;

      foreach (var selector in CheckedSelectors) {
        int numberOfSelectedSubScopes = numberOfSelected;
        if (remaining > 0) {
          numberOfSelectedSubScopes++;
          remaining--;
        }

        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(numberOfSelectedSubScopes);
      }
      #endregion

      #region prepare subscopes as a selector would
      List<IScope> scopes = new List<IScope>(CurrentScope.SubScopes);
      CurrentScope.SubScopes.Clear();
      IScope remainingScope = new Scope("Remaining");
      remainingScope.SubScopes.AddRange(scopes);
      CurrentScope.SubScopes.Add(remainingScope);
      IScope selectedScope = new Scope("Selected");
      selectedScope.SubScopes.AddRange(new IScope[0]);
      CurrentScope.SubScopes.Add(selectedScope);
      #endregion
      return base.Apply();
    }
    public override IOperation Apply() {
      IScope currentScope = ExecutionContext.Scope;

      Scope localScope = new Scope();
      Scope individual = new Scope();

      foreach (IVariable var in currentScope.Variables)
        individual.Variables.Add(var); // add reference to variable otherwise the analyzer fails (it's looking down the tree)

      localScope.SubScopes.Add(individual);
      currentScope.SubScopes.Add(localScope);
      int index = currentScope.SubScopes.Count - 1;

      SubScopesProcessor processor = new SubScopesProcessor();
      SubScopesRemover remover = new SubScopesRemover();

      remover.RemoveAllSubScopes = false;
      remover.SubScopeIndexParameter.Value = new IntValue(index);

      if (index > 0) {
        EmptyOperator eo = new EmptyOperator();
        for (int i = 0; i < index - 1; i++) {
          processor.Operators.Add(eo);
        }
      }

      VariableCreator variableCreator = new VariableCreator();
      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>(loop.IterationsParameter.ActualName, new IntValue(0)));
      variableCreator.CollectedValues.Add(new ValueParameter<DoubleValue>(loop.BestLocalQualityParameter.ActualName, new DoubleValue(0)));

      variableCreator.Successor = loop;

      processor.Operators.Add(variableCreator);
      processor.Successor = remover;

      OperationCollection next = new OperationCollection(base.Apply());
      next.Insert(0, ExecutionContext.CreateChildOperation(processor));

      return next;
    }