CDCrossover extends AbstractCrossover<CDRule> { @Override protected List<CDRule> mate(CDRule parent1, CDRule parent2, int numberOfCrossoverPoints, Random rng) { Preconditions.checkArgument( parent1.getNbConditions() == parent2.getNbConditions(), "Cannot perform cross-over with parents of different size."); CDRule offspring1 = new CDRule(parent1); CDRule offspring2 = new CDRule(parent2); for (int i = 0; i < numberOfCrossoverPoints; i++) { int crossoverIndex = 1 + rng.nextInt(parent1.getNbConditions() - 1); for (int j = 0; j < crossoverIndex; j++) { swap(offspring1, offspring2, j); } } List<CDRule> result = Lists.newArrayListWithCapacity(2); result.add(offspring1); result.add(offspring2); return result; } CDCrossover(int crossoverPoints);  CDCrossover(int crossoverPoints, Probability crossoverProbability);   }
@Test public void testMate1() { Random rng = RandomUtils.getRandom(); DataSet dataset = EasyMock.createMock(DataSet.class); DataSet.initialize(dataset); int n = 100; int maxcrosspnts = 10; int maxattributes = 100; for (int nloop = 0; nloop < n; nloop++) { int nbattributes = rng.nextInt(maxattributes) + 3; int crosspnts = rng.nextInt(maxcrosspnts) + 1; EasyMock.reset(dataset); EasyMock.expect(dataset.getNbAttributes()).andReturn(nbattributes).times(2); EasyMock.replay(dataset); CDCrossover crossover = new CDCrossover(crosspnts); CDRule parent0 = generate0Rule(); CDRule parent1 = generate1Rule(); List<CDRule> offsprings = crossover .mate(parent0, parent1, crosspnts, rng); assertEquals("offsprings number", 2, offsprings.size()); CDRule offspring1 = offsprings.get(0); CDRule offspring2 = offsprings.get(1); for (int index = 0; index < offspring1.getNbConditions(); index++) { assertFalse("The offsprings have a common gene", CDRule.areGenesEqual( offspring1, offspring2, index)); } EasyMock.verify(dataset); } }
@Test public void testMate2() { Random rng = RandomUtils.getRandom(); DataSet dataset = EasyMock.createMock(DataSet.class); DataSet.initialize(dataset); int n = 100; int maxcrosspnts = 10; int maxattributes = 100; for (int nloop = 0; nloop < n; nloop++) { int nbattributes = rng.nextInt(maxattributes) + 3; int crosspnts = rng.nextInt(maxcrosspnts) + 1; if (crosspnts >= nbattributes) { crosspnts = nbattributes - 1; } EasyMock.reset(dataset); EasyMock.expect(dataset.getNbAttributes()).andReturn(nbattributes).times(2); EasyMock.replay(dataset); CDCrossover crossover = new CDCrossover(crosspnts); CDRule parent0 = generate0Rule(); CDRule parent1 = generate1Rule(); int m = 10; for (int mloop = 0; mloop < m; mloop++) { List<CDRule> offsprings = crossover.mate(parent0, parent1, crosspnts, rng); assertEquals("offsprings number", 2, offsprings.size()); CDRule offspring = offsprings.get(0); int nbareas = countAreas(offspring); assertTrue("NbAreas(" + nbareas + ") > crosspnts(" + crosspnts + ")+1", nbareas <= (crosspnts + 1)); } EasyMock.verify(dataset); } }