Example #1
0
        public async Task <Genome> FindPathAsync(Roteiro map, Genome seed = null)
        {
            if (Mutate == null || Crossover == null || Fitness == null || Selection == null)
            {
                throw new System.Exception("GA cant run without all operators");
            }

            var locals = map.Destinations.ToList();

            locals.Add(map.Depot);
            await routeService.Prepare(locals);

            var rand      = RandomSingleton.Instance;
            var startNode = map.Depot;

            Populations.Clear();

            var popusize = PopulationSize;

            if (seed != null)
            {
                Populations.Add(seed);
                popusize--;
            }

            Populations.AddRange(
                Enumerable.Range(0, popusize)
                .Select(_ => Genome.Generator(map, Settings)));

            await CalcFitness();

            for (int i = 0; i < GenerationLimit; i++)
            {
                var newpopulations = new List <Genome>();

                for (int j = 0; j < BestSolutionToPick; j++)
                {
                    newpopulations.Add(Populations[j]);
                }

                while (newpopulations.Count < Populations.Count)
                {
                    if (newpopulations.Any(e => e.Trucks.SelectMany(l => l.Locals).Count() != map.Destinations.Count))
                    {
                        throw new System.Exception();
                    }

                    // Selection
                    var(nodemom, nodedad) = Selection.SelectCouple(Populations);

                    // CrossOver
                    var sons = Crossover.Make(nodemom, nodedad);

                    // Mutation
                    sons = sons.Select(s => Mutate.Apply(s)).ToArray();

                    newpopulations.AddRange(sons);
                }
                Populations = newpopulations.ToList();

                await CalcFitness();

                Best = Populations.First();
            }

            return(Best);
        }