Exemple #1
0
        protected void noClonesAroundTest(IPopulation population)
        {
            foreach (IEvolvable evolvable in population.Individuals)
            {
                Assert.IsNotNull(evolvable);
            }

            for (int i = 0; i < population.Individuals.Count - 1; i++)
            {
                for (int j = i + 1; j < population.Individuals.Count; j++)
                {
                    if (population.Individuals[i].Equals(population.Individuals[j]))
                    {
                        throw new Exception("Clones!! " + i + " and " + j);
                    }
                }
            }

            foreach (var individual in population.Individuals)
            {
                if (individual is IPopulation)
                {
                    noClonesAroundTest(individual as IPopulation);
                }
            }
        }
Exemple #2
0
        public IList <IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList <IChromosome> parents)
        {
            var minSize   = population.MinSize;
            var offspring = new List <IChromosome>(minSize);

            for (int i = 0; i < minSize; i += crossover.ParentsNumber)
            {
                var selectedParents = parents.Skip(i).Take(crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= crossoverProbability)
                {
                    offspring.AddRange(crossover.Cross(selectedParents));
                }
                else
                {
                    var left = crossover.ParentsNumber - selectedParents.Count;
                    for (int j = 0; j < left; j++)
                    {
                        offspring.Add(parents[RandomizationProvider.Current.GetInt(0, parents.Count)].Clone());
                    }
                }
            }

            return(offspring);
        }
        public void InitGA()
        {
            System.Random rand;

            rand = (seedRandom) ? new System.Random(1) : new System.Random();
            var randGenomGenerator = new RandNeuralGenomeGeneratorBase(
                rand,
                new Sigmoid(),
                weightRange,
                inputCount,
                outputCount,
                hiddenLayers,
                createBias);

            var reinsertion = new ReinsertBest <Synapse>(
                (int)(poplLne * reinsertPart));
            var breeding            = NewBreeding(rand);
            var generationGenerator = new GenerationGeneratorBase <Synapse>(
                poplLne,
                reinsertion,
                breeding);

            population = new PopulationBase <Synapse>(
                poplLne,
                randGenomGenerator,
                generationGenerator);
        }
        public IPopulation EvolvePopulation(IPopulation oldPopulation)
        {
            var newPopulation = _populationFactory.CreatePopulation(oldPopulation.Size);

            var individualIndexOffset = 0;

            if (_elitism)
            {
                newPopulation.SetIndividual(0, oldPopulation.MostSuitableIndividualToProblem);
                individualIndexOffset = 1;
            }

            // Populate 'newPopulation' with children from the parents in 'oldPopulation' to exploit the current knowledge.
            for (var individualIndex = individualIndexOffset; individualIndex < newPopulation.Size; individualIndex++)
            {
                var resultingIndividualFromCrossoverOperation =
                    _crossoverOperator.PerformCrossover(oldPopulation);

                _problemService.MakeSolutionValid(resultingIndividualFromCrossoverOperation);

                newPopulation.SetIndividual(individualIndex, resultingIndividualFromCrossoverOperation);
            }

            // Mutate each individual in the new population to explore the problem domain.
            for (var individualIndex = individualIndexOffset; individualIndex < oldPopulation.Size; individualIndex++)
            {
                // TODO: Refactor the 'currentIndividual.Chromosome' - shouldn't be able to view Chromosome.
                var currentIndividual = newPopulation.GetIndividual(individualIndex);
                _mutationOperator.PerformMutation(currentIndividual);
            }

            return(newPopulation);
        }
        /// <summary>
        /// Construct an innovation list.
        /// </summary>
        ///
        /// <param name="population_0">The population.</param>
        /// <param name="links">The links.</param>
        /// <param name="neurons">THe neurons.</param>
        public NEATInnovationList(IPopulation population_0,
                                  Chromosome links, Chromosome neurons)
        {
            nextNeuronID = 0;
            population   = population_0;

            foreach (IGene gene  in  neurons.Genes)
            {
                var neuronGene = (NEATNeuronGene)gene;

                var innovation = new NEATInnovation(neuronGene,
                                                    population_0.AssignInnovationID(), AssignNeuronID());
                Add(innovation);
            }


            foreach (IGene gene_1  in  links.Genes)
            {
                var linkGene     = (NEATLinkGene)gene_1;
                var innovation_2 = new NEATInnovation(
                    linkGene.FromNeuronID, linkGene.ToNeuronID,
                    NEATInnovationType.NewLink,
                    population.AssignInnovationID());
                Add(innovation_2);
            }
        }
Exemple #6
0
        public Generation(IPopulation population)
        {
            Population = population;

            // Perform initial speciation
            Population.Speciate();
        }
