Java Code Examples for org.apache.commons.math3.random.RandomGenerator#nextInt()

The following examples show how to use org.apache.commons.math3.random.RandomGenerator#nextInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FenwickTreeTest.java    From fasten with Apache License 2.0 6 votes vote down vote up
@Test
public void testBernoulli() {
	FenwickTree t = new FenwickTree(2);
	RandomGenerator random = new XoRoShiRo128PlusRandomGenerator(0);
	// Increment the same number of times counters 1 and 2
	int times = random.nextInt(1000) + 1000;
	int[] increments = new int[] {times, times};
	while (increments[0] + increments[1] > 0) {
		int whichOne = random.nextInt(2);
		if (increments[whichOne] == 0) whichOne = 1 - whichOne;
		t.incrementCount(whichOne + 1);
		increments[whichOne]--;
	}
	// Now sample
	int sampleSize = 1000000;
	for (int i = 0; i < sampleSize; i++) {
		int sample = t.sample(random);
		increments[sample - 1]++;
	}
	assertEquals((double)increments[0] / sampleSize, 0.5, 1E-3);
}
 
Example 2
Source File: FastByIDMapTest.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersusHashMap() {
  FastByIDMap<String> actual = new FastByIDMap<String>();
  Map<Long, String> expected = Maps.newHashMapWithExpectedSize(1000000);
  RandomGenerator r = RandomManager.getRandom();
  for (int i = 0; i < 1000000; i++) {
    double d = r.nextDouble();
    Long key = (long) r.nextInt(100);
    if (d < 0.4) {
      assertEquals(expected.get(key), actual.get(key));
    } else {
      if (d < 0.7) {
        assertEquals(expected.put(key, "bang"), actual.put(key, "bang"));
      } else {
        assertEquals(expected.remove(key), actual.remove(key));
      }
      assertEquals(expected.size(), actual.size());
      assertEquals(expected.isEmpty(), actual.isEmpty());
    }
  }
}
 
Example 3
Source File: WelzlEncloser3DTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLargeSamples() throws IOException {
    RandomGenerator random = new Well1024a(0x35ddecfc78131e1dl);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(3, random);
    for (int k = 0; k < 50; ++k) {

        // define the reference sphere we want to compute
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector3D refCenter = new Vector3D(d, new Vector3D(sr.nextVector()));
        // set up a large sample inside the reference sphere
        int nbPoints = random.nextInt(1000);
        List<Vector3D> points = new ArrayList<Vector3D>();
        for (int i = 0; i < nbPoints; ++i) {
            double r = refRadius * random.nextDouble();
            points.add(new Vector3D(1.0, refCenter, r, new Vector3D(sr.nextVector())));
        }

        // test we find a sphere at most as large as the one used for random drawings
        checkSphere(points, refRadius);

    }
}
 
Example 4
Source File: FastIDSetTest.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersusHashSet() {
  FastIDSet actual = new FastIDSet(1);
  Collection<Integer> expected = new HashSet<Integer>(1000000);
  RandomGenerator r = RandomManager.getRandom();
  for (int i = 0; i < 1000000; i++) {
    double d = r.nextDouble();
    Integer key = r.nextInt(100);
    if (d < 0.4) {
      assertEquals(expected.contains(key), actual.contains(key));
    } else {
      if (d < 0.7) {
        assertEquals(expected.add(key), actual.add(key));
      } else {
        assertEquals(expected.remove(key), actual.remove(key));
      }
      assertEquals(expected.size(), actual.size());
      assertEquals(expected.isEmpty(), actual.isEmpty());
    }
  }
}
 
