Beispiel #1
0
        public GeneticAlgorithmResult <TGeneSequence> Start()
        {
            var keepRunning = true;
            var session     = new GeneticAlgorithmSession <TGeneSequence>();

            // Create the initial starting population
            var startingPopulation = new List <Chromosome <TGeneSequence> >();

            for (var i = 0; i < _initialPopulation; i++)
            {
                startingPopulation.Add(_populationFactory.Create());
            }

            session.CurrentPopulation = startingPopulation;
            _currentSession           = session;

            // Calculate the initial fitness score of each chromosome
            CalculateFitness();

            var bestSelection = _currentSession.CurrentPopulation.OrderByDescending(x => x.FitnessScore).ToList();

            Console.WriteLine($"Running session: {session}. Current population: {_currentSession.CurrentPopulation.Count} Best fitness score: {bestSelection.First().FitnessScore}");

            while (keepRunning)
            {
                // Run one evolve generation
                Evolve();

                bestSelection = _currentSession.CurrentPopulation.OrderByDescending(x => x.FitnessScore).ToList();
                Console.WriteLine($"Running session: {session}. Current population: {_currentSession.CurrentPopulation.Count} Best fitness score: {bestSelection.First().FitnessScore}");

                // Check if we should keep on running yes/ no
                keepRunning = !_termination.ShouldTerminate(session);
            }

            var newResult = new GeneticAlgorithmResult <TGeneSequence>(new ReadOnlyCollection <Chromosome <TGeneSequence> >(bestSelection));

            return(newResult);
        }
Beispiel #2
0
        public async Task Evolve(ITermination <TIndividual, TGeneStructure, TGene> termination,
                                 CancellationToken cancellationToken)
        {
            termination.Algorithm = this;
            if (!IsInitialized)
            {
                Initialize();
            }

            while (!termination.ShouldTerminate())
            {
                await EvolveOneGeneration();

                Update();
                OnGenerationProgress(this);
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
            }

            Statistics.Finish();
            OnTermination(this);
        }