Exemple #7
0
        /// <summary>
        /// Evolved one generation.
        /// </summary>
        /// <param name="population">Curr. pop</param>
        /// <returns>New generation</returns>
        protected override IPopulation EvolvedOneGeneration(IPopulation population)
        {
            List <IIndividual> newGeneration = new List <IIndividual>();

            foreach (var orginal in population.Individuals)
            {
                // generate unique random numbers
                var randomValues = FastRandom.GetUniqueInts(3, 0, population.Size);
                int a            = randomValues[0];
                int b            = randomValues[1];
                int c            = randomValues[2];

                // choose random individuals (agents) from population
                IIndividual individual1 = population.Individuals[a];
                IIndividual individual2 = population.Individuals[b];
                IIndividual individual3 = population.Individuals[c];

                int i = 0;


                int R = FastRandom.GetInt(0, population.Size);

                var candidate = population.CreateEmptyIndividual();
                foreach (var orginalElement in orginal.GetGenes())
                {
                    double probXover = FastRandom.GetDouble();

                    if (probXover < XoverProbability || i == R)
                    {
                        // simple mutation
                        double newElement = individual1.GetGene(i) + F * (individual2.GetGene(i) - individual3.GetGene(i));
                        candidate.ReplaceGene(i, newElement);
                    }
                    else
                    {
                        candidate.ReplaceGene(i, orginalElement);
                    }

                    i++;
                }


                var fit = fitness.Evaluate(candidate);

                if (fit < orginal.Fitness)
                {
                    newGeneration.Add(candidate);
                }
                else
                {
                    newGeneration.Add(orginal);
                }
            }

            CurrentGenerationsNumber++;

            population.Individuals = newGeneration;

            return(population);
        }
        public IList <IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList <IChromosome> parents)
        {
            var offspring     = new List <IChromosome>();
            var clonedParents = parents.Select(x => x.Clone()).ToList();

            for (int i = 0; i < population.MaxSize; i += crossover.ParentsNumber)
            {
                var selectedParents = clonedParents.Skip(i).Take(crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == crossover.ParentsNumber)
                {
                    bool shouldCrossover = RandomizationProvider.Current.GetDouble() <= crossoverProbability;

                    offspring.AddRange(shouldCrossover ?
                                       crossover.Cross(selectedParents) : selectedParents);
                }
                else
                {
                    offspring.AddRange(selectedParents);

                    int leftToAdd = crossover.ParentsNumber - selectedParents.Count;
                    for (int j = 0; j < leftToAdd; j++)
                    {
                        offspring.Add(clonedParents[RandomizationProvider.Current.GetInt(0, clonedParents.Count)].Clone());
                    }
                }
            }

            return(offspring);
        }
        public override bool TravelerReceptionDecision(IPopulation population)
        {
            var receptionRate     = Parameters.GetValue(ParameterNames.MigrationReceptionRate);
            var receptionDecision = Random.GetDouble(0, 1) < receptionRate;

            return(receptionDecision);
        }
Exemple #10
0
        protected virtual void basicTest(IPopulation population)
        {
            Assert.AreEqual(population.Fitness, population.Best.Fitness);

            AssertEx.IsGreaterThanOrEqualTo(population.Individuals.Count, 1);
            AssertEx.IsGreaterThanOrEqualTo(population.FoodConsumedInLifetime, 1);
            AssertEx.IsGreaterThanOrEqualTo(population.FitnessEvaluations, 1);

            AssertEx.IsGreaterThanOrEqualTo(population.Generations, 1);
            AssertEx.IsGreaterThanOrEqualTo(population.Mutations, 1);
            AssertEx.IsGreaterThanOrEqualTo(population.Crossovers, 1);

            Assert.IsNotInstanceOfType(population.BestOfAllTime, typeof(IPopulation));
            Assert.IsNotInstanceOfType(population.BestOfAllTime, typeof(IEvolver));

            if (population is EvolvablePopulation)
            {
                AssertEx.IsGreaterThanOrEqualTo((population as EvolvablePopulation).FullPopulation, population.Individuals.Count);
            }

            foreach (IEvolvable evolvable in population.Individuals)
            {
                Assert.IsNotNull(evolvable);
            }

            foreach (var individual in population.Individuals)
            {
                if (individual is IPopulation)
                {
                    basicTest(individual as IPopulation);
                }
            }
        }
        /// <inheritdoc />
        public void Generate(EncogRandom rnd, IPopulation pop)
        {
            // prepare population
            _contents.Clear();
            pop.Species.Clear();
            ISpecies defaultSpecies = pop.CreateSpecies();

            if (Score.RequireSingleThreaded || ThreadCount == 1)
            {
                for (int i = 0; i < pop.PopulationSize; i++)
                {
                    EncogProgram prg = AttemptCreateGenome(rnd, pop);
                    AddPopulationMember(pop, prg);
                }
            }
            else
            {
                Parallel.For(0, pop.PopulationSize, i =>
                {
                    EncogProgram prg = AttemptCreateGenome(rnd, pop);
                    AddPopulationMember(pop, prg);
                });
            }

            // just pick a leader, for the default species.
            defaultSpecies.Leader = defaultSpecies.Members[0];
        }
Exemple #12
0
        /// <summary>Initializes a new instance of the <see cref="GeneticAlgorithm"/> class.</summary>
        /// <param name="population">The chromosomes population.</param>
        /// <param name="selection">The selection operator.</param>
        /// <param name="crossover">The crossover operator.</param>
        /// <param name="mutation">The mutation operator.</param>
        /// <param name="reinsertion">The reinsertion operator.</param>
        /// <param name="termination">The termination operator.</param>

        public DynamoGeneticAlgorithm(
            IPopulation population,
            ISelection selection,
            ICrossover crossover,
            IMutation mutation,
            IReinsertion reinsertion,
            ITermination termination)
        {
            ExceptionHelper.ThrowIfNull("population", population);
            ExceptionHelper.ThrowIfNull("selection", selection);
            ExceptionHelper.ThrowIfNull("crossover", crossover);
            ExceptionHelper.ThrowIfNull("mutation", mutation);
            ExceptionHelper.ThrowIfNull("reinsertion", reinsertion);
            ExceptionHelper.ThrowIfNull("termination", termination);

            Population  = population;
            Selection   = selection;
            Crossover   = crossover;
            Mutation    = mutation;
            Reinsertion = reinsertion;
            Termination = termination;

            SelectionSize        = 0;
            CrossoverProbability = (float)DefaultCrossoverProbability;
            MutationProbability  = (float)DefaultMutationProbability;

            TimeEvolving      = TimeSpan.Zero;
            OperatorsStrategy = new DefaultOperatorsStrategy();

            State = GeneticAlgorithmState.NotStarted;
        }