Example 5
Source File: WelzlEncloser3DTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLargeSamples() throws IOException {
    RandomGenerator random = new Well1024a(0x35ddecfc78131e1dl);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(3, random);
    for (int k = 0; k < 50; ++k) {

        // define the reference sphere we want to compute
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector3D refCenter = new Vector3D(d, new Vector3D(sr.nextVector()));
        // set up a large sample inside the reference sphere
        int nbPoints = random.nextInt(1000);
        List<Vector3D> points = new ArrayList<Vector3D>();
        for (int i = 0; i < nbPoints; ++i) {
            double r = refRadius * random.nextDouble();
            points.add(new Vector3D(1.0, refCenter, r, new Vector3D(sr.nextVector())));
        }

        // test we find a sphere at most as large as the one used for random drawings
        checkSphere(points, refRadius);

    }
}
 
Example 6
Source File: BitSetTest.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
@Test
public void testNextBitSetRandom() {
  RandomGenerator random = RandomManager.getRandom();
  for (int i = 0; i < 100; i++) {
    BitSet bitSet = new BitSet(NUM_BITS);
    for (int j = 0; j < 20 + random.nextInt(50); j++) {
      bitSet.set(random.nextInt(NUM_BITS));
    }
    int from = random.nextInt(NUM_BITS);
    int nextSet = bitSet.nextSetBit(from);
    if (nextSet == -1) {
      for (int j = from; j < NUM_BITS; j++) {
        assertFalse(bitSet.get(j));
      }
    } else {
      for (int j = from; j < nextSet; j++) {
        assertFalse(bitSet.get(j));
      }
      assertTrue(bitSet.get(nextSet));
    }
  }
}
 
Example 7
Source File: FenwickTreeTest.java    From fasten with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistr() {
	RandomGenerator random = new XoRoShiRo128PlusRandomGenerator(0);
	int n = 2 + random.nextInt(5);
	FenwickTree t = new FenwickTree(n);
	int[] increments = new int[n];
	int[] intended = new int[n];
	int total = 0;
	for (int i = 0; i < n; i++) {
		increments[i] = random.nextInt(10000) + 1;
		intended[i] = increments[i];
		total += increments[i];
	}
	for (int i = 0; i < total; i++) {
		int whichOne = random.nextInt(n);
		if (increments[whichOne] == 0) {
			i--;
			continue;
		}
		t.incrementCount(whichOne + 1);
		increments[whichOne]--;
	}

	for(int i = 1; i <= n; i++) assertEquals(i + "", intended[i - 1], t.getCount(i) - t.getCount(i - 1));
	// Now sample
	int[] sampled = new int[n];
	int sampleSize = 10000000;
	for (int i = 0; i < sampleSize; i++) {
		int sample = t.sample(random);
		sampled[sample - 1]++;
	}
	for (int i = 0; i < n; i++) 
		assertEquals((double)sampled[i] / sampleSize, (double)intended[i] / total, 1E-3);
}
 
Example 8
Source File: MinibatchSliceSampler.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * To efficiently sample without replacement with the possibility of early stopping when creating minibatches,
 * we lazily shuffle to avoid unnecessarily shuffling all data.  Uses the properties of relative primes and is
 * random enough for our purposes.  Adapted from https://stackoverflow.com/questions/16165128/lazy-shuffle-algorithms.
 */
private static <T> Iterator<T> lazyShuffleIterator(final RandomGenerator rng,
                                                   final List<T> data) {
    final int numDataPoints = data.size();

    //find first prime greater than or equal to numDataPoints
    final int nextPrime = Primes.nextPrime(numDataPoints);

    return new Iterator<T>() {
        int numSeen = 0;
        int index = rng.nextInt(numDataPoints) + 1;
        final int increment = index;

        public boolean hasNext() {
            return numSeen < data.size();
        }

        @Override
        public T next() {
            while (true) {
                index = (index + increment) % nextPrime;
                if (index < numDataPoints) {
                    numSeen++;
                    return data.get(index);
                }
            }
        }
    };
}
 
