예제 #1
0
 public LocalityTest(GrammaticalEvolution ge1, GrammaticalEvolution ge2, FitnessCalculator calculator, ExecutionParameters parameters)
 {
     GE1        = ge1;
     GE2        = ge2;
     Calculator = calculator;
     Parameters = parameters;
 }
예제 #2
0
        private void Evaluate(Generation generation)
        {
            foreach (Chromosome chromosome in generation)
            {
                if (chromosome.Fitness.HasValue && !chromosome.ReEvaluate)
                {
                    continue;
                }
                generation.Stats.executedEvaluations++;
                chromosome.ReEvaluate = false;

                GrammaticalEvolution newGE                = GE.GetClone();
                string    code                            = null;
                object    result                          = null;
                Exception generationException             = null;
                CompilerErrorCollection compilationErrors = null;
                Exception executionException              = null;

                try
                {
                    code = newGE.Generate(chromosome, generation.Stats);
                }
                catch (GrammaticalEvolution.ErrorCorrectionFailedException e)
                {
                    generationException = e;
                    generation.Stats.generationErrors++;
                }
                catch (GrammaticalEvolution.EndOfCodonQueueException e)
                {
                    generationException = e;
                    generation.Stats.generationErrors++;
                }

                if (generationException == null)
                {
                    try
                    {
                        result = Execute(code);
                    }
                    catch (Executor.CompilationErrorException e)
                    {
                        compilationErrors = e.Errors;
                        generation.Stats.compilationErrors++;
                    }
                    catch (Executor.ExecutionExceptionException e)
                    {
                        executionException = e.InnerException;
                        generation.Stats.executionExceptions++;
                    }
                }
                chromosome.Fitness = _FitnessCalculator(result, generationException, compilationErrors, executionException);

                if (generationException == null && compilationErrors == null && executionException == null)
                {
                    chromosome.BackupCodons = chromosome.ToList();//If the compilation was successful the codons are copied to the backupCodons
                }
            }
        }
예제 #3
0
 public GeneticAlgorithm(int elitismSize, GrammaticalEvolution ge, FitnessCalculator fitnessCalculator, Selection selection, Crossover crossover, Mutation mutation, Population population, ExecutionParameters parameters)
 {
     ElitismSize        = elitismSize;
     GE                 = ge;
     _FitnessCalculator = fitnessCalculator;
     Selection          = selection;
     Crossover          = crossover;
     Mutation           = mutation;
     Population         = population;
     Parameters         = parameters;
 }
예제 #4
0
        public Tuple <List <double>, List <double> > ExecuteTest(int testnumber, int testSize, int mutatedIndividuals, int initialChromosomeSize, double failureFitnessValue, bool useGE1ForBase, bool includeFailedCorrections)
        {
            List <double> localityResults1 = new List <double>();
            List <double> localityResults2 = new List <double>();

            for (int i = 0; i < testSize; i++)
            {
                Chromosome baseChromosome = null;
                double     baseFitness    = failureFitnessValue;
                while (baseFitness == failureFitnessValue)//Check that it is a correct individual
                {
                    baseChromosome = new Chromosome(initialChromosomeSize, 64);
                    GrammaticalEvolution baseGE = (useGE1ForBase ? GE1 : GE2).GetClone();
                    baseFitness = Evaluate(baseChromosome, true, baseGE).Item1;
                }
                for (int j = 0; j < mutatedIndividuals; j++)//TODO: Perché le differenze del 2 è di 1?.
                {
                    Chromosome mutatedChromosome1 = SingleMutation(baseChromosome);
                    mutatedChromosome1.BackupCodons = baseChromosome.ToList();
                    Chromosome mutatedChromosome2 = mutatedChromosome1.GetClone();

                    Tuple <double, bool> result1 = Evaluate(mutatedChromosome1, false, GE1);
                    Tuple <double, bool> result2 = Evaluate(mutatedChromosome2, false, GE2);
                    double minDistance           = (double)1 / 64;

                    localityResults1.Add(Math.Abs(result1.Item1 - baseFitness - minDistance));

                    double secondResult = result2.Item2 ? baseFitness : result2.Item1;
                    localityResults2.Add(Math.Abs(secondResult - baseFitness - minDistance));
                }
                Console.WriteLine(i + " out of " + testSize);
            }
            Console.WriteLine("Media 1:" + localityResults1.Average());
            Console.WriteLine("Media 2:" + localityResults2.Average());
            Console.WriteLine("Miglioramento:" + ((localityResults1.Average() - localityResults2.Average()) / localityResults1.Average()));
            return(new Tuple <List <double>, List <double> >(localityResults1, localityResults2));

            /*string percorso = @"C:\Users\Samuele\Documents\BetterPECLE\v3\Studio località\";
             * //string avviso = "ATTENZIONE: QUESTI RISULTATI SONO STATI DEFINITI PREVENTIVAMENTE COME TEST.\n" +
             * //    "AL FINE DI RISPETTARE L'ETICA SCIENTIFICA, NON USARE QUESTI DATI IN NESSUNA PUBBLICAZIONE.\n\n";
             *
             * double miglioramento = ((localityResults1.Average() - localityResults2.Average()) / localityResults1.Average());
             *
             * string spiegazione = "I seguenti dati indicano la differenza di fitness medio per mutazione. Più la differenza\n" +
             *  "è bassa, più la rappresentazione è locale.\n\n";
             * File.WriteAllText(percorso + "Studio" + testnumber + ".txt",
             *  spiegazione + "Media default: " + localityResults1.Average() +
             *  "\nDeviazione Standard: " + StdDev(localityResults1) +
             *  "\nMedia PECLE: " + localityResults2.Average() +
             *  "\nDeviazione Standard: " + StdDev(localityResults2) +
             *  "\nMiglioramento: " + miglioramento);*/
        }