Exemple #13
0
 public StringGenerator(IPopulation <char> population, IWriter writer)
     : base(population, writer)
 {
     FittestIndividual           = new Individual(population.Chromosome);
     SecondFittestIndividual     = new Individual(population.Chromosome);
     FittestIndividualForAllTime = new Individual(population.Chromosome);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GeneticSharp.Domain.GeneticAlgorithm"/> class.
        /// </summary>
        /// <param name="population">The chromosomes population.</param>
        /// <param name="fitness">The fitness evaluation function.</param>
        /// <param name="selection">The selection operator.</param>
        /// <param name="crossover">The crossover operator.</param>
        /// <param name="mutation">The mutation operator.</param>
        public GeneticAlgorithm(
            IPopulation population,
            IFitness fitness,
            ISelection selection,
            ICrossover crossover,
            IMutation mutation)
        {
            ExceptionHelper.ThrowIfNull("population", population);
            ExceptionHelper.ThrowIfNull("fitness", fitness);
            ExceptionHelper.ThrowIfNull("selection", selection);
            ExceptionHelper.ThrowIfNull("crossover", crossover);
            ExceptionHelper.ThrowIfNull("mutation", mutation);

            Population  = population;
            Fitness     = fitness;
            Selection   = selection;
            Crossover   = crossover;
            Mutation    = mutation;
            Reinsertion = new ElitistReinsertion();
            Termination = new GenerationNumberTermination(1);

            CrossoverProbability = DefaultCrossoverProbability;
            MutationProbability  = DefaultMutationProbability;
            TimeEvolving         = TimeSpan.Zero;
            State        = GeneticAlgorithmState.NotStarted;
            TaskExecutor = new LinearTaskExecutor();
        }
Exemple #15
0
 public IntegersImplementationCommand(IReader reader, IWriter writer)
 {
     this.reader = reader;
     this.writer = writer;
     population  = new Population(this.reader, this.writer);
     generator   = new IntegersGenerator(population, writer);
 }
        /// <summary>
        /// Constructor for genetic algorithm.
        /// Genetic algorithms imitate natural biological processes,
        /// </summary>
        /// <param name="population">Init population. </param>
        /// <param name="fitness">Fitness.</param>
        /// <param name="selection">Selection operator.</param>
        /// <param name="xover">Xover operator.</param>
        /// <param name="mutation">Mutation operator.</param>
        /// <param name="elitizmus">Elitizmus.</param>
        /// <param name="termination">Termination GA.</param>
        /// <param name="executor">Executor.</param>
        /// <param name="mutationProbability">Mutation probability.</param>
        /// <param name="xoverProbability">Xover probability.</param>
        public GeneticAlgorithm(IPopulation population,
                                IFitness fitness,
                                ISelection selection,
                                IXover xover,
                                IMutation mutation,
                                IElite elitizmus,
                                ITermination termination,
                                IExecutor executor,
                                float mutationProbability,
                                float xoverProbability)
        {
            Population       = population;
            this.fitness     = fitness;
            this.selection   = selection;
            this.xover       = xover;
            this.mutation    = mutation;
            this.elitizmus   = elitizmus;
            this.executor    = executor;
            this.termination = termination;

            // base probability
            this.xoverProbability    = xoverProbability;
            this.mutationProbability = mutationProbability;
            TimeEvolving             = TimeSpan.Zero;
            CurrentGenerationsNumber = 1;
        }
        /// <summary>
        /// Construct an innovation list.
        /// </summary>
        ///
        /// <param name="population_0">The population.</param>
        /// <param name="links">The links.</param>
        /// <param name="neurons">THe neurons.</param>
        public NEATInnovationList(IPopulation population_0,
                                  Chromosome links, Chromosome neurons)
        {
            nextNeuronID = 0;
            population = population_0;

            foreach (IGene gene  in  neurons.Genes)
            {
                var neuronGene = (NEATNeuronGene) gene;

                var innovation = new NEATInnovation(neuronGene,
                                                    population_0.AssignInnovationID(), AssignNeuronID());
                Add(innovation);
            }


            foreach (IGene gene_1  in  links.Genes)
            {
                var linkGene = (NEATLinkGene) gene_1;
                var innovation_2 = new NEATInnovation(
                    linkGene.FromNeuronID, linkGene.ToNeuronID,
                    NEATInnovationType.NewLink,
                    population.AssignInnovationID());
                Add(innovation_2);
            }
        }
        private IPopulation GetNextPopulation(IPopulation currentPopulation)
        {
            var breedingSeason = breedingSeasonFactory.Build(currentPopulation);

            breedingSeason.ResolveConfrontations();
            return(breedingSeason.GetNewPopulation());
        }
        /// <summary>
        /// Linear xover executor.
        /// </summary>
        /// <param name="population">Input population.</param>
        /// <param name="xover">Xover operator.</param>
        /// <param name="xoverProbability">Xover probability</param>
        /// <param name="parents">Parents list</param>
        /// <returns>Childten(individuals)</returns>
        public virtual IList <IIndividual> Cross(IPopulation population, IXover xover, float xoverProbability, IList <IIndividual> parents)
        {
            var size = population.Size;

            var offspring = new List <IIndividual>(size);

            for (int i = 0; i < size; i += xover.ChildrenNumber)
            {
                // selected parents from population
                var selectedParents = parents.Skip(i).Take(xover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest individual
                if (selectedParents.Count == xover.ParentsNumber && FastRandom.GetDouble() <= xoverProbability)
                {
                    offspring.AddRange(xover.Cross(selectedParents));
                }
                else
                {
                    offspring.AddRange(selectedParents);
                }
            }

            return(offspring);
        }
 public IntegersGenerator(IPopulation <int> population, IWriter writer)
     : base(population, writer)
 {
     FittestIndividual           = new Individual(population.GeneLength);
     SecondFittestIndividual     = new Individual(population.GeneLength);
     FittestIndividualForAllTime = new Individual(population.GeneLength);
 }
Exemple #21
0
        public T Select <T>(IPopulation <T> population) where T : IBreedingCandidate
        {
            if (population.Size <= 0)
            {
                throw new ArgumentException("The population cannot be empty");
            }

            var selected = default(T);

            var spin = _randomNumberGenerator.NextDouble() * population.TotalFitness;

            var currentFitness = 0.0;

            foreach (var candidate in population.GetCandidates())
            {
                currentFitness += candidate.Fitness;

                if (spin <= currentFitness)
                {
                    selected = candidate;
                    break;
                }
            }

            return(selected);
        }
Exemple #22
0
        private AgentOrderbookLoader MakeAgentOrderbookLoader(string PATH)
        {
            int dim = 0;

            string []  names = new string [0];
            double []  mins  = new double [0];
            double []  maxs  = new double [0];
            IBlauSpace s     = BlauSpace.create(dim, names, mins, maxs);

            IBlauPoint    mean = new BlauPoint(s);
            IBlauPoint    std  = new BlauPoint(s);
            IDistribution d    = new Distribution_Gaussian(s, mean, std);

            IAgentFactory afact = new AgentOrderbookLoader_Factory(PATH, d);
            IPopulation   pop   = PopulationFactory.Instance().create(afact, 1);

            AgentOrderbookLoader loader = null;

            foreach (IAgent ag in pop)
            {
                loader = (AgentOrderbookLoader)ag;
                break;
            }

            return(loader);
        }
Exemple #23
0
 public virtual void AddEntitiesToPopulation(IPopulation population, IEntityList entities)
 {
     for (int i = 0; i < entities.Count; i++)
     {
         population.Add(entities[i]);
     }
 }
        /// <summary>
        /// Construct an innovation list. 
        /// </summary>
        /// <param name="population">The population.</param>
        /// <param name="links">The links.</param>
        /// <param name="neurons">The neurons.</param>
        public NEATInnovationList(IPopulation population, Chromosome links, Chromosome neurons)
        {

            this.population = population;
            foreach (IGene gene in neurons.Genes)
            {
                NEATNeuronGene neuronGene = (NEATNeuronGene)gene;

                NEATInnovation innovation = new NEATInnovation(neuronGene,
                       population.AssignInnovationID(), AssignNeuronID());

                Innovations.Add(innovation);

            }

            foreach (IGene gene in links.Genes)
            {
                NEATLinkGene linkGene = (NEATLinkGene)gene;
                NEATInnovation innovation = new NEATInnovation(linkGene
                        .FromNeuronID, linkGene.ToNeuronID,
                        NEATInnovationType.NewLink, this.population.AssignInnovationID());
                Innovations.Add(innovation);

            }
        }
Exemple #25
0
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            pop          = InitPopulation();
            score        = new PlantScore();
            this.genetic = new BasicEA(pop, score);

            //this.genetic.Speciation = new ArraySpeciation<DoubleArrayGenome>();

            genetic.AddOperation(0.9, new Splice(PlantUniverse.GenomeSize / 3));
            genetic.AddOperation(0.1, new MutatePerturb(0.1));

            // Display

            this.universe = new PlantUniverse();
            this.universe.Reset();


            DoubleArrayGenome bestGenome = (DoubleArrayGenome)genetic.BestGenome;
            PlantPhysics      physics    = new PlantPhysics();
            PlantGrowth       growth     = new PlantGrowth();

            for (int i = 0; i < 100; i++)
            {
                physics.RunPhysics(universe);
                growth.RunGrowth(universe, bestGenome.Data);
            }

            this.display          = new DisplayPlant(CanvasOutput);
            this.display.Universe = this.universe;
            Thread t = new Thread(DoWork);

            t.Start();
        }
Exemple #26
0
 public virtual void RemoveEntitiesFromPopulation(IPopulation population, IEntityList entities)
 {
     for (int i = 0; i < entities.Count; i++)
     {
         population.Remove(entities[i]);
     }
 }
Exemple #27
0
        /// <summary>
        /// Evolved one generation.
        /// </summary>
        /// <param name="population">Current population.</param>
        /// <returns>New generation.</returns>
        protected override IPopulation EvolvedOneGeneration(IPopulation population)
        {
            List <Tuple <Vector <double>, double> > solutions = new List <Tuple <Vector <double>, double> >();

            for (int i = 0; i < cma.PopSize; i++)
            {
                var x = cma.Ask();

                var currInd = population.CreateEmptyIndividual();
                currInd.ReplaceGenes(x.ToArray());

                var value = fitness.Evaluate(currInd);
                solutions.Add(new Tuple <Vector <double>, double>(x, value));
            }
            cma.Tell(solutions);

            double yCurrentBest = solutions.Min(x => x.Item2);
            var    xCurrentBest = solutions.Where(x => x.Item2 == yCurrentBest).FirstOrDefault().Item1;


            IIndividual bestInd = population.CreateEmptyIndividual();

            bestInd.ReplaceGenes(xCurrentBest.ToArray());
            fitness.Evaluate(bestInd);
            BestIndividual = bestInd;

            // Console.WriteLine(j + " - " + yCurrentBest);
            CurrentGenerationsNumber++;
            population.Individuals = new List <IIndividual>();

            population.Individuals.Add(bestInd);

            return(population);
        }
Exemple #28
0
        static public AgentOrderbookLoader MakeAgentOrderbookLoader(string path)
        {
            string [] names = new string [1] {
                "x"
            };
            double [] mins = new double [1] {
                0.00
            };
            double [] maxs = new double [1] {
                100.0
            };
            IBlauSpace    s = BlauSpace.create(1, names, mins, maxs);
            IDistribution d = new Distribution_Gaussian(s, 0.0, 0.0);

            IAgentFactory afact = new AgentOrderbookLoader_Factory(path, d);
            IPopulation   pop   = PopulationFactory.Instance().create(afact, 1);

            AgentOrderbookLoader loader = null;

            foreach (IAgent ag in pop)
            {
                loader = (AgentOrderbookLoader)ag;
                break;
            }

            return(loader);
        }
        /// <summary>
        ///     Selects two individuals from the population and performs the crossover operation on them.
        /// </summary>
        /// <param name="population">The population to select from</param>
        /// <returns></returns>
        public IIndividual PerformCrossover(IPopulation population)
        {
            var individual1 = _selectionStrategy.SelectIndividualFromPopulation(population);
            var individual2 = _selectionStrategy.SelectIndividualFromPopulation(population);

            return(PerformCrossover(individual1, individual2));
        }
        public override IEntityList Replace(IPopulation targetPopulation, IEntityList offspring, IEntityList parents, IPopulation sourcePopulation)
        {
            var inserted       = new EntityList(1);
            var populationSize = Parameters.GetValue(Algorithm.ParameterNames.PopulationSize);

            //TODO: FitnessComparer.SelectWorst, SelectBest

            if (offspring.Count == 0)
            {
                return(inserted);
            }

            var entityToRemove = FitnessComparer.Dominates(parents[0].Fitness, parents[1].Fitness) ? parents[0] : parents[1];
            var entityToAdd    = (offspring.Count > 1 && FitnessComparer.Dominates(offspring[0].Fitness, offspring[1].Fitness)) ? offspring[1] : offspring[0];

            if (FitnessComparer.Dominates(entityToRemove.Fitness, entityToAdd.Fitness))
            {
                targetPopulation.Add(entityToAdd);
                inserted.Add(entityToAdd);

                if (sourcePopulation.Count > populationSize)
                {
                    sourcePopulation.Remove(entityToRemove);
                }
            }

            return(inserted);
        }
 public StringImplementationCommand(IReader reader, IWriter writer)
 {
     this.reader = reader;
     this.writer = writer;
     population  = new Population(this.reader, this.writer);
     generator   = new StringGenerator(population, writer);
 }
Exemple #32
0
        public OptimizationResult Optimize()
        {
            _selection = new EliteSelection();
            _crossover = new UniformCrossover();
            _mutation  = new TworsMutation();

            _chromosome = new BlockedTestcasesChromosome(_dataset.Blockers.Count);
            _fitness    = new WeightedMaximizeSolvedTestcasesFitness(_resolver);

            _population = new Population(20, 40, _chromosome);

            _ga             = new GeneticAlgorithm(_population, _fitness, _selection, _crossover, _mutation);
            _ga.Termination = new OrTermination(new FitnessStagnationTermination(100),
                                                new GenerationNumberTermination(10000),
                                                new TimeEvolvingTermination(TimeSpan.FromMinutes(5)));

            //_ga.GenerationRan += Ga_GenerationRan;
            //_fitness.Evaluated += Fitness_Evaluated;

            _ga.Start();

            var resolvedBlockers = GetBlockersToResolve(_ga.BestChromosome);
            var resolution       = _resolver.Resolve(resolvedBlockers);

            var resolvedTestcases = resolution.ResolvedTestcases;
            var resolvedTestcasesIncludingUnblocked = resolution.ResolvedDataset.Testcases.Where(x => x.BlockerIds.Count <= 0).ToList();// GetResolvedTestcasesIncludingUnblocked(resolvedBlockers);

            var cost  = _dataset.GetCostForBlockers(resolvedBlockers);
            var value = _dataset.GetValueForTestcases(resolvedTestcases);
            var valueIncludingUnblocked = _dataset.GetValueForTestcases(resolvedTestcasesIncludingUnblocked);

            var optimizationResult = new OptimizationResult(_ga.BestChromosome.Fitness.Value, value, valueIncludingUnblocked, cost, resolvedBlockers, resolvedTestcases, resolvedTestcasesIncludingUnblocked);

            return(optimizationResult);
        }
Exemple #33
0
 public Citizen(IPopulation population, IInsuranceSocialSystem iss)
 {
     State = CitizenState.Premature;
     Age = new Age();
     DeathAge = RollDeathAge();
     Laziness = StatisticHelper.RollLaziness();
     Population = population;
     ISS = iss;
 }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(IPopulation population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            if (offspring.Count > population.MaxSize)
            {
                return offspring.OrderByDescending(o => o.Fitness).Take(population.MaxSize).ToList();
            }

            return offspring;
        }
        /// <summary>
        /// Register that a new generation has been created.
        /// </summary>
        /// <param name="population">The population where the new generation has been created.</param>
        public void RegisterNewGeneration(IPopulation population)
        {
            ExceptionHelper.ThrowIfNull("population", population);

            if (population.Generations.Count > GenerationsNumber)
            {
                population.Generations.RemoveAt(0);
            }
        }
 /// <summary>
 ///     Construct a species.
 /// </summary>
 /// <param name="thePopulation">The population the species belongs to.</param>
 /// <param name="theFirst">The first genome in the species.</param>
 public BasicSpecies(IPopulation thePopulation, IGenome theFirst)
 {
     Population = thePopulation;
     BestScore = theFirst.Score;
     GensNoImprovement = 0;
     Age = 0;
     Leader = theFirst;
     _members.Add(theFirst);
 }
        public override IOrganism Execute(IPopulation population)
        {
            var target = Randomizer.NextDouble();

            foreach (var organism in population)
                if (organism.Metrics.Value.ProportionSumInPopulation > target)
                    return organism;

            return population.Last();
        }
        /// <summary>
        /// Select one genome of population
        /// </summary>
        /// <param name="population">Population with genomes</param>
        /// <returns>The genome chosen</returns>
        public IGenome Select(IPopulation population)
        {
            int genome1 = Helper.Random.Next(0, population.Length);
            int genome2 = Helper.Random.Next(0, population.Length);

            if (population[genome1].CompareTo(population[genome2]) < 0)
                return population[genome2];
            else
                return population[genome1];
        }
 public World(IPopulation pop, IPersonFactory pf, IRandomGenerator random, IMortalityCurve mc)
 {
     _mortalityCurve = mc;
     _registeredGenes = new GeneBank(this);
     WorldSeeds.BaseGenes(_registeredGenes, this);
     _population = pop;
     _personFactory = pf;
     _random = random;
     SeedWorld(1001);
 }
Exemple #40
0
 public void Add(IPopulation population)
 {
     Contract.Requires(population != null);
     
     lock (populationSync)
     {
         populations.Add(population);
         AddHandlers(population);
     }
 }
Exemple #41
0
        internal BestBodyArrivedToPopulationEventArgs(IPopulation population, IGroup group, IBody body)
        {
            Contract.Requires(population != null);
            Contract.Requires(group != null);
            Contract.Requires(body != null);

            Population = population;
            Group = group;
            Body = body;
        }
 /// <summary>
 ///     Construct the parallel score calculation object.
 /// </summary>
 /// <param name="thePopulation">The population to score.</param>
 /// <param name="theCODEC">The CODEC to use.</param>
 /// <param name="theAdjusters">The score adjusters to use.</param>
 /// <param name="theScoreFunction">The score function.</param>
 /// <param name="theThreadCount">The requested thread count.</param>
 public ParallelScore(IPopulation thePopulation, IGeneticCODEC theCODEC,
                      IList<IAdjustScore> theAdjusters, ICalculateScore theScoreFunction,
                      int theThreadCount)
 {
     _codec = theCODEC;
     _population = thePopulation;
     _scoreFunction = theScoreFunction;
     _adjusters = theAdjusters;
     ThreadCount = theThreadCount;
 }
 public World(IPopulation pop, IPersonFactory pf, IMortalityCurve mortalityCurve, IRandomGenerator random)
 {
     if (pop?.Populus?.Count > 0) pop.Populus.Clear();
     _random = random;
     _population = pop;
     _registeredGenes = new GeneBank(this);
     _personFactory = pf;
     _mortalityCurve = mortalityCurve;
     WorldSeeds.BaseGenes(_registeredGenes, this);
     SeedWorld(1000);
     _population?.UpdatePopulus();
 }
        public override IOrganism Execute(IPopulation population)
        {
            /*Selection pressure is easily adjusted by changing the tournament size. 
             * If the tournament size is larger, weak individuals have a smaller chance to be selected.*/

            // As the generations go up, the tournament should be more pressured
            
            var fighterOne = population.RandomElement();
            var fighterTwo = population.RandomElement();

            return population.ParentIEnvironment.OrganismValueComparer.Compare(fighterOne, fighterTwo) > 0 ? fighterOne : fighterTwo;
        }
Exemple #45
0
        public void Remove(IPopulation population)
        {
            Contract.Requires(population != null);

            lock (populationSync)
            {
                int idx = populations.IndexOf(population);
                if (idx != -1)
                {
                    populations.RemoveAt(idx);
                    RemoveHandlers(population);
                }
            }
        }
Exemple #46
0
        /// <summary>
        /// Record each genome of population and some other parameters
        /// </summary>
        /// <param name="population">Population to be record</param>
        /// <param name="generation">Number of generation</param>
        /// <param name="avarageFitness">Avarage fitness of population</param>
        public void setPopulationLog(IPopulation population, int generation, double avarageFitness)
        {
            xtw.WriteStartElement("Population");
            xtw.WriteAttributeString("Generation", generation.ToString());
            xtw.WriteAttributeString("AvarageFitness", avarageFitness.ToString());

            for (int i = 0; i < population.Length; i++)
            {
                xtw.WriteStartElement("Genome");
                xtw.WriteAttributeString("Value", population[i].ToString());
                xtw.WriteAttributeString("Fitness", population[i].Evaluate().ToString());
                xtw.WriteEndElement();
            }
            xtw.WriteEndElement();
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(IPopulation population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            if (offspring.Count == 0)
            {
                throw new ReinsertionException(this, "The minimum size of the offspring is 1.");
            }

            var rnd = RandomizationProvider.Current;

            while (offspring.Count < population.MinSize)
            {
                offspring.Add(offspring[rnd.GetInt(0, offspring.Count)]);
            }

            return offspring;
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(IPopulation population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            var diff = population.MinSize - offspring.Count;

            if (diff > 0)
            {
                var bestParents = parents.OrderByDescending(p => p.Fitness).Take(diff);

                foreach (var p in bestParents)
                {
                    offspring.Add(p);
                }
            }

            return offspring;
        }
        public void calculatePopulate()
        {
            DateTime startDate = DateTime.Now;

            if (_option.typeAlgoritme == staticConst.DIFFERENCIAL_GENETIC_ALGORITME)
            {
                populate = new DEGenetic(_option.countPopulate, _option.countValueVariable, _option.turnInteger, _containerFunction, _option.сhanceMutation, _option.valueMutation);
            }
            else if (_option.typeAlgoritme == staticConst.CLASSIC_ALGORITME)
            {
                populate = new ClassicGenetic(_option.countPopulate, _option.countValueVariable, _option.turnInteger, _containerFunction, _option.сhanceMutation, _option.valueMutation);
            }
            else if (_option.typeAlgoritme == staticConst.CLASSIC_ALGORITME2)
            {
                populate = new ClassicGenetic2(_option.countPopulate, _option.countValueVariable, _option.turnInteger, _containerFunction, _option.сhanceMutation, _option.valueMutation, _option.B);
            }
            else if (_option.typeAlgoritme == staticConst.DOUBLE_ALGORITM)
            {
                populate = new DoubleGenetic(_option.countPopulate, _option.countValueVariable, _option.turnInteger, _containerFunction, _option.сhanceMutation, _option.valueMutation);
            }

            populate.init();

            _intermediateResult = populate.bestChromosome();

            ProgressBarEventArgs eventsArg = new ProgressBarEventArgs(_option.countGeneration);
            for (int i = 1; i <= _option.countGeneration; i++)
            {
                populate.nextGeneration();

                if (showProgress != null)
                {
                    eventsArg.step = i;
                    showProgress(this, eventsArg);

                }
            }

            DateTime stopDate = DateTime.Now;

            TimeSpan interval =  stopDate - startDate;

            _result = populate.bestChromosome();
            _result.time = interval.Milliseconds;
        }
        /// <summary>
        ///     Construct an EA.
        /// </summary>
        /// <param name="thePopulation">The population.</param>
        /// <param name="theScoreFunction">The score function.</param>
        public BasicEA(IPopulation thePopulation,
                       ICalculateScore theScoreFunction)
        {
            RandomNumberFactory = EncogFramework.Instance.RandomFactory.FactorFactory();
            EliteRate = 0.3;
            MaxTries = 5;
            MaxOperationErrors = 500;
            CODEC = new GenomeAsPhenomeCODEC();


            Population = thePopulation;
            ScoreFunction = theScoreFunction;
            Selection = new TournamentSelection(this, 4);
            Rules = new BasicRuleHolder();

            // set the score compare method
            if (theScoreFunction.ShouldMinimize)
            {
                SelectionComparer = new MinimizeAdjustedScoreComp();
                BestComparer = new MinimizeScoreComp();
            }
            else
            {
                SelectionComparer = new MaximizeAdjustedScoreComp();
                BestComparer = new MaximizeScoreComp();
            }

            // set the iteration
            foreach (ISpecies species in thePopulation.Species)
            {
                foreach (IGenome genome in species.Members)
                {
                    IterationNumber = Math.Max(IterationNumber,
                                               genome.BirthGeneration);
                }
            }


            // Set a best genome, just so it is not null.
            // We won't know the true best genome until the first iteration.
            if (Population.Species.Count > 0 && Population.Species[0].Members.Count > 0)
            {
                BestGenome = Population.Species[0].Members[0];
            }
        }
        public static IList<IIndividual<Wrapper<MyValuableClass>>> SelectionFunc(IPopulation<Wrapper<MyValuableClass>> population, IGAconfiguration gaConfigs)
        {
            IList<IIndividual<Wrapper<MyValuableClass>>> list = new List<IIndividual<Wrapper<MyValuableClass>>>();
            int individualsCountToSelect = population.Individuals.Count;
            if (gaConfigs.ElitismPercentage != null)
            {
                int populationSize = population.Individuals.Count;
                int eliteIndCount = (int)(populationSize * gaConfigs.ElitismPercentage);
                individualsCountToSelect = populationSize - eliteIndCount;
            }

            while (list.Count < individualsCountToSelect)
            {
                var ind = GAUtils.ProvideTournamentSelection(2, population);
                list.Add(ind);
            }
            return list;
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        public IList<IChromosome> SelectChromosomes(IPopulation population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            ExceptionHelper.ThrowIfNull("population", population);
            ExceptionHelper.ThrowIfNull("offspring", offspring);
            ExceptionHelper.ThrowIfNull("parents", parents);

            if (!CanExpand && offspring.Count < population.MinSize)
            {
                throw new ReinsertionException(this, "Cannot expand the number of chromosome in population. Try another reinsertion!");
            }

            if (!CanCollapse && offspring.Count > population.MaxSize)
            {
                throw new ReinsertionException(this, "Cannot collapse the number of chromosome in population. Try another reinsertion!");
            }

            return PerformSelectChromosomes(population, offspring, parents);
        }
Exemple #53
0
 public NEATInnovationList(IPopulation population_0, Chromosome links, Chromosome neurons)
 {
     this.nextNeuronID = 0L;
     this.population = population_0;
     foreach (IGene gene in neurons.Genes)
     {
         NEATNeuronGene neuronGene = (NEATNeuronGene) gene;
         NEATInnovation innovation = new NEATInnovation(neuronGene, population_0.AssignInnovationID(), this.AssignNeuronID());
         if (15 == 0)
         {
             break;
         }
         base.Add(innovation);
     }
     foreach (IGene gene3 in links.Genes)
     {
         NEATLinkGene gene4 = (NEATLinkGene) gene3;
         NEATInnovation innovation2 = new NEATInnovation((long) gene4.FromNeuronID, (long) gene4.ToNeuronID, NEATInnovationType.NewLink, this.population.AssignInnovationID());
         base.Add(innovation2);
     }
 }
Exemple #54
0
 public BasicSpecies(IPopulation thePopulation, IGenome theFirst, long theSpeciesID)
 {
     this._members = new List<IGenome>();
     this._population = thePopulation;
     Label_005F:
     this._speciesID = theSpeciesID;
     if (0xff != 0)
     {
         this._bestScore = theFirst.Score;
         this._gensNoImprovement = 0;
         if (0 != 0)
         {
             goto Label_005F;
         }
         this._age = 0;
     }
     if (((uint) theSpeciesID) >= 0)
     {
         this._leader = theFirst;
     }
     this._spawnsRequired = 0.0;
     this._members.Add(theFirst);
 }
Exemple #55
0
 public NEATTraining(ICalculateScore calculateScore, IPopulation population)
 {
     NEATGenome genome;
     this.xd9d3bb742c7a307b = 0.1;
     this.x67e8029e782709f0 = 0.07;
     this.xe6c7b0462e12d2ff = 0.04;
     this.xd3f94467320a5684 = 0.05;
     this.x8a503d42183ff26d = 0.26;
     this.xa4a074c49c97739c = 0.7;
     this.xf52a69d338e65c0f = 0.1;
     this.x214332e2bd2e8ae1 = 100.0;
     this.x7a6edccccc229234 = 0.5;
     this.x68e0847485ce0c21 = 0.2;
     this.xd7944ba63721a56b = 5;
     this.xfca9d4aed1b3cd4b = 15;
     this.xe44426390f1f3741 = 5;
     this.x340c2bbd00cd3fa4 = 5;
     this.xe5ff50155887c0e7 = 0.1;
     goto Label_0102;
     if (0 == 0)
     {
         goto Label_010B;
     }
     Label_0102:
     if (population.Size() < 1)
     {
         throw new TrainingError("Population can not be empty.");
     }
     Label_010B:
     genome = (NEATGenome) population.Genomes[0];
     base.CalculateScore = new GeneticScoreAdapter(calculateScore);
     base.Comparator = new GenomeComparator(base.CalculateScore);
     base.Population = population;
     this.x43f451310e815b76 = genome.InputCount;
     this.x98cf41c6b0eaf6ab = genome.OutputCount;
     this.xd586e0c16bdae7fc();
 }
 /// <summary>
 ///     Create a trainer for training data.
 /// </summary>
 /// <param name="thePopulation">The population.</param>
 /// <param name="trainingData">The training data.</param>
 public TrainEA(IPopulation thePopulation, IMLDataSet trainingData)
     : base(thePopulation, new TrainingSetScore(trainingData))
 {
 }
 public EvolutionManager(IPopulation population)
 {
     Population = population;
     MutationRate = ConfigManager.Current.MutationRate;
 }
Exemple #58
0
        /// <summary>
        /// Construct neat training with an existing population.
        /// </summary>
        /// <param name="calculateScore">The score object to use.</param>
        /// <param name="population">The population to use.</param>
        public NEATTraining(ICalculateScore calculateScore,
                            IPopulation population)
        {
            if (population.Size() < 1)
            {
                throw new TrainingError("Population can not be empty.");
            }

            var genome = (NEATGenome) population.Genomes[0];
            CalculateScore = new GeneticScoreAdapter(calculateScore);
            Comparator = new GenomeComparator(CalculateScore);
            Population = (population);
            inputCount = genome.InputCount;
            outputCount = genome.OutputCount;

            Init();
        }
 /// <summary>
 ///     Create a trainer for a score function.
 /// </summary>
 /// <param name="thePopulation">The population.</param>
 /// <param name="theScoreFunction">The score function.</param>
 public TrainEA(IPopulation thePopulation, ICalculateScore theScoreFunction)
     : base(thePopulation, theScoreFunction)
 {
 }
Exemple #60
0
 /// <summary>
 /// Construct a species.
 /// </summary>
 ///
 /// <param name="thePopulation">The population the species belongs to.</param>
 /// <param name="theFirst">The first genome in the species.</param>
 /// <param name="theSpeciesID">The species id.</param>
 public BasicSpecies(IPopulation thePopulation, IGenome theFirst,
                     long theSpeciesID)
 {
     _members = new List<IGenome>();
     _population = thePopulation;
     _speciesID = theSpeciesID;
     _bestScore = theFirst.Score;
     _gensNoImprovement = 0;
     _age = 0;
     _leader = theFirst;
     _spawnsRequired = 0;
     _members.Add(theFirst);
 }