Example #1
0
 public static async Task Evolve(
     this IGeneticAlgorithm genetic,
     IPopulation population,
     CancellationToken token)
 {
     await genetic.EvolveUntil(population, _ => false, token);
 }
Example #2
0
 public GameController(IDebug debug, IUiObject uiObject, IGeneticAlgorithm ga, IMainGameObject mainGameObject)
 {
     this.debug          = debug;
     this.uiObject       = uiObject;
     this.ga             = ga;
     this.mainGameObject = mainGameObject;
 }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;

            //Console.WriteLine("Best Chromosome Fitness: {0}", bestFitness);

            if (m_lastFitness == bestFitness)
            {
                //Console.WriteLine("Best Chromosome Fitness Value is still same");
                m_stagnantGenerationsCount++;
            }
            else
            {
                //Console.WriteLine("Best Chromosome Fitness Value is changed");
                m_stagnantGenerationsCount = 1;
            }
            //Console.WriteLine("Stagnant Generation Count: {0}", m_stagnantGenerationsCount);

            m_lastFitness = bestFitness;

            //if (m_stagnantGenerationsCount >= ExpectedStagnantGenerationsNumber)
            //{
            //    Console.WriteLine("Stagnant Generation Count({0}) reached expected stagnant generation number({1})", m_stagnantGenerationsCount, ExpectedStagnantGenerationsNumber);
            //}
            //else
            //{
            //    Console.WriteLine("Expected stagnant generation number({0}) is not reached yet.", ExpectedStagnantGenerationsNumber);
            //}

            return(m_stagnantGenerationsCount >= ExpectedStagnantGenerationsNumber);
        }
Example #4
0
        /// <summary>
        /// Runs one generation of genetic evolution on the population using the supplied solver.
        /// </summary>
        /// <param name="algorithm">Genetic algorithm to use during evolution.</param>
        public virtual void Evolve(IGeneticAlgorithm algorithm)
        {
            var nextGeneration = algorithm.Evolve(this._Chromosomes, this.FitnessMetric, this.FitnessMode);

            int size          = (this.IsDynamic ? nextGeneration.Count() : this._Chromosomes.Count);
            var newGeneration = new IChromosome[size];

            for (int i = 0; i < size; i++)
            {
                IChromosome current;

                if (i >= nextGeneration.Count() && !this.IsDynamic)
                {
                    current = this.Random();
                }
                else
                {
                    current = nextGeneration.ElementAt(i);
                }

                newGeneration[i] = current;
            }

            this.Apply(newGeneration);
        }
