Example usage for org.apache.commons.math3.genetics FixedGenerationCount FixedGenerationCount

List of usage examples for org.apache.commons.math3.genetics FixedGenerationCount FixedGenerationCount

Introduction

In this page you can find the example usage for org.apache.commons.math3.genetics FixedGenerationCount FixedGenerationCount.

Prototype

public FixedGenerationCount(final int maxGenerations) throws NumberIsTooSmallException 

Source Link

Document

Create a new FixedGenerationCount instance.

Usage

From source file:it.units.malelab.sse.Main.java

public static void main(String[] args) throws IOException {
    Random random = new Random(1);
    VirtualMachine vm = new VirtualMachine(4, 4, 400);
    List<Map<Boolean, List<String>>> datasets = new ArrayList<>();
    datasets.add(Util.loadStrings("/home/eric/Documenti/esperimenti/datasets/Bills-Date.txt", random));
    datasets.add(Util.loadStrings("/home/eric/Documenti/esperimenti/datasets/Log-IP.txt", random));
    datasets.add(Util.loadStrings("/home/eric/Documenti/esperimenti/datasets/Twitter-URL.txt", random));

    Evaluator evaluator = new Evaluator(vm, datasets, 1, 10);

    MyGeneticAlgorithm ga = new MyGeneticAlgorithm(new OnePointCrossover<Integer>(), 0.2, new BinaryMutation(),
            0.6, new TournamentSelection(10), evaluator);
    MyGeneticAlgorithm.setRandomGenerator(new JDKRandomGenerator(1));

    List<Chromosome> chromosomes = new ArrayList<>();
    for (int i = 0; i < 2000; i++) {
        chromosomes.add(new OperationsChromosome(evaluator));
    }//www.j  a va  2s .  c o  m
    Population population = new ElitisticListPopulation(chromosomes, chromosomes.size(), 0.99);
    Population finalPopulation = ga.evolve(population, new FixedGenerationCount(10000));
    List<Operation> operations = ((OperationsChromosome) finalPopulation.getFittestChromosome())
            .getOperations();
    for (int i = 0; i < operations.size(); i++) {
        System.out.printf("%4d: %s\n", i, operations.get(i));
    }

}

From source file:eu.tsp.sal.WSN.java

/**
 * Algorithm run on a number of sensors = LENGTH
 * //from  w  w w  .  ja  v  a 2 s. c o m
 * Population has POPULATION_SIZE individuals (SensorIndividual class)
 * each individual has LENGTH genes (~ sensor)
 * 
 *  
 * 
 */

public static void main(String[] args) {
    /**
     *  initialize a new genetic algorithm with
     *      Crossover policy
     *      CROSSOVER_RATE
     *      Mutation policy
     *      MUTATION_RATE
     *      Selection Policy 
     *      
     */

    SensorGeneticAlgorithm ga = new SensorGeneticAlgorithm(new NPointCrossover(2), CROSSOVER_RATE, // all selected chromosomes will be recombined (=crosssover)
            new SensorMutation(), MUTATION_RATE, new SensorTournamentSelection(TOURNAMENT_ARITY));

    //assertEquals(0, ga.getGenerationsEvolved());
    //System.out.println(ga.getGenerationsEvolved());

    // initial population of POPULATION_SIZE SensorIndividual
    //Population initial = randomPopulation(LENGTH, POPULATION_SIZE);
    Population initial = randomPopulationWithFixedOA(OA_NUMBER, LENGTH, POPULATION_SIZE);

    printPopulation(initial);

    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);

    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();
    System.out.println("Best Individual in initial population (highest fitness) = " + bestInitial);
    System.out.println("Solution  of the best individual = " + ((SensorIndividual) bestInitial).solution());

    // run the algorithm
    Population finalPopulation = ga.evolve(initial, stopCond);

    // best SensorIndividual from the final population
    Chromosome bestFinal = finalPopulation.getFittestChromosome();
    System.out.println("\nBest Individual in final population (highest fitness) = " + bestFinal);
    //System.out.println("Solution of the best individual = " + ((SensorIndividual) bestFinal).solution());
    printSolution((SensorIndividual) bestFinal);

    // Assertion

    // assertTrue(bestFinal.compareTo(bestInitial) > 0);
    // assertEquals(NUM_GENERATIONS, ga.getGenerationsEvolved());
    System.out.println((bestFinal.compareTo(bestInitial) > 0) ? "Final generation is better than the initial"
            : "Final generation is worse than the initial!!!!");
    //System.out.println(ga.getGenerationsEvolved());
}

From source file:ga.GeneticAlgorithmTestBinary.java