예제 #5
0
        private static GeneticAlgorithmResult PECLETest_NoImprovements(int populationSize, int generationNumber, int initialChromosomeSize, int maximumChromosomeSize, int elitismSize, int tournamentSize, double crossoverProbability, double mutationProbability, double duplicationProbability, double pruningProbability)
        {
            GrammaticalEvolution ge = new GrammaticalEvolution();

            ge.BluePrintGOs = new List <GrammaticalObject>()
            {
                new OneMaxGO_NoImprovements()
            };
            ge.StartingGO             = new OneMaxGO_NoImprovements();
            ge.StartingProductionRule = new ProductionRule(new NonTerminal("code"));

            GeneticAlgorithm ga = new GeneticAlgorithm(elitismSize, ge, Calculator, new TournamentSelection(tournamentSize, false), new OnePointCrossover(), new UniformMutation(), new Population(populationSize, initialChromosomeSize, maximumChromosomeSize), new ExecutionParameters("namespace A{ public class B{ public bool[] C() { \nbool[] grid = new bool[64];\n int a = 0;\n int b = 0;\n int c = 0;\n PECLECODE\n return grid;}}}", "A.B", "C"));

            return(ga.Evolve(generationNumber, crossoverProbability, mutationProbability, duplicationProbability, pruningProbability));
        }
예제 #6
0
        private Tuple <double, bool> Evaluate(Chromosome chromosome, bool saveBackupCodons, GrammaticalEvolution ge)
        {
            GrammaticalEvolution newGE                = ge.GetClone();
            string    code                            = null;
            object    result                          = null;
            Exception generationException             = null;
            CompilerErrorCollection compilationErrors = null;
            Exception       executionException        = null;
            GenerationStats s                         = new GenerationStats();

            try
            {
                code = newGE.Generate(chromosome, s);
            }
            catch (GrammaticalEvolution.ErrorCorrectionFailedException e)
            {
                generationException = e;
            }
            catch (GrammaticalEvolution.EndOfCodonQueueException e)
            {
                generationException = e;
            }
            if (generationException == null)
            {
                try
                {
                    result = Executor.Execute(Parameters, code);
                }
                catch (Executor.CompilationErrorException e)
                {
                    compilationErrors = e.Errors;
                }
                catch (Executor.ExecutionExceptionException e)
                {
                    executionException = e.InnerException;
                }
            }

            if (generationException == null && compilationErrors == null && executionException == null && saveBackupCodons)
            {
                chromosome.BackupCodons = chromosome.ToList();
            }

            return(new Tuple <double, bool>(Calculator(result, generationException, compilationErrors, executionException), s.failedErrorCorrections > 0));
        }
예제 #7
0
        public GrammaticalEvolution GetClone()
        {
            GrammaticalEvolution ge = new GrammaticalEvolution();

            if (BluePrintGOs != null)
            {
                ge.BluePrintGOs = new List <GrammaticalObject>();
                foreach (GrammaticalObject go in BluePrintGOs)
                {
                    ge.BluePrintGOs.Add(go.GetClone());
                }
            }
            ge.codonPosition           = codonPosition;
            ge.StartingGO              = StartingGO == null ? null : StartingGO.GetClone();
            ge.StartingProductionRule  = StartingProductionRule == null ? null : new ProductionRule(StartingProductionRule.ToArray());
            ge._currentGenerationStats = _currentGenerationStats == null ? null : _currentGenerationStats.GetClone();
            ge._genome = _genome == null ? null : _genome.GetClone();
            return(ge);
        }