Example #5
0
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            /*var ga = geneticAlgorithm as GeneticAlgorithm;
             *
             * var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;
             *
             * if (bestFitness <= m_lastFitness)
             * {
             *  m_stagnantGenerationsCount++;
             *  Console.WriteLine($"Fitness stagnant for {m_stagnantGenerationsCount} generations.");
             * }
             * else
             * {
             *  m_stagnantGenerationsCount = 1;
             * }
             *
             * m_lastFitness = bestFitness;
             *
             *
             * foreach (var c in ga.Population.CurrentGeneration.Chromosomes)
             * {
             *  c.Fitness = null;
             * }
             *
             * return m_stagnantGenerationsCount >= 50;*/

            return(false);
        }
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var ga = geneticAlgorithm as GeneticAlgorithm;

            var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;

            if (bestFitness <= m_lastFitness)
            {
                m_stagnantGenerationsCount++;
                Debug.Log($"Fitness stagned for {m_stagnantGenerationsCount} generations.");
            }
            else
            {
                m_stagnantGenerationsCount = 1;
            }

            m_lastFitness = bestFitness;


            foreach (var c in ga.Population.CurrentGeneration.Chromosomes)
            {
                c.Fitness = null;
            }

            return(m_stagnantGenerationsCount >= 50);
        }
        private void OnGeneticAlgorithmTerminated(object sender, GeneticAlgorithmTerminatedEventArgs args)
        {
            ConsoleEx.WriteLineGreen("\n\nGenetic algorithm finished because one of the stopping criteria!");
            ConsoleEx.WriteLine("The final result: ");

            IGeneticAlgorithm <T> ga = sender as IGeneticAlgorithm <T>;

            if (ga != null)
            {
                string timeString = "";
                if (ga.EvolutionTime < TimeSpan.FromSeconds(1))
                {
                    timeString = ga.EvolutionTime.TotalMilliseconds + " ms";
                }
                else if (ga.EvolutionTime < TimeSpan.FromMinutes(1))
                {
                    timeString = ga.EvolutionTime.TotalSeconds + " s";
                }
                else
                {
                    timeString = (int)ga.EvolutionTime.TotalMinutes + " m " + ga.EvolutionTime.Seconds + " s";
                }

                Console.Write(string.Format(
                                  "Time: {0, -10} Generations: {1, -8} Evaluations: {2, -10} Best fitness: {3, -20} Best individual: {4}",
                                  timeString, ga.CurrentGeneration, ga.FitnessEvaluations, ga.BestIndividual.Fitness, ga.BestIndividual
                                  ));
            }
        }
 public TextOptimization(IStringPatternService stringPatternService, IGeneticAlgorithm <StringPatternProcessor> geneticAlgorithm, IRawTextRepository rawTextRepository, ILog log, ITextOptimizationConfig textOptimizationConfig)
 {
     this.stringPatternService = stringPatternService;
     this.geneticAlgorithm     = geneticAlgorithm;
     this.rawTextRepository    = rawTextRepository;
     this.log = log;
     this.textOptimizationConfig = textOptimizationConfig;
 }
Example #9
0
        private ISpecies[] epochStartSpecies; //temporary variable with all the simulated species of an epoch

        public GeneticAlgorithmTrainerWindow(IGeneticAlgorithm geneticAlgorithm)
        {
            InitializeComponent();

            this.geneticAlgorithm = geneticAlgorithm;

            geneticAlgorithm.onScoresCalculated += (o, a) => { epochStartSpecies = geneticAlgorithm.Population.ToArray(); };
        }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        public bool HasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            ExceptionHelper.ThrowIfNull("geneticAlgorithm", geneticAlgorithm);

            m_hasReached = PerformHasReached(geneticAlgorithm);

            return m_hasReached;
        }
Example #11
0
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        public bool HasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            ExceptionHelper.ThrowIfNull("geneticAlgorithm", geneticAlgorithm);

            m_hasReached = PerformHasReached(geneticAlgorithm);

            return(m_hasReached);
        }
Example #12
0
        public string Generate(IGeneticAlgorithm ga)
        {
            // Generate functions.
            IFitness myFitness;
            string   originalTargetString = _targetParams.TargetString;
            string   program;
            string   appendCode = "";

            // Split string into terms.
            string[] parts = _targetParams.TargetString.Split(new char[] { ' ' });

            // Build corpus of unique terms to generate functions.
            Dictionary <string, string> terms = new Dictionary <string, string>();

            foreach (string part in parts)
            {
                if (!string.IsNullOrEmpty(part))
                {
                    terms[part] = part;
                }
            }

            foreach (string term in terms.Values)
            {
                _targetParams.TargetString = term;

                // Get the target fitness for this method.
                myFitness = _getFitnessFunc();

                _targetParams.TargetFitness = myFitness.TargetFitness;

                // Run the genetic algorithm and get the best brain.
                program = GAManager.Run(ga, _fitnessFunc, _generationFunc);

                // Trim extraneous loop instructions from the end.
                program = program.Replace("[]", "");

                appendCode += program + "@";

                // Reset the target fitness.
                myFitness.ResetTargetFitness();
                _bestStatus.Fitness        = 0;
                _bestStatus.TrueFitness    = 0;
                _bestStatus.Output         = "";
                _bestStatus.LastChangeDate = DateTime.Now;
                _bestStatus.Program        = "";
                _bestStatus.Ticks          = 0;

                // Notify parent of progress.
                _onStepComplete(appendCode, term);
            }

            // Restore target string.
            _targetParams.TargetString = originalTargetString;

            return(appendCode);
        }
