Esempio n. 1
0
        public void Step(int MaxThreads = 4)
        {
            ParallelOptions pOptions = new ParallelOptions
            {
                MaxDegreeOfParallelism = MaxThreads
            };

            Parallel.For(0, CurrentGeneration.Height, pOptions, y =>
            {
                for (int x = 0; x < CurrentGeneration.Width; x++)
                {
                    int AliveNeighbors = CurrentGeneration.GetAliveNeighbours(x, y);
                    bool isAlive       = CurrentGeneration.IsAlive(x, y);

                    if (isAlive && (AliveNeighbors == 2 || AliveNeighbors == 3))
                    {
                        NextGeneration.SetPixel(x, y, true);
                    }
                    else if (!isAlive && AliveNeighbors == 3)
                    {
                        NextGeneration.SetPixel(x, y, true);
                    }
                    else
                    {
                        NextGeneration.SetPixel(x, y, false);
                    }
                }
            });
        }
Esempio n. 2
0
        public static void Initialize()
        {
            thisEvolution = new Evolution();
            thisEvolution.Start();

            Loading = true;


            Random RNG = new Random();

            EvolviMaxAmount    = 1f;
            EvolviLoadedAmount = 0;

            CurrentGeneration.Clear();

            for (int i = 0; i < evolviAmount; i++)
            {
                CurrentGeneration.Add(new Evolvi(new Vector2(RNG.Next(20, 2000 - 20), RNG.Next(20, 2000 - 20))));
            }

            CurrentFood.Clear();

            for (int i = 0; i < foodAmount; i++)
            {
                CurrentFood.Add(new Food(new Vector2(RNG.Next(20, 2000 - 20), RNG.Next(20, 2000 - 20))));

                Thread.Sleep(10);
            }

            Loading = false;
        }
Esempio n. 3
0
        public void NextGeneration()
        {
            SpeciesCollection.ClearSpecies();
            foreach (var genome in CurrentGeneration)
            {
                SpeciesCollection.Speciate(genome);
            }
            SpeciesCollection.ClearEmptySpecies();

            int population = Population;

            var nextGeneration = SpeciesCollection.Selection(population);

            LastGenerationWithSpecies = nextGeneration;

            // fill up when there is no species or
            var remaining = population - nextGeneration.Count;

            for (int i = 0; i < remaining; i++)
            {
                nextGeneration.Add(Genome.CreateDefault(this), null);
            }

            //Populate(population);

            LastFillUp = remaining;

            LastGeneration.Clear();
            LastGeneration.AddRange(CurrentGeneration);
            CurrentGeneration.Clear();
            CurrentGeneration.AddRange(nextGeneration.Select(x => x.Key));

            Generation++;
        }
 public string CandidateInfo(Candidate candidate)
 {
     return($"X1 = {candidate.X1}, \n" +
            $"X2 = {candidate.X2}, \n" +
            $"X3 = {candidate.X3}, \n" +
            $"Fitness = {candidate.Fitness}, \n" +
            $"Average of Generation = {CurrentGeneration.Select(x => x.Fitness).Average()}\n");
 }
 private void InitializePopulation()
 {
     for (int i = 0; i < PopulationSize; i++)
     {
         var candidate = new Candidate();
         CurrentGeneration.Add(candidate);
     }
 }
Esempio n. 6
0
 public void Populate(int population)
 {
     for (var i = 0; i < population; i++)
     {
         var genome = Genome.CreateDefault(this);
         CurrentGeneration.Add(genome);
     }
 }
        private void ToggleCellInNextGeneration(int x, int y)
        {
            var isAliveInNextGen = CurrentGeneration.IsCellReincarnated(x, y);

            if (isAliveInNextGen)
            {
                NextGeneration[x, y].Toggle();
            }
        }