Example 9
Source File: RandomALSDataGenerator.java    From oryx with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
  String userString = ALSUtilsTest.idToStringID(random.nextInt(numUsers));
  String itemString = ALSUtilsTest.idToStringID(random.nextInt(numProducts));
  int rating = random.nextInt(maxRating - minRating + 1) + minRating;
  String datum = userString + ',' +  itemString + ',' + rating + ',' + System.currentTimeMillis();
  return new Pair<>(Integer.toString(id), datum);
}
 
Example 10
Source File: FastByIDFloatMapTest.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
@Test
public void testVersusHashMap() {
  FastByIDFloatMap actual = new FastByIDFloatMap();
  Map<Long,Float> expected = Maps.newHashMapWithExpectedSize(1000000);
  RandomGenerator r = RandomManager.getRandom();
  for (int i = 0; i < 1000000; i++) {
    double d = r.nextDouble();
    Long key = (long) r.nextInt(100);
    if (d < 0.4) {
      Number expectedValue = expected.get(key);
      float actualValue = actual.get(key);
      if (expectedValue == null) {
        assertNaN(actualValue);
      } else {
        assertEquals(expectedValue.floatValue(), actualValue);
      }
    } else {
      if (d < 0.7) {
        expected.put(key, 3.0f);
        actual.put(key, 3.0f);
      } else {
        expected.remove(key);
        actual.remove(key);
      }
      assertEquals(expected.size(), actual.size());
      assertEquals(expected.isEmpty(), actual.isEmpty());
    }
  }
}
 
Example 11
Source File: WelzlEncloser2DTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testLargeSamples() {
    RandomGenerator random = new Well1024a(0xa2a63cad12c01fb2l);
    for (int k = 0; k < 100; ++k) {
        int nbPoints = random.nextInt(10000);
        List<Vector2D> points = new ArrayList<Vector2D>();
        for (int i = 0; i < nbPoints; ++i) {
            double x = random.nextDouble();
            double y = random.nextDouble();
            points.add(new Vector2D(x, y));
        }
        checkDisk(points);
    }
}
 
Example 12
Source File: FeaturesALSDataGenerator.java    From oryx with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
  int user = random.nextInt(numUsers);
  int randProduct = random.nextInt(numProducts);
  // Want product === user mod features
  int product = ((user % features) + (randProduct / features) * features) % numProducts;
  String datum = ALSUtilsTest.idToStringID(user) + ',' + ALSUtilsTest.idToStringID(product) +
      ",1," + System.currentTimeMillis();
  return new Pair<>(Integer.toString(id), datum);
}
 
Example 13
Source File: CopyRatioSegmenterUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<SimpleInterval> randomPositions(final String contig, final int chainLength, final RandomGenerator rng, final double separationScale) {
    final List<SimpleInterval> positions = new ArrayList<>();
    int position = 1;
    for (int n = 0; n < chainLength; n++) {
        position += rng.nextInt((int) separationScale);
        final SimpleInterval interval = new SimpleInterval(contig, position, position);
        positions.add(interval);
    }
    return positions;
}
 
Example 14
Source File: NPointCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 * @throws NumberIsTooLargeException if the number of crossoverPoints is too large for the
 * actual chromosomes
 */
private ChromosomePair mate(final AbstractListChromosome<T> first,
                            final AbstractListChromosome<T> second) {
    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }
    if (crossoverPoints >= length) {
        throw new NumberIsTooLargeException(crossoverPoints, length, false);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final ArrayList<T> child1Rep = new ArrayList<T>(first.getLength());
    final ArrayList<T> child2Rep = new ArrayList<T>(second.getLength());

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();

    ArrayList<T> c1 = child1Rep;
    ArrayList<T> c2 = child2Rep;

    int remainingPoints = crossoverPoints;
    int lastIndex = 0;
    for (int i = 0; i < crossoverPoints; i++, remainingPoints--) {
        // select the next crossover point at random
        final int crossoverIndex = 1 + lastIndex + random.nextInt(length - lastIndex - remainingPoints);

        // copy the current segment
        for (int j = lastIndex; j < crossoverIndex; j++) {
            c1.add(parent1Rep.get(j));
            c2.add(parent2Rep.get(j));
        }

        // swap the children for the next segment
        ArrayList<T> tmp = c1;
        c1 = c2;
        c2 = tmp;

        lastIndex = crossoverIndex;
    }

    // copy the last segment
    for (int j = lastIndex; j < length; j++) {
        c1.add(parent1Rep.get(j));
        c2.add(parent2Rep.get(j));
    }

    return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
                              second.newFixedLengthChromosome(child2Rep));
}
 