Example #13
0
 public GeneticAlgorithmRunner(
     IGeneticAlgorithm <T> geneticAlgorithm, IOptions <GeneticOptions> geneticOptions,
     IAlgorithmOutputManager <T> outputManager)
 {
     this.random           = new Random();
     this.geneticOptions   = geneticOptions.Value;
     this.geneticAlgorithm = geneticAlgorithm;
     this.outputManager    = outputManager;
 }
Example #14
0
        public static async Task <GeneticEvolutionStates> TryEvolve(
            this IGeneticAlgorithm genetic,
            IPopulation population,
            CancellationToken token)
        {
            var(result, _) = await genetic.TryEvolveUntil(population, _ => false, token);

            return(result);
        }
Example #15
0
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            if (geneticAlgorithm?.BestChromosome?.Fitness != null &&
                geneticAlgorithm.BestChromosome.Fitness.Value >= _fitnessThreshold)
            {
                return(true);
            }

            return(base.PerformHasReached(geneticAlgorithm));
        }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        /// <returns>
        /// True if termination has been reached, otherwise false.
        /// </returns>
        public bool HasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            ExceptionHelper.ThrowIfNull("geneticAlgorithm", geneticAlgorithm);

            if (Terminations.Count < m_minOperands)
            {
                throw new InvalidOperationException("The {0} needs at least {1} terminations to perform. Please, add the missing terminations.".With(GetType().Name, m_minOperands));
            }

            return PerformHasReached(geneticAlgorithm);
        }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var ga = geneticAlgorithm as GeneticAlgorithm;

            if (ga == null)
            {
                throw new InvalidCastException("I am expecting genetic algorithm to be of Custom type!");
            }

            return(ga.Population.FruitlessGenerationsCount >= _fruitlessGenerations);
        }
