Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.RealVector/HeuristicCrossover.cs @ 94

Last change on this file since 94 was 77, checked in by swagner, 17 years ago

Fixed ticket #67

  • adapted accessing of variables in operators due to changes of variable lookup and the new name aliasing mechanism (actual/formal name translations should not be done directly anymore; instead the new method Scope.TranslateName should be used)
File size: 2.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4using HeuristicLab.Core;
5using HeuristicLab.Data;
6using HeuristicLab.Evolutionary;
7
8namespace HeuristicLab.RealVector {
9  class HeuristicCrossover : CrossoverBase {
10    public HeuristicCrossover()
11      : base() {
12      AddVariableInfo(new VariableInfo("Maximization", "Maximization problem", typeof(BoolData), VariableKind.In));
13      AddVariableInfo(new VariableInfo("Quality", "Quality value", typeof(DoubleData), VariableKind.In));
14      AddVariableInfo(new VariableInfo("RealVector", "Parent and child real vector", typeof(DoubleArrayData), VariableKind.In | VariableKind.New));
15    }
16
17    public override string Description {
18      get { return "Heuristic crossover for real vectors."; }
19    }
20
21    public static double[] Apply(IRandom random, bool maximization, double[] parent1, double quality1, double[] parent2, double quality2) {
22      int length = parent1.Length;
23      double[] result = new double[length];
24      double factor = random.NextDouble();
25
26      for (int i = 0; i < length; i++) {
27        if ((maximization && (quality1 > quality2)) || ((!maximization) && (quality1 < quality2)))
28          result[i] = parent1[i] + factor * (parent1[i] - parent2[i]);
29        else
30          result[i] = parent2[i] + factor * (parent2[i] - parent1[i]);
31      }
32      return result;
33    }
34
35    protected sealed override void Cross(IScope scope, IRandom random, IScope parent1, IScope parent2, IScope child) {
36      bool maximization = GetVariableValue<BoolData>("Maximization", scope, true).Data;
37      DoubleArrayData vector1 = parent1.GetVariableValue<DoubleArrayData>("RealVector", false);
38      DoubleData quality1 = parent1.GetVariableValue<DoubleData>("Quality", false);
39      DoubleArrayData vector2 = parent2.GetVariableValue<DoubleArrayData>("RealVector", false);
40      DoubleData quality2 = parent2.GetVariableValue<DoubleData>("Quality", false);
41
42      if (vector1.Data.Length != vector2.Data.Length) throw new InvalidOperationException("Cannot apply crossover to real vectors of different length.");
43
44      double[] result = Apply(random, maximization, vector1.Data, quality1.Data, vector2.Data, quality2.Data);
45      child.AddVariable(new Variable(child.TranslateName("RealVector"), new DoubleArrayData(result)));
46    }
47  }
48}
Note: See TracBrowser for help on using the repository browser.