Exemplo n.º 1
0
        public void SetUnitPosition(int id, Coordinates coordinates)
        {
            try
            {
                var unit = PopulationList.FirstOrDefault(u => u.Id == id);
                if (unit == null || unit.Id == 0)
                {
                    unit = PopulationList.FirstOrDefault(u => u.Id == 0);
                    if (unit == null)
                    {
                        throw new Exception("SetUnitPosition: unit not found");
                    }
                    // Cas où il s'agit d'une nouvelle unité qui n'a pas encore d'Id
                    else
                    {
                        unit.Id = id;
                    }
                }

                unit.Position = coordinates;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="worker"></param>
        /// <param name="resource"></param>
        public void FetchResource(int workerId, int buildingId)
        {
            if (buildingId == 0 || workerId == 0)
            {
                throw new ArgumentNullException($"Manager FetchResource: workerId = {workerId} or buildingId = {buildingId} is missing");
            }

            // TODO: faire un try/catch pour valider le workerId comme étant un Id de Worker
            var worker   = PopulationList.FirstOrDefault(wk => wk.Id == workerId) as Worker;
            var building = BuildingList.FirstOrDefault(bld => bld.Id == buildingId) as PassiveBuilding;

            if (building == null || worker == null)
            {
                throw new ArgumentException("Manager FetchResource: workerId or buildingId does not exist");
            }

            // Annule la tâche en cours
            CancelTask(workerId);

            // Créé la tâche de collecter les ressources
            worker.FetchResource(building);

            // Capte l'evénement de collecte de ressources par ce worker
            worker.ResourceCollected += OnWorkerCompletedCollect;
            // worker.ResourceFetched += AddResourcesToStock;
        }
Exemplo n.º 3
0
        public void RunGenerations(int iterations, List <double[]> inputTrainSet, List <double[]> outputTarget, int maxAge)
        {
            _inputTrainSet = inputTrainSet;
            _outputTarget  = outputTarget;

            for (int i = 0; i < iterations; i++)
            {
                EvaluatePopulation();
                SortPopulation();
                //CopyRightKill();
                if (PopulationList.First().Error <= 0.1)
                {
                    break;
                }
                PrintBestIndividualError(i);
                SurvivalOfTheFitest(0.01d, PopulationSize, maxAge);
                Mutation(0.05d, 0.1d);
                CrossPopulation();
                DieOfAge(maxAge);
            }
            EvaluatePopulation();
            SortPopulation();
            PrintBestIndividualError(iterations);
            Console.WriteLine("End...");
        }
Exemplo n.º 4
0
        private void readFile()
        {
            string[] lines = File.ReadAllLines("USPopulation.txt");
            if (lines.Length != LAST_YEAR - FIRST_YEAR + 1)
            {
                MessageBox.Show("Wrong number of lines in input file");
                Application.Current.Shutdown();
            }
            int year = FIRST_YEAR;

            foreach (string line in lines)
            {
                try
                {
                    years.Add(year, int.Parse(line));
                    dataList.Add(new KeyValuePair <int, int>(year, int.Parse(line)));
                    PopulationList.Add("The population in " + year + " is " + line);
                }
                catch (Exception)
                {
                    MessageBox.Show("Incorrect data in input file");
                    Application.Current.Shutdown();
                }
                year++;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Annule toutes les tâches en cours d'un worker
        /// </summary>
        /// <param name="workerId"></param>
        public void CancelTask(int workerId)
        {
            // TODO: faire un try/catch pour valider le workerId comme étant un Id de Worker
            var worker = PopulationList.FirstOrDefault(wk => wk.Id == workerId) as Worker;

            if (worker.IsWorking)
            {
                worker.CancelAllActions();
            }
        }
Exemplo n.º 6
0
 private void DieOfAge(int maxAge)
 {
     if (PopulationList.Exists(x => x.Age > maxAge))
     {
         PopulationList = PopulationList.OrderBy(x => x.Age).ToList();
         NeuronNet firstOld = PopulationList.First(x => x.Age > maxAge);
         int       index    = PopulationList.IndexOf(firstOld);
         PopulationList.RemoveRange(index, PopulationList.Count - index);
         PopulationList = PopulationList.OrderBy(x => x.Error).ToList();
     }
 }
Exemplo n.º 7
0
        private void SurvivalOfTheFitest(double fatality, int populationSize, int maxAge)
        {
            if (PopulationList.Count > populationSize)
            {
                PopulationList.RemoveRange(populationSize, PopulationList.Count - populationSize);
            }
            int casualityNumber = (int)Math.Round(PopulationList.Count * fatality);

            for (int i = PopulationList.Count - 1; i >= PopulationList.Count - casualityNumber; i--)
            {
                PopulationList[i].RandomizeWeights(MinWeightValue, MaxWeightValue);
            }
        }
Exemplo n.º 8
0
        public GeneticAlgorithm(int[] shape, int populationSize, Random rnd, double minWeightValue, double maxWeightValue, double[] inputExample)
        {
            PopulationSize = populationSize;
            Rnd            = rnd;
            MinWeightValue = minWeightValue;
            MaxWeightValue = maxWeightValue;
            InputExample   = inputExample;
            Shape          = shape;

            for (int i = 0; i < populationSize; i++)
            {
                PopulationList.Add(new NeuronNet(shape, Rnd));
            }
            foreach (NeuronNet neuronNet in PopulationList) //randomize individuals
            {
                neuronNet.SetInputLayer(inputExample);
                neuronNet.RandomizeWeights(MinWeightValue, MaxWeightValue);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Worker"></param>
        private void AddWorkerToList(Worker worker)
        {
            // Vérifie si le nombre de slots de populaton est suffisant
            // avant de créer l'unité
            try
            {
                if (CheckFreeSlotInPopulation(worker))
                {
                    PopulationList.Add(worker);
                    PopulationChanged(this, new PopulationChangedEventArgs {
                        ActualPopulation = PopulationList.Sum(x => x.PopulationSlots), Unit = worker
                    });
                }
            }

            catch (NotEnoughUnitSlotsAvailableException)
            {
                throw;
            }
        }
Exemplo n.º 10
0
        private void CopyRightKill()
        {
            List <NeuronNet> deleteList = new List <NeuronNet>();

            foreach (NeuronNet neuronNet in PopulationList)
            {
                if (!deleteList.Any(x => Math.Abs(x.Error - neuronNet.Error) < 0))
                {
                    foreach (NeuronNet deleteNet in PopulationList.FindAll(x => { return(Math.Abs(x.Error - neuronNet.Error) < 0.0001); }))
                    {
                        deleteList.Add(deleteNet);
                    }
                    deleteList.Remove(neuronNet);
                }
            }
            foreach (NeuronNet neuronNet in deleteList)
            {
                PopulationList.Remove(neuronNet);
            }
        }
Exemplo n.º 11
0
 public void Remove(T element)
 {
     PopulationList.Remove(element);
 }
Exemplo n.º 12
0
 public void Add(T element)
 {
     PopulationList.Add(element);
 }
Exemplo n.º 13
0
        public T GetAtIndex(int index)
        {
            HelperFunctions.CheckIndex(index, PopulationList.Count);

            return(PopulationList.ElementAt(index));
        }
Exemplo n.º 14
0
 public IEnumerator <T> GetEnumerator()
 {
     return(PopulationList.GetEnumerator());
 }
Exemplo n.º 15
0
        private void NearGenesCrossWithOffspring(NeuronNet individualA, NeuronNet individualB)
        {
            NeuronNet offspring  = new NeuronNet(Shape, Rnd);
            double    extraRange = 0.1;

            offspring.SetInputLayer(InputExample);
            if (individualA.Layers.Count != individualB.Layers.Count)
            {
                throw new Exception("Different layer size. Can not cross");
            }
            for (int i = 0; i < individualA.Layers.Count; i++)
            {
                if (individualA.Layers[i].Neurons.Count != individualB.Layers[i].Neurons.Count)
                {
                    throw new Exception("Different neuron size. Can not cross");
                }
                for (int j = 0; j < individualA.Layers[i].Neurons.Count; j++)
                {
                    double auxBiasA = individualA.Layers[i].Neurons[j].Bias;
                    double auxBiasB = individualB.Layers[i].Neurons[j].Bias;
                    double maximumBias;
                    double minimumBias;

                    if (auxBiasA > auxBiasB)
                    {
                        maximumBias = auxBiasA + (auxBiasA * extraRange);
                        minimumBias = auxBiasB - (auxBiasA * extraRange);
                    }
                    else
                    {
                        maximumBias = auxBiasB + (auxBiasA * extraRange);
                        minimumBias = auxBiasA - (auxBiasA * extraRange);
                    }

                    offspring.Layers[i].Neurons[j].Bias = Rnd.NextDouble() * (maximumBias - minimumBias) + minimumBias;

                    if (individualA.Layers[i].Neurons[j].Dendrites.Count != individualB.Layers[i].Neurons[j].Dendrites.Count)
                    {
                        throw new Exception("Different dendrite count. Can not cross");
                    }
                    for (int k = 0; k < individualA.Layers[i].Neurons[j].Dendrites.Count; k++)
                    {
                        double auxDendriteWeightA = individualA.Layers[i].Neurons[j].Dendrites[k].Weight;
                        double auxDendriteWeightB = individualB.Layers[i].Neurons[j].Dendrites[k].Weight;
                        double maximum;
                        double minimum;

                        if (auxDendriteWeightA > auxDendriteWeightB)
                        {
                            maximum = auxDendriteWeightA + (auxDendriteWeightA * extraRange);
                            minimum = auxDendriteWeightB - (auxDendriteWeightA * extraRange);
                        }
                        else
                        {
                            maximum = auxDendriteWeightB + (auxDendriteWeightA * extraRange);
                            minimum = auxDendriteWeightA - (auxDendriteWeightA * extraRange);
                        }
                        offspring.Layers[i].Neurons[j].Dendrites[k].Weight = Rnd.NextDouble() * (maximum - minimum) + minimum;
                    }
                }
            }
            PopulationList.Add(offspring);
        }
Exemplo n.º 16
0
 private void SortPopulation()
 {
     PopulationList = PopulationList.OrderBy(x => x.Error).ToList();
 }
Exemplo n.º 17
0
        private void PrintBestIndividualError(int iteration)
        {
            double error = PopulationList.First().Error;

            Console.WriteLine(error + " iteration N°: " + iteration);
        }