Example #18
0
 public override bool CheckTermination(IGeneticAlgorithm ga)
 {
     if (ga.GenerationNumber >= maxGenerations)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #19
0
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        /// <returns>
        /// True if termination has been reached, otherwise false.
        /// </returns>
        public bool HasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            ExceptionHelper.ThrowIfNull("geneticAlgorithm", geneticAlgorithm);

            if (Terminations.Count < m_minOperands)
            {
                throw new InvalidOperationException("The {0} needs at least {1} terminations to perform. Please, add the missing terminations.".With(GetType().Name, m_minOperands));
            }

            return(PerformHasReached(geneticAlgorithm));
        }
        static void Main(string[] args)
        {
            NeuralNetworkConfigurationSettings networkConfig = new NeuralNetworkConfigurationSettings
            {
                NumInputNeurons    = 1,
                NumOutputNeurons   = 1,
                NumHiddenLayers    = 2,
                NumHiddenNeurons   = 3,
                SummationFunction  = new SimpleSummation(),
                ActivationFunction = new TanhActivationFunction()
            };
            GenerationConfigurationSettings generationSettings = new GenerationConfigurationSettings
            {
                UseMultithreading    = true,
                GenerationPopulation = 500
            };
            EvolutionConfigurationSettings evolutionSettings = new EvolutionConfigurationSettings
            {
                NormalMutationRate  = 0.05,
                HighMutationRate    = 0.5,
                GenerationsPerEpoch = 10,
                NumEpochs           = 1000,
                NumTopEvalsToReport = 10
            };
            MutationConfigurationSettings mutationSettings = new MutationConfigurationSettings
            {
                MutateAxonActivationFunction       = true,
                MutateNumberOfHiddenLayers         = true,
                MutateNumberOfHiddenNeuronsInLayer = true,
                MutateSomaBiasFunction             = true,
                MutateSomaSummationFunction        = true,
                MutateSynapseWeights = true
            };
            var random = new RandomWeightInitializer(new Random());
            INeuralNetworkFactory factory          = NeuralNetworkFactory.GetInstance(SomaFactory.GetInstance(networkConfig.SummationFunction), AxonFactory.GetInstance(networkConfig.ActivationFunction), SynapseFactory.GetInstance(new RandomWeightInitializer(new Random()), AxonFactory.GetInstance(networkConfig.ActivationFunction)), SynapseFactory.GetInstance(new ConstantWeightInitializer(1.0), AxonFactory.GetInstance(new IdentityActivationFunction())), random);
            IBreeder            breeder            = BreederFactory.GetInstance(factory, random).Create();
            IMutator            mutator            = MutatorFactory.GetInstance(factory, random).Create(mutationSettings);
            IEvalWorkingSet     history            = EvalWorkingSetFactory.GetInstance().Create(50);
            IEvaluatableFactory evaluatableFactory = new GameEvaluationFactory();

            IStorageProxy proxy  = new NodeJSProxy(1, "http://localhost:3000", "123456789");
            IEpochAction  action = new BestPerformerUpdater(proxy);

            var GAFactory             = GeneticAlgorithmFactory.GetInstance(evaluatableFactory);
            IGeneticAlgorithm evolver = GAFactory.Create(networkConfig, generationSettings, evolutionSettings, factory, breeder, mutator, history, evaluatableFactory, action);

            evolver.RunSimulation();
        }
        public string Generate(IGeneticAlgorithm ga)
        {
            // Generate functions.
            IFitness myFitness;
            string   originalTargetString = _targetParams.TargetString;
            string   program;
            string   appendCode = "";

            // Split string into terms of 3-characters.
            string[] parts = SplitInParts(_targetParams.TargetString, _chunkSize).ToArray();

            // Build corpus of unique terms to generate functions.
            Dictionary <string, string> terms = new Dictionary <string, string>();

            foreach (string part in parts)
            {
                terms[part] = part;
            }

            foreach (string term in terms.Values)
            {
                _targetParams.TargetString = term;

                // Get the target fitness for this method.
                myFitness = _getFitnessFunc();

                _targetParams.TargetFitness = myFitness.TargetFitness;

                // Run the genetic algorithm and get the best brain.
                program = GAManager.Run(ga, _fitnessFunc, _generationFunc);

                appendCode += program + "@";

                // Reset the target fitness.
                myFitness.ResetTargetFitness();
                _bestStatus.Fitness        = 0;
                _bestStatus.TrueFitness    = 0;
                _bestStatus.Output         = "";
                _bestStatus.LastChangeDate = DateTime.Now;
                _bestStatus.Program        = "";
                _bestStatus.Ticks          = 0;
            }

            // Restore target string.
            _targetParams.TargetString = originalTargetString;

            return(appendCode);
        }
