1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Text;
|
---|
4 | using HeuristicLab.Core;
|
---|
5 | using HeuristicLab.Data;
|
---|
6 | using HeuristicLab.Evolutionary;
|
---|
7 |
|
---|
8 | namespace 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 | }
|
---|