Example 15
Source File: OrderedCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 16
Source File: NPointCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 * @throws NumberIsTooLargeException if the number of crossoverPoints is too large for the actual chromosomes
 */
private ChromosomePair mate(final AbstractListChromosome<T> first,
                            final AbstractListChromosome<T> second)
    throws DimensionMismatchException, NumberIsTooLargeException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }
    if (crossoverPoints >= length) {
        throw new NumberIsTooLargeException(crossoverPoints, length, false);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final ArrayList<T> child1Rep = new ArrayList<T>(first.getLength());
    final ArrayList<T> child2Rep = new ArrayList<T>(second.getLength());

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();

    ArrayList<T> c1 = child1Rep;
    ArrayList<T> c2 = child2Rep;

    int remainingPoints = crossoverPoints;
    int lastIndex = 0;
    for (int i = 0; i < crossoverPoints; i++, remainingPoints--) {
        // select the next crossover point at random
        final int crossoverIndex = 1 + lastIndex + random.nextInt(length - lastIndex - remainingPoints);

        // copy the current segment
        for (int j = lastIndex; j < crossoverIndex; j++) {
            c1.add(parent1Rep.get(j));
            c2.add(parent2Rep.get(j));
        }

        // swap the children for the next segment
        ArrayList<T> tmp = c1;
        c1 = c2;
        c2 = tmp;

        lastIndex = crossoverIndex;
    }

    // copy the last segment
    for (int j = lastIndex; j < length; j++) {
        c1.add(parent1Rep.get(j));
        c2.add(parent2Rep.get(j));
    }

    return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
                              second.newFixedLengthChromosome(child2Rep));
}
 
Example 17
Source File: OrderedCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 18
Source File: OrderedCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 19
Source File: OrderedCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 20
Source File: NPointCrossover.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 * @throws NumberIsTooLargeException if the number of crossoverPoints is too large for the actual chromosomes
 */
private ChromosomePair mate(final AbstractListChromosome<T> first,
                            final AbstractListChromosome<T> second)
    throws DimensionMismatchException, NumberIsTooLargeException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }
    if (crossoverPoints >= length) {
        throw new NumberIsTooLargeException(crossoverPoints, length, false);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1Rep = new ArrayList<T>(length);
    final List<T> child2Rep = new ArrayList<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();

    List<T> c1 = child1Rep;
    List<T> c2 = child2Rep;

    int remainingPoints = crossoverPoints;
    int lastIndex = 0;
    for (int i = 0; i < crossoverPoints; i++, remainingPoints--) {
        // select the next crossover point at random
        final int crossoverIndex = 1 + lastIndex + random.nextInt(length - lastIndex - remainingPoints);

        // copy the current segment
        for (int j = lastIndex; j < crossoverIndex; j++) {
            c1.add(parent1Rep.get(j));
            c2.add(parent2Rep.get(j));
        }

        // swap the children for the next segment
        List<T> tmp = c1;
        c1 = c2;
        c2 = tmp;

        lastIndex = crossoverIndex;
    }

    // copy the last segment
    for (int j = lastIndex; j < length; j++) {
        c1.add(parent1Rep.get(j));
        c2.add(parent2Rep.get(j));
    }

    return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
                              second.newFixedLengthChromosome(child2Rep));
}