Example #22
0
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            //Console.WriteLine("Genetic Algorithm Running Time: {0}", geneticAlgorithm.TimeEvolving);
            //Console.WriteLine("Genetic Algorithm Max Running Time: {0}", MaxTime);

            //if (geneticAlgorithm.TimeEvolving >= MaxTime)
            //{
            //    Console.WriteLine("Genetic Algorithm Running Time reached Max Time to Run.");
            //}
            //else
            //{
            //    Console.WriteLine("Genetic Algorithm has still some time to run.");
            //}

            return(geneticAlgorithm.TimeEvolving >= MaxTime);
        }
        public string Generate(IGeneticAlgorithm ga)
        {
            // Generate functions.
            IFitness myFitness;
            string originalTargetString = _targetParams.TargetString;
            string program;
            string appendCode = "";

            // Split string into terms of 3-characters.
            string[] parts = SplitInParts(_targetParams.TargetString, _chunkSize).ToArray();

            // Build corpus of unique terms to generate functions.
            Dictionary<string, string> terms = new Dictionary<string, string>();
            foreach (string part in parts)
            {
                terms[part] = part;
            }

            foreach (string term in terms.Values)
            {
                _targetParams.TargetString = term;

                // Get the target fitness for this method.
                myFitness = _getFitnessFunc();

                _targetParams.TargetFitness = myFitness.TargetFitness;
                
                // Run the genetic algorithm and get the best brain.
                program = GAManager.Run(ga, _fitnessFunc, _generationFunc);
                
                appendCode += program + "@";

                // Reset the target fitness.
                myFitness.ResetTargetFitness();
                _bestStatus.Fitness = 0;
                _bestStatus.TrueFitness = 0;
                _bestStatus.Output = "";
                _bestStatus.LastChangeDate = DateTime.Now;
                _bestStatus.Program = "";
                _bestStatus.Ticks = 0;
            }

            // Restore target string.
            _targetParams.TargetString = originalTargetString;

            return appendCode;
        }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;

            if (m_lastFitness == bestFitness)
            {
                m_stagnantGenerationsCount++;
            }
            else
            {
                m_stagnantGenerationsCount = 1;
            }

            m_lastFitness = bestFitness;

            return m_stagnantGenerationsCount >= ExpectedStagnantGenerationsNumber;
        }
        public bool HasReached <T>(IGeneticAlgorithm <T> geneticAlgorithm) where T : IChromosome
        {
            double bestFitness = geneticAlgorithm.BestIndividual.Fitness;

            if (_bestFitness == bestFitness)
            {
                _stagnatingGenerations++;
            }
            else
            {
                _stagnatingGenerations = 1;
            }

            _bestFitness = bestFitness;

            return(_stagnatingGenerations >= MaxStagnatingGenerations);
        }
        /// <summary>
        /// Determines whether the specified geneticAlgorithm reached the termination condition.
        /// </summary>
        /// <returns>True if termination has been reached, otherwise false.</returns>
        /// <param name="geneticAlgorithm">The genetic algorithm.</param>
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;

            if (m_lastFitness == bestFitness)
            {
                m_stagnantGenerationsCount++;
            }
            else
            {
                m_stagnantGenerationsCount = 1;
            }

            m_lastFitness = bestFitness;

            return(m_stagnantGenerationsCount >= ExpectedStagnantGenerationsNumber || bestFitness == 0 || geneticAlgorithm.TimeEvolving.TotalSeconds > 60);
        }
Example #27
0
        /// <summary>
        /// Setup the genetic algorithm and run it.
        /// </summary>
        /// <returns>Best brain's output source code</returns>
        public static string Run(IGeneticAlgorithm iga, GAFunction fitnessFunc, OnGeneration generationFunc, Action setupFunc = null, bool resume = false)
        {
            GA ga = (GA)iga;

            if (!resume)
            {
                if (setupFunc != null)
                {
                    // Perform any additional setup for this fitness.
                    setupFunc();
                }

                try
                {
                    // Delete any existing dat file.
                    File.Delete(Directory.GetCurrentDirectory() + "\\my-genetic-algorithm.dat");
                }
                catch (Exception excep)
                {
                    Console.WriteLine("Unable to delete " + Directory.GetCurrentDirectory() + "\\my-genetic-algorithm.dat\n" + excep.Message);
                }

                // Start a new genetic algorithm.
                ga.GAParams.Elitism     = true;
                ga.GAParams.HistoryPath = Directory.GetCurrentDirectory() + "\\history.txt";
                ga.FitnessFunction      = new GAFunction(fitnessFunc);
                ga.OnGenerationFunction = new OnGeneration(generationFunc);
                ga.Go();
            }
            else
            {
                // Load a saved genetic algorithm.
                ga.Load("my-genetic-algorithm.dat");
                ga.Resume(fitnessFunc, generationFunc);
            }

            // Results.
            double[] weights;
            double   fitness;

            ga.GetBest(out weights, out fitness);

            Console.WriteLine("***** DONE! *****");

            return(CommonManager.ConvertDoubleArrayToBF(weights));
        }