Esempio n. 8
0
 private bool CheckPopulationForZero()
 {
     if (CurrentGeneration.CalculatePopulation() != 0)
     {
         return(false);
     }
     Console.WriteLine("All dead! All dead!");
     return(true);
 }
        private void CheckRowGrowth(Borders border)
        {
            var aliveCellGroupCount
                = CurrentGeneration.GetConsecutiveHorizontalCellCount(border);

            if (aliveCellGroupCount >= 1)
            {
                AddRow(border);
            }
        }
        private void CheckColumnGrowth(Borders border)
        {
            var aliveCellGroupCount
                = CurrentGeneration.GetConsecutiveVerticalCellCount(border);

            if (aliveCellGroupCount >= 1)
            {
                AddColumn(border);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Ends the current generation.
        /// </summary>
        public virtual void EndCurrentGeneration()
        {
            CurrentGeneration.End(MaxSize);

            if (BestChromosome != CurrentGeneration.BestChromosome)
            {
                BestChromosome = CurrentGeneration.BestChromosome;

                OnBestChromosomeChanged(EventArgs.Empty);
            }
        }
Esempio n. 12
0
        public void ApplyFitnessJudgement(FitnessJudgement judgement)
        {
            int weight = _settingsGa.GetWeightOfFitnessJudgement(judgement);

            if (weight > 0)
            {
                _currentCa.Fitness = weight;
                CurrentGeneration.Add(_currentCa);
            }
            GenerateNewCa();
        }
        /// <summary>
        ///     Ends the current generation.
        /// </summary>
        public virtual void EndCurrentGeneration()
        {
            CurrentGeneration.End(CurrentGeneration.Genomes.Count);

            if (BestGenome != CurrentGeneration.BestGenome)
            {
                BestGenome = CurrentGeneration.BestGenome;

                OnBestGenomeChanged(EventArgs.Empty);
            }
        }
Esempio n. 14
0
 public void CreateEmpty(int universeSize)
 {
     Size = universeSize;
     for (int column = 0; column < universeSize; column++)
     {
         for (int raw = 0; raw < universeSize; raw++)
         {
             CurrentGeneration.Add(new Point(raw, column), new Cell());
             NextGeneration.Add(new Point(raw, column), new Cell());
         }
     }
 }
Esempio n. 15
0
 public void Reset(int population, int inputs, int outputs)
 {
     Generation   = 0;
     InnovationId = 0;
     GenomeId     = 0;
     NodeId       = 0;
     InitialNodes.Clear();
     CurrentGeneration.Clear();
     LastGeneration.Clear();
     SpeciesCollection.SpeciesItems.Clear();
     Connections.Clear();
     Initialize(population, inputs, outputs);
 }
Esempio n. 16
0
 private bool InBounds(Point startCoords, int figureSize)
 {
     for (int column = startCoords.Y; column < startCoords.Y + figureSize; column++)
     {
         for (int raw = startCoords.X; raw < startCoords.X + figureSize; raw++)
         {
             if (!CurrentGeneration.ContainsKey(new Point(raw, column)))
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Esempio n. 17
0
        /// <summary>
        /// Ends the current generation.
        /// </summary>
        public void EndCurrentGeneration()
        {
            CurrentGeneration.End(MaxSize);

            if (BestChromosome != CurrentGeneration.BestChromosome)
            {
                BestChromosome = CurrentGeneration.BestChromosome;

                if (BestChromosomeChanged != null)
                {
                    BestChromosomeChanged(this, EventArgs.Empty);
                }
            }
        }
Esempio n. 18
0
        public void StartGame()
        {
            CurrentGeneration.FillField();

            while (true)
            {
                CurrentGeneration.PrintField();
                if (CheckPopulationForZero())
                {
                    break;
                }
                CurrentGeneration.BornNextGeneration(NextGeneration);
                TryToFixStalemate();
                ShiftGenerations();
                Thread.Sleep(100);
            }
        }
Esempio n. 19
0
        public void EvaluatePopulation()
        {
            List <Chromosome> chromosomes = CurrentGeneration.FindAll(x => x.FitnessOutdated);

            if (chromosomes.Count == 0)
            {
                return;
            }

            int evaluations = (int)((double)chromosomes.Count * EvaluationRate);
            List <Chromosome> orderedChromosomes = chromosomes.OrderByDescending(x => x.Priority).ToList();

            for (int i = 0; i < orderedChromosomes.Count; i++)
            {
                Chromosome c = orderedChromosomes[i];

                if (i < evaluations) //Chosen for evaluation
                {
                    c.Fitness         = FitnessFunction.Evaluate(c);
                    c.Priority        = 0;
                    c.FitnessOutdated = false;
                    totalEvaluations++;
                }
                else
                {
                    c.Priority += NonEvaluationWeigth;
                }
                //If the maximum number is reached while evaluating the population, the process is interrupted.
                if (totalEvaluations == MaxEvaluations)
                {
                    break;
                }
            }

            if (EvaluationRate < 1)
            {
                EvaluationRate = EvaluationRate + (1 - EvaluationRate) * 0.001;
            }
            if (EvaluationRate > 1)
            {
                EvaluationRate = 1;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Checks square around cell and returns true, if cell is alive.
        /// </summary>
        /// <param name="cellCoord"></param>
        /// <param name="currentGeneration"></param>
        /// <returns></returns>
        private bool CheckCellState(Point cellCoord)
        {
            int livesCounter = 0;

            var neighbours = new Point []
            {
                new Point(cellCoord.X - 1, cellCoord.Y - 1),
                new Point(cellCoord.X, cellCoord.Y - 1),
                new Point(cellCoord.X + 1, cellCoord.Y - 1),
                new Point(cellCoord.X - 1, cellCoord.Y),
                new Point(cellCoord.X + 1, cellCoord.Y),
                new Point(cellCoord.X - 1, cellCoord.Y + 1),
                new Point(cellCoord.X, cellCoord.Y + 1),
                new Point(cellCoord.X + 1, cellCoord.Y + 1),
            };

            foreach (var neighbour in neighbours)
            {
                if (CurrentGeneration.ContainsKey(neighbour) && CurrentGeneration[neighbour].Alive)
                {
                    livesCounter++;
                }
            }

            if ((livesCounter == 3 || livesCounter == 2) && CurrentGeneration[new Point((cellCoord.X + Size) % Size, (cellCoord.Y + Size) % Size)].Alive)
            {
                return(true);
            }
            else if (livesCounter == 3)
            {
                return(true);
            }
            else if (livesCounter < 2 || livesCounter > 3)
            {
                return(false);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Tworzy nową generację krzyżując obiekty z obecnej generacji.
        /// </summary>
        /// <returns>Zwraca nową generację.</returns>
        public Generation CreateNewGeneration()
        {
            if (!CurrentGeneration.WasEvaluated)
            {
                CurrentGeneration.Evaluate();
            }

            IDna[] objects = new IDna[GenerationsSize];
            for (uint i = 0; i < GenerationsSize; i++)
            {
                IDna parentA = CurrentGeneration.GetDnaBasedOnFitness();
                IDna parentB = CurrentGeneration.GetDnaBasedOnFitness();
                objects[i] = evolutionController.Crossover(parentA, parentB);
                IDna db = objects[i];
                Console.WriteLine(new string(db.GetGenes() as char[]) + " ||| " + db.Fitness);
            }

            CurrentGeneration = new Generation(evolutionController, objects);
            CurrentGeneration.Mutate(MutationChance > 100 ? (byte)100 : MutationChance);
            return(CurrentGeneration);
        }
Esempio n. 22
0
        private void InitializePopulation()
        {
            for (var i = 0; i < PopulationSize; i++)
            {
                CurrentGeneration.Add(new Knapsack(_knapsackCapacity, _maxKnapsackWeight));
            }

            BestOfRun = CurrentGeneration[0];

            foreach (var knapsack in CurrentGeneration)
            {
                var knapsackFitness     = GetKnapsackFitness(knapsack);
                var bestKnapsackFitness = GetKnapsackFitness(BestOfRun);
                if (knapsackFitness > bestKnapsackFitness)
                {
                    BestOfRun        = knapsack;
                    BestOfRunFitness = knapsackFitness;
                }
            }

            Generations.Add(CurrentGeneration);
        }
Esempio n. 23
0
    protected override void OnEndSimulation()
    {
        var max = CurrentGeneration.First(i => i.Fitness.Equals(CurrentGeneration.Max(j => j.Fitness)));

        _data.Genes = max.Chromosome.ToArray();
    }
Esempio n. 24
0
        public static void DoUpdate(GameTime gameTime)
        {
            if ((ElapsedGenerationTime > GenerationTime && GenerationTime != 0) || !AnyoneAlive())
            {
                // GENETIC ALGORITHM THIS SHIT

                thisEvolution.AddGeneration(new Generation(CurrentGeneration));


                if (CurrentGeneration.Count > 0)
                {
                    List <Evolvi> sorted = SortFittest();

                    int root = (int)Math.Sqrt(sorted.Count);

                    sorted = sorted.OrderByDescending(x => x.Energy).ToList();

                    List <Evolvi> newGen = new List <Evolvi>();

                    while (newGen.Count < evolviAmount)
                    {
                        Evolvi e = sorted.First().Crossbreed(sorted.First());
                        e.Mutate(mutationRate);

                        newGen.Add(e);

                        Thread.Sleep(10);
                    }

                    CurrentGeneration.Clear();

                    CurrentGeneration = newGen;
                }
                else
                {
                    Random RNG = new Random();

                    Evolvi e = new Evolvi(new Vector2(RNG.Next(0, 2000), RNG.Next(0, 2000)));

                    for (int i = 0; i < evolviAmount; i++)
                    {
                        CurrentGeneration.Add(e.Clone());

                        Thread.Sleep(10);
                    }
                }


                ElapsedGenerationTime = 0;
                Generation++;


                OnNewGeneration(null, EventArgs.Empty);
            }

            ElapsedGenerationTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

            List <Evolvi> deadEvolvis = new List <Evolvi>();

            foreach (Evolvi evolvi in CurrentGeneration)
            {
                if (!evolvi.Dead)
                {
                    if (evolvi.Energy <= 0)
                    {
                        evolvi.Dead = true;
                    }

                    Input[] inpts   = new Input[evolvi.AreasOfVision + 1];
                    int     indexer = 0;

                    if (Math.Abs(evolvi.AngleDegrees) > 360)
                    {
                        evolvi.AngleDegrees = 0;
                    }

                    float anglePerAreaOfVision = (float)evolvi.FOV / (float)(evolvi.AreasOfVision + 1);

                    for (float i = -evolvi.FOV / 2f; i < (evolvi.FOV / 2f); i += anglePerAreaOfVision)
                    {
                        inpts[indexer] = new Input();

                        Vector2 start = evolvi.Position;
                        Vector2 end;

                        float xDiff = (float)Math.Cos(evolvi.AngleRadians + MathHelper.ToRadians(i)) * evolvi.VisionRange;
                        float yDiff = (float)Math.Sin(evolvi.AngleRadians + MathHelper.ToRadians(i)) * evolvi.VisionRange;

                        end = start + new Vector2(xDiff, yDiff);
                        inpts[indexer].value = 0;

                        Vector2 dir = new Vector2(xDiff, yDiff);
                        dir.Normalize();

                        Ray ray = new Ray(new Vector3(start, 0), new Vector3(dir, 0));

                        float angle = (float)Math.Atan2(dir.Y, dir.X);

                        List <DistanceEvaluator> ends = new List <DistanceEvaluator>();

                        float intersectionToWall = RayIntersectsAWall(ray);

                        foreach (Food food in CurrentFood)
                        {
                            if (evolvi.CollisionBox.Intersects(food.CollisionBox))
                            {
                                evolvi.Energy += food.Nutrition;
                                evolvi.FoodEaten++;

                                Random RNG = new Random();

                                food.Position = new Vector2(RNG.Next(40, 2000 - 80), RNG.Next(40, 2000 - 80));
                                //food.CollisionBox = new Rectangle(food.Position.ToPoint(), food.TextureFood.Bounds.Size);
                                //food.BoundingBox = new BoundingBox(new Vector3(food.Position, 0), new Vector3(food.Position + food.CollisionBox.Size.ToVector2(), 0));

                                bool done = false;

                                while (!done)
                                {
                                    bool intersects = false;

                                    foreach (Food secondFood in CurrentFood)
                                    {
                                        if (food != secondFood)
                                        {
                                            if (food.CollisionBox.Intersects(secondFood.CollisionBox))
                                            {
                                                intersects = true;
                                            }
                                        }
                                    }

                                    if (!intersects)
                                    {
                                        done = true;
                                    }
                                    else
                                    {
                                        food.Position = new Vector2(RNG.Next(20, 2000 - 20), RNG.Next(20, 2000 - 20));
                                        //food.CollisionBox = new Rectangle(food.Position.ToPoint(), food.TextureFood.Bounds.Size);
                                        //food.BoundingBox = new BoundingBox(new Vector3(food.Position, 0), new Vector3(food.Position + food.CollisionBox.Size.ToVector2(), 0));
                                    }
                                }
                            }

                            if (ray.Intersects(food.BoundingBox) != 0)
                            {
                                if (ray.Intersects(food.BoundingBox) < intersectionToWall)
                                {
                                    if (ray.Intersects(food.BoundingBox) < evolvi.VisionRange)
                                    {
                                        float?dist = ray.Intersects(food.BoundingBox);

                                        ends.Add(new DistanceEvaluator((1f - (dist.Value / evolvi.VisionRange)) * (food.Nutrition / 50f), new Vector2((float)(Math.Cos(angle) * dist), (float)(Math.Sin(angle) * dist)) + start));
                                    }
                                }
                                else
                                {
                                    if (intersectionToWall < evolvi.VisionRange)
                                    {
                                        float?dist = intersectionToWall;

                                        ends.Add(new DistanceEvaluator(-(1 - (dist.Value / evolvi.VisionRange)), new Vector2((float)(Math.Cos(angle) * dist), (float)(Math.Sin(angle) * dist)) + start));
                                    }
                                }
                            }
                        }

                        if (ends.Count > 0)
                        {
                            List <DistanceEvaluator> sortedByDist = ends.OrderBy(x => x.Distance).ToList();

                            end = sortedByDist.Last().End;
                            inpts[indexer].value = sortedByDist.Last().Distance;
                        }

                        inpts[indexer].start = start;
                        inpts[indexer].end   = end;

                        indexer++;
                    }

                    evolvi.Update(inpts);
                }
            }
        }
 private void AddRow(Borders border)
 {
     CurrentGeneration.AddRow(border);
     NextGeneration.AddRow(border);
 }
Esempio n. 26
0
        public static List <Evolvi> SortFittest()
        {
            List <Evolvi> sorted = CurrentGeneration.OrderBy(x => x.Energy).ToList();

            return(sorted);
        }
Esempio n. 27
0
 public List <DNA> GetPopulation()
 {
     return(CurrentGeneration.ToList());
 }
Esempio n. 28
0
        public void NewGeneration()
        {
            if (CurrentGeneration.Count <= 0)
            {
                return;
            }

            newGeneration = new List <Specimen>();
            oldGeneration = new List <Specimen>();
            List <Specimen> bestOfTheBest = new List <Specimen>();

            allGenerations.Add(CurrentGeneration);

            for (int i = 0; i < CurrentGeneration.Count; i++)
            {
                for (int j = 0; j < CurrentGeneration.Count; j++)
                {
                    if (i == j)
                    {
                        j++;
                    }
                    if (j == CurrentGeneration.Count)
                    {
                        break;
                    }

                    var firstParent  = CurrentGeneration[i];
                    var secondParent = CurrentGeneration[j];

                    var child = firstParent.CrossoverWith(secondParent);
                    if (RandomForGA.Generator.NextDouble() < Parameters.MutationRate)
                    {
                        child.Mutate(Parameters.MutationAmplitude);
                    }


                    newGeneration.Add(child);
                }
            }

            for (int i = 0; i < CurrentGeneration.Count; i++)
            {
                oldGeneration.Add(CurrentGeneration[i]);
            }

            CurrentGeneration.Clear();
            for (int i = 0; i < oldGeneration.Count; i++)
            {
                CurrentGeneration.Add(oldGeneration[i]);
            }

            for (int i = 0; i < newGeneration.Count; i++)
            {
                CurrentGeneration.Add(newGeneration[i]);
            }

            CalculateFitness();

            CurrentGeneration.Sort((a, b) => population.FittingFunction(a).CompareTo(population.FittingFunction(b)));

            for (int i = 0; i < Parameters.PopulationSize; i++)
            {
                bestOfTheBest.Add(CurrentGeneration[i]);
            }
            CurrentGeneration = bestOfTheBest;
            GenerationNum++;
        }
Esempio n. 29
0
        public void RunEpoch()
        {
            List <Chromosome> newGeneration = new List <Chromosome>();

            newGeneration.AddRange(CurrentGeneration.OrderBy(x => x.Fitness).Take((int)(CurrentGeneration.Count * ElitismRate)));

            while (newGeneration.Count < CurrentGeneration.Count)
            {
                //Selection

                Tuple <Chromosome, Chromosome> parents = Selection.Select(CurrentGeneration);

                Tuple <Chromosome, Chromosome> children;

                //Crossover

                if (random.NextDouble() < CrossoverRate)
                {
                    children = parents.Item1.Crossover(parents.Item2);

                    children.Item1.FitnessOutdated = true;
                    children.Item2.FitnessOutdated = true;

                    double parentAverage = (parents.Item1.Fitness + parents.Item2.Fitness) / 2;

                    children.Item1.Fitness = parentAverage;
                    children.Item2.Fitness = parentAverage;

                    children.Item1.FitnessOutdated = true;
                    children.Item2.FitnessOutdated = true;

                    if (random.NextDouble() < 0.5)
                    {
                        children.Item1.Priority = parents.Item1.Priority;
                        children.Item2.Priority = parents.Item2.Priority;
                    }
                    else
                    {
                        children.Item1.Priority = parents.Item2.Priority;
                        children.Item2.Priority = parents.Item1.Priority;
                    }

                    double variance          = (Math.Pow(parents.Item1.Fitness - parentAverage, 2) + Math.Pow(parents.Item2.Fitness - parentAverage, 2)) / 2;
                    double stdDev            = Math.Sqrt(variance);
                    double fitnessDifference = Math.Abs(parents.Item1.Fitness - parents.Item2.Fitness);
                    children.Item1.Priority += variance;
                    children.Item2.Priority += variance;
                }
                else
                {
                    children = new Tuple <Chromosome, Chromosome>((Chromosome)parents.Item1.Clone(), (Chromosome)parents.Item2.Clone());
                }

                //Mutation
                if (random.NextDouble() < MutationRate)
                {
                    children.Item1.Mutate();
                    children.Item1.FitnessOutdated = true;
                    children.Item1.Priority       += MutationWeigth;
                }
                if (random.NextDouble() < MutationRate)
                {
                    children.Item2.Mutate();
                    children.Item2.FitnessOutdated = true;
                    children.Item2.Priority       += MutationWeigth;
                }

                newGeneration.Add(children.Item1);

                //Sometimes only one child can be added
                if (newGeneration.Count == CurrentGeneration.Count)
                {
                    newGeneration.Add(children.Item2);
                }
            }
            CurrentGeneration = new Generation(newGeneration);
            EvaluatePopulation();
        }
 private void AddColumn(Borders border)
 {
     CurrentGeneration.AddColumn(border);
     NextGeneration.AddColumn(border);
 }