Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.1/sources/HeuristicLab.SimOpt/SimOptSinglePointCrossover.cs @ 583

Last change on this file since 583 was 583, checked in by abeham, 16 years ago

Adding communication framework to branch 3.1 (ticket #278)

File size: 1.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4using HeuristicLab.Core;
5using HeuristicLab.Data;
6using HeuristicLab.Operators;
7using HeuristicLab.Random;
8using HeuristicLab.Evolutionary;
9
10namespace HeuristicLab.SimOpt {
11  public class SimOptSinglePointCrossover : CrossoverBase {
12
13    public override string Description {
14      get { return @"This operator applies a single point crossover on the variables defined"; }
15    }
16
17    public SimOptSinglePointCrossover()
18      : base() {
19      AddVariableInfo(new VariableInfo("Item", "The item list to be crossed", typeof(ConstrainedItemList), VariableKind.In));
20    }
21
22    protected override void Cross(IScope scope, IRandom random, IScope parent1, IScope parent2, IScope child) {
23      ICollection<IConstraint> violated;
24      ConstrainedItemList p1 = parent1.GetVariableValue<ConstrainedItemList>("Item", false);
25      ConstrainedItemList p2 = parent2.GetVariableValue<ConstrainedItemList>("Item", false);
26
27      if (p1.Count != p2.Count) throw new InvalidOperationException("ERROR: the lists do not contain the same number of items");
28
29      ConstrainedItemList childList = (ConstrainedItemList)p1.Clone();
30      if (childList.Count > 1) {
31        int iter = 0;
32        do {
33          childList.BeginCombinedOperation();
34          int crossPoint = random.Next(1, childList.Count);
35          for (int i = crossPoint; i < childList.Count; i++) {
36            childList.TrySetAt(i, (IItem)p2[i].Clone(), out violated);
37          }
38        } while (!childList.EndCombinedOperation(out violated) && ++iter < 100);
39        if (violated.Count == 0) {
40          child.AddVariable(new Variable(parent1.TranslateName("Item"), childList));
41        }
42      }
43    }
44  }
45}
Note: See TracBrowser for help on using the repository browser.