Example #28
0
        /// <summary>
        /// Метод, вызываемый после клика на кнопку "OK".
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                switch (Algorithm)
                {
                case GeneticAlgotithmMethod.ClassicGA:
                    ErrorMessageZeroIterationSize();
                    GA = new ClassicGA(
                        IterationSize, PopulationSize,
                        CMethod, CrossoverProbability, DotCrossover,
                        MMethod, MutationProbability, DotMutation,
                        SMethod, CountSelected, CountTour);
                    break;

                case GeneticAlgotithmMethod.GenitorGA:
                    ErrorMessageZeroIterationSize();
                    GA = new GenitorGA(
                        IterationSize, PopulationSize,
                        CMethod, CrossoverProbability, DotCrossover,
                        MMethod, MutationProbability, DotMutation,
                        SMethod, CountSelected, CountTour);
                    break;

                case GeneticAlgotithmMethod.CHCGA:
                    ErrorMessageZeroIterationSize();
                    GA = new CHCGA(
                        IterationSize, PopulationSize,
                        CrossoverProbability,
                        MMethod, DotMutation,
                        MinHemmingDistance);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                return;
            }

            DialogResult = true;
            Close();
        }
 public GeneticCreater(IGeneticAlgorithm geneticAlgorithm, List <Input> inputList, int popopulationSize, float crossingVal, float mutationVal, int numberOfGeneration, int precision = 1)
 {
     if (inputList == null)
     {
         Console.WriteLine("Error : Input list is null !");
         return;
     }
     this.numberOfGeneration = numberOfGeneration;
     this.geneticAlgorithm   = geneticAlgorithm;
     inputSize      = inputList.Count;
     this.inputList = inputList;
     chromosomes    = new List <Chromosome>(popopulationSize);
     AlgorithmRuleValuesCheck(popopulationSize, precision, crossingVal, mutationVal);
     GetInputsBinarySize();
     CreatePopulation();
     NewGenerationCalculater();
     chromosomesWriter(true);
     generations = Chromosome.ProducerGenerations(this);
     Chromosome.GetGenerationThatHaveMaxFitness(generations);
 }
Example #30
0
        public void Setup()
        {
            var uiObject = Substitute.For <IUiObject>();

            ga    = Substitute.For <IGeneticAlgorithm>();
            debug = Substitute.For <IDebug>();


            brain1 = Substitute.For <ICarBrainController>();
            brain2 = Substitute.For <ICarBrainController>();
            brain3 = Substitute.For <ICarBrainController>();
            brain4 = Substitute.For <ICarBrainController>();
            brain5 = Substitute.For <ICarBrainController>();

            mainGameObject = Substitute.For <IMainGameObject>();
            mainGameObject.CreateCarBrainController(Arg.Any <List <decimal> >()).Returns(brain1, brain2, brain3, brain4, brain5);

            controller = new GameController(debug, uiObject, ga, mainGameObject);

            controller.Init(5);
        }
Example #31
0
        protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
        {
            var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;

            if (bestFitness == m_lastFitness)
            {
                m_stagnantGenerationsCount2++;
            }
            else
            {
                m_stagnantGenerationsCount2 = 1;
            }

            if (m_stagnantGenerationsCount2 == 2000)
            {
                List <Question> pitanja = DataAccess.DataAccess.GetInstance().GetQuestionsWhichContainDomainsAndAreSelected(Oblasti);
                if (pitanja.Count != 0)
                {
                    foreach (var p in pitanja)
                    {
                        p.Izabrano = false;
                    }
                    m_stagnantGenerationsCount2 = 1;
                }
            }

            if (bestFitness == 0)
            {
                m_stagnantGenerationsCount1++;
            }
            else
            {
                m_stagnantGenerationsCount1 = 1;
            }

            m_lastFitness = bestFitness;

            return((m_stagnantGenerationsCount1 >= ExpectedStagnantGenerationsNumber) || (m_stagnantGenerationsCount2 >= 2000));
        }
