Beispiel #1
0
 public GA(Citizen citizenTemplate)
 {
     Population             = new List <ICitizen>();
     defaultCitizenTemplate = citizenTemplate;
     Observers = new List <IObserver <TrainingUpdateEventArgs> >();
 }
Beispiel #2
0
        /// <summary>
        /// The training method called to run the course of the algorithm (ie. Generate Population, selection, crossover, mutation, repeat)
        /// </summary>
        /// <param name="iterations">Total number of iterations of populations to complete</param>
        /// <param name="populationSize">Population size</param>
        /// <param name="citizenTemplate">The template citizen to use for generation</param>
        /// <returns></returns>
        public CancellationTokenSource Train(int iterations, int populationSize = 100, Citizen citizenTemplate = null)
        {
            GeneratePopulation(citizenTemplate ?? defaultCitizenTemplate, populationSize);  // Generates the initial Population

            // Handles the abortion of the training procedure if ended prematurely
            CancellationTokenSource TokenSource = new CancellationTokenSource();
            CancellationToken       token       = TokenSource.Token;

            // Launches the training task in a new thread, that is cancellable
            Task.Factory.StartNew(() =>
            {
                token.ThrowIfCancellationRequested();   // Tests if the task has already been cancelled

                // Handles the cancellation event asynchronously
                Task.Factory.StartNew(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        token.ThrowIfCancellationRequested();
                        Thread.Sleep(100);
                    }
                });

                TrainingRoutine(iterations);    // Executes the training routine
            }, token);

            return(TokenSource);
        }