@Test
public void test() {
    // to test a stochastic algorithm is hard, so this will rather be an usage example

    // initialize a new genetic algorithm
    GeneticAlgorithm ga = new StatisticGeneticAlgorithm(new OnePointCrossover<Integer>(), CROSSOVER_RATE, // all selected chromosomes will be recombined (=crosssover)
            new BinaryMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    Assert.assertEquals(0, ga.getGenerationsEvolved());

    // initial population
    Population initial = randomPopulation();
    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);

    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();

    // run the algorithm
    Population finalPopulation = ga.evolve(initial, stopCond);

    // best chromosome from the final population
    Chromosome bestFinal = finalPopulation.getFittestChromosome();

    // the only thing we can test is whether the final solution is not worse than the initial
    // one/*from w ww  .  j a  v  a 2 s  .c  o m*/
    // however, for some implementations of GA, this need not be true :)

    Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0);
    Assert.assertEquals(NUM_GENERATIONS, ga.getGenerationsEvolved());
    System.out.println(bestFinal);

}

From source file:org.apache.kylin.cube.cuboid.algorithm.generic.GeneticAlgorithm.java

@Override
public List<Long> start(double maxSpaceLimit) {
    logger.debug("Genetic Algorithm started.");

    //Initial mandatory cuboids
    double remainingSpace = maxSpaceLimit;
    for (Long mandatoryOne : cuboidStats.getAllCuboidsForMandatory()) {
        if (cuboidStats.getCuboidSize(mandatoryOne) != null) {
            remainingSpace -= cuboidStats.getCuboidSize(mandatoryOne);
        }/*from w  ww. j a  v  a 2s  . co m*/
    }

    BitsChromosomeHelper helper = new BitsChromosomeHelper(remainingSpace, cuboidStats);

    //Generate a population randomly
    Population initial = initRandomPopulation(helper);

    //Set stopping condition
    List<StoppingCondition> conditions = Lists.newArrayList();
    conditions.add(new FixedGenerationCount(550));
    CombinedStoppingCondition stopCondition = new CombinedStoppingCondition(conditions);

    //Start the evolution
    Population current = geneticAlgorithm.evolve(initial, stopCondition);
    BitsChromosome chromosome = (BitsChromosome) current.getFittestChromosome();
    logger.debug("Genetic Algorithm finished.");
    List<Long> finalList = Lists.newArrayList();
    finalList.addAll(helper.getMandatoryCuboids());
    finalList.addAll(chromosome.getCuboids());

    double totalSpace = 0;
    if (logger.isTraceEnabled()) {
        for (Long cuboid : finalList) {
            Double unitSpace = cuboidStats.getCuboidSize(cuboid);
            if (unitSpace != null) {
                logger.trace(String.format(Locale.ROOT, "cuboidId %d and Space: %f", cuboid, unitSpace));
                totalSpace += unitSpace;
            } else {
                logger.trace(String.format(Locale.ROOT, "mandatory cuboidId %d", cuboid));
            }
        }
        logger.trace("Total Space:" + totalSpace);
        logger.trace("Space Expansion Rate:" + totalSpace / cuboidStats.getBaseCuboidSize());
    }
    return finalList;
}

From source file:p.lodz.playground.ApacheGeneticsTest.java

@Test
public void test() {
    // to test a stochastic algorithm is hard, so this will rather be an
    // usage example

    // initialize a new genetic algorithm
    GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover<Integer>(), CROSSOVER_RATE, // all
            // selected
            // chromosomes
            // will be
            // recombined
            // (=crosssover)
            new BinaryMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    Assert.assertEquals(0, ga.getGenerationsEvolved());

    // initial population
    Population initial = randomPopulation();
    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);

    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();

    // run the algorithm
    Population finalPopulation = ga.evolve(initial, stopCond);

    // best chromosome from the final population
    Chromosome bestFinal = finalPopulation.getFittestChromosome();

    // the only thing we can test is whether the final solution is not worse
    // than the initial one
    // however, for some implementations of GA, this need not be true :)

    Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0);
    Assert.assertEquals(NUM_GENERATIONS, ga.getGenerationsEvolved());

    System.out.println(bestFinal);
}

From source file:tmp.GACombGraphMoore.java

public static void main(String... args) {
    // to test a stochastic algorithm is hard, so this will rather be an usage example

    // initialize a new genetic algorithm   
    GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover<Integer>(), CROSSOVER_RATE,
            new RandomKeyMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    // initial population
    Population initial = randomPopulation(args);

    System.out.println("Initial population:");
    System.out.println(initial.getFittestChromosome());
    long lastime = System.currentTimeMillis();

    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);
    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();

    // run the algorithm
    //        Population finalPopulation = ga.evolve(initial, stopCond);
    double bestfit = initial.getFittestChromosome().fitness();
    Population current = initial;/* w  w  w. j av a2s . co m*/
    int generationsEvolved = 0;
    //        while (!stopCond.isSatisfied(current)) {
    while (bestfit != 0.0) {
        current = ga.nextGeneration(current);
        generationsEvolved++;
        Chromosome bestFinal = current.getFittestChromosome();
        //            System.out.print(bestFinal);
        double atualfit = bestFinal.getFitness();
        if (atualfit > bestfit || System.currentTimeMillis() - lastime > HOUR) {
            bestfit = atualfit;
            //                String strbest = generationsEvolved + "-f=" + atualfit + "-" + ((MinPermutations) bestFinal).decode(sequence).toString().replaceAll(" ", "") + "\n";
            String strbest = generationsEvolved + "-f=" + atualfit;
            //                UtilTmp.dumpString(strbest);
            System.out.println(strbest);
            //                strbest = bestFinal.toString();
            //                UtilTmp.dumpString(strbest);
            System.out.println(strbest);
            //                System.out.println();
            lastime = System.currentTimeMillis();
        }
    }

    // best chromosome from the final population
    Chromosome bestFinal = current.getFittestChromosome();
    System.out.println("Best initial:");
    System.out.println(bestInitial);
    System.out.println(((MinPermutations) bestInitial).decode(sequence));
    System.out.println("Best result:");
    System.out.println(bestFinal);
    System.out.println(((MinPermutations) bestFinal).decode(sequence));

    // the only thing we can test is whether the final solution is not worse than the initial one
    // however, for some implementations of GA, this need not be true :)
    //        Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0);
    //System.out.println(bestInitial);
    //System.out.println(bestFinal);
}

From source file:tmp.GACombPermutation.java

public static void main(String... args) {
    // to test a stochastic algorithm is hard, so this will rather be an usage example

    // initialize a new genetic algorithm
    GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover<Integer>(), CROSSOVER_RATE,
            new RandomKeyMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    // initial population
    Population initial = randomPopulation(args);
    System.out.print("Graph e-");
    System.out.print(graph.getEdgeCount());
    System.out.print(" Subgraph e-");
    System.out.println(subgraph.getEdgeCount());

    System.out.println("Initial population:");
    System.out.println(initial.getFittestChromosome());
    long lastime = System.currentTimeMillis();

    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);

    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();

    // run the algorithm
    //        Population finalPopulation = ga.evolve(initial, stopCond);
    double bestfit = initial.getFittestChromosome().fitness();
    Population current = initial;// w  w w .j a v a 2s .com
    int generationsEvolved = 0;
    //        while (!stopCond.isSatisfied(current)) {
    while (bestfit != 0.0) {
        current = ga.nextGeneration(current);
        generationsEvolved++;
        Chromosome bestFinal = current.getFittestChromosome();
        //            System.out.print(bestFinal);
        double atualfit = bestFinal.getFitness();
        if (atualfit > bestfit || System.currentTimeMillis() - lastime > UtilTmp.ALERT_HOUR) {
            lastime = System.currentTimeMillis();
            System.out.print(generationsEvolved);
            System.out.print("-");
            bestfit = atualfit;
            String strbest = bestFinal.toString() + "\n";
            UtilTmp.dumpString(strbest);
            System.out.print(strbest);
            System.out.println();
        }
    }

    // best chromosome from the final population
    Chromosome bestFinal = current.getFittestChromosome();
    System.out.println("Best result:");
    System.out.println(bestFinal);

    // the only thing we can test is whether the final solution is not worse than the initial one
    // however, for some implementations of GA, this need not be true :)
    //        Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0);
    //System.out.println(bestInitial);
    //System.out.println(bestFinal);
}

From source file:tmp.GeneticAlgorithmTestPermutations.java

@Test
public void test() {
    // to test a stochastic algorithm is hard, so this will rather be an usage example

    // initialize a new genetic algorithm
    GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover<Integer>(), CROSSOVER_RATE,
            new RandomKeyMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    // initial population
    Population initial = randomPopulation();
    System.out.print("Initial population");
    System.out.println(initial.getFittestChromosome());

    // stopping conditions
    StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);

    // best initial chromosome
    Chromosome bestInitial = initial.getFittestChromosome();

    // run the algorithm
    Population finalPopulation = ga.evolve(initial, stopCond);

    // best chromosome from the final population
    Chromosome bestFinal = finalPopulation.getFittestChromosome();
    System.out.print("Best result: ");
    System.out.println(bestFinal);

    // the only thing we can test is whether the final solution is not worse than the initial one
    // however, for some implementations of GA, this need not be true :)
    Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0);

    //System.out.println(bestInitial);
    //System.out.println(bestFinal);
}