Example #32
0
        /// <summary>
        /// Setup the genetic algorithm and run it.
        /// </summary>
        /// <returns>Best brain's output source code</returns>
        public static string Run(IGeneticAlgorithm iga, GAFunction fitnessFunc, OnGeneration generationFunc, Action setupFunc = null, bool resume = false)
        {
            GA ga = (GA)iga;

            if (!resume)
            {
                if (setupFunc != null)
                {
                    // Perform any additional setup for this fitness.
                    setupFunc();
                }

                // Delete any existing dat file.
                File.Delete(Directory.GetCurrentDirectory() + "\\my-genetic-algorithm.dat");

                // Start a new genetic algorithm.
                ga.GAParams.Elitism = true;
                ga.GAParams.HistoryPath = Directory.GetCurrentDirectory() + "\\history.txt";
                ga.FitnessFunction = new GAFunction(fitnessFunc);
                ga.OnGenerationFunction = new OnGeneration(generationFunc);
                ga.Go();
            }
            else
            {
                // Load a saved genetic algorithm.
                ga.Load("my-genetic-algorithm.dat");
                ga.Resume(fitnessFunc, generationFunc);
            }

            // Results.
            double[] weights;
            double fitness;
            ga.GetBest(out weights, out fitness);

            Console.WriteLine("***** DONE! *****");

            return CommonManager.ConvertDoubleArrayToBF(weights);
        }
Example #33
0
        /// <summary>
        /// Handles the Click event of the startStopButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void startStopButton_Click(object sender, EventArgs e)
        {
            GeneticAlgorithmParams parameters;

            if (startStopButton.Text == "Start")
            {
                startStopButton.Text = "Stop";
                EnableForm(false);

                parameters = (GeneticAlgorithmParams)paramsComboBox.SelectedItem;

                if (parameters.GetType() == typeof(TravellingSalesmanParams))
                {
                    ga = new TravellingSalesmanGA((TravellingSalesmanParams)parameters);
                }
                else
                {
                    ga = new NQueenGA((NQueenParams)parameters);
                }

                ga.SelectionMethod = (SelectionMethod)selectionComboBox.SelectedItem;
                ga.CrossoverMethod = (CrossoverMethod)crossoverComboBox.SelectedItem;
                ga.MutationMethod  = (MutationMethod)mutationComboBox.SelectedItem;

                ga.TerminationMethods.Clear();
                ga.TerminationMethods.Add(new GALib.Termination.SolutionFound());
                ga.TerminationMethods.Add(new GALib.Termination.GenerationLimit((int)terminationNumericUpDown.Value));

                best = null;

                backgroundWorker.RunWorkerAsync();
            }
            else
            {
                stopRequested = true;
            }
        }
Example #34
0
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 /// <returns>
 /// True if termination has been reached, otherwise false.
 /// </returns>
 protected abstract bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm);
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <returns>True if termination has been reached, otherwise false.</returns>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
 {
     return geneticAlgorithm.TimeEvolving >= MaxTime;
 }
 public bool HasReached <T>(IGeneticAlgorithm <T> geneticAlgorithm) where T : IChromosome
 {
     return(geneticAlgorithm.CurrentGeneration >= MaxGenerations);
 }
Example #37
0
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 /// <returns>
 /// True if termination has been reached, otherwise false.
 /// </returns>
 protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
 {
     return Terminations.All(t => t.HasReached(geneticAlgorithm));
 }
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <returns>True if termination has been reached, otherwise false.</returns>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
 {
     return geneticAlgorithm.GenerationsNumber >= ExpectedGenerationNumber;
 }
 public InitialTeamSelectorStrategy(ILogger logger, IGeneticAlgorithm<FitTeam, IList<Player>> geneticTeamSelector)
 {
     _logger = logger;
     _geneticTeamSelector = geneticTeamSelector;
 }
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <returns>True if termination has been reached, otherwise false.</returns>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
 {
     return geneticAlgorithm.BestChromosome.Fitness >= ExpectedFitness;
 }
 public Population(IGeneticAlgorithm genetics)
 {
     _genetics = genetics;
     FitnessStats = new FitnessStats();
 }
 public TransferSelectorStrategy(IGeneticAlgorithm<FitTransferActions, SeasonState> geneticTransferSelector, ILogger logger)
 {
     _geneticTransferSelector = geneticTransferSelector;
     _logger = logger;
 }
 /// <summary>
 /// Determines whether the specified geneticAlgorithm reached the termination condition.
 /// </summary>
 /// <returns>True if termination has been reached, otherwise false.</returns>
 /// <param name="geneticAlgorithm">The genetic algorithm.</param>
 protected abstract bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm);