Exemplo n.º 1
0
        /// <summary>
        /// Add the genres and their associated albums either to the next or a new population
        /// </summary>
        /// <param name="populationIndex"></param>
        /// <param name="genres"></param>
        public void AddToPopulation(int populationIndex, IEnumerable <string> genres)
        {
            // Make sure that there are some genres and albums that have not been seen before
            // Use a List here as having the GenresAlreadyIncluded modifier in the .where seems to cause problems with Linq lazy evaluation
            List <string> newGenres = genres.Where(gen => GenresAlreadyIncluded.Add(gen) == true).ToList();

            if (newGenres.Count > 0)
            {
                // Are there any albums associated with these genres that have not been seen before
                List <Album> newAlbums = GetAlbumsFromGenres(newGenres);
                if (newAlbums.Count > 0)
                {
                    // Add these entries to the next population to the one just used. If the one just used was the last one then create a new population
                    if (populationIndex == (Populations.Count - 1))
                    {
                        // A new population is required
                        Populations.Add(new Population(GenrePopulations.CreatePopulation(Id, Populations.Count, newGenres), newGenres, newAlbums));
                    }
                    else
                    {
                        // Add the genres and albums to the existing Population
                        Populations[populationIndex + 1].Add(newGenres, newAlbums);
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Form the initial population from all the genres and albums that can be reached from the specified initial set of genres
        /// </summary>
        /// <param name="startingGenres"></param>
        public void AddAllReachableGenres(IEnumerable <string> startingGenres)
        {
            List <string> newGenres      = null;
            List <Album>  newAlbums      = null;
            int           expansionCount = 0;

            // Start with the initial genres
            List <string> currentGenres = startingGenres.ToList();

            do
            {
                // Are there any genres that have not been seen before
                newGenres = currentGenres.Where(gen => GenresAlreadyIncluded.Add(gen) == true).ToList();
                if (newGenres.Count > 0)
                {
                    // Are there any albums associated with these genres that have not been seen before
                    newAlbums = GetAlbumsFromGenres(newGenres);
                    if (newAlbums.Count > 0)
                    {
                        // Get all the genres associated with these new albums
                        currentGenres = newAlbums.SelectMany(alb => alb.Genre.Split(';')).ToList();
                    }
                }
            }while ((newGenres.Count > 0) && (newAlbums.Count > 0) && ((FastSpreadLimit == 0) || (++expansionCount < FastSpreadLimit)));

            // Unload the genres and albums from the HashSets and use to generate the first population
            Populations.Add(new Population(GenrePopulations.CreatePopulation(Id, Populations.Count, GenresAlreadyIncluded.ToList()),
                                           GenresAlreadyIncluded.ToList(), Albums.AlbumCollection.Where(alb => AlbumsAlreadyIncluded.Contains(alb.Id))));
        }
            public Chromosomes.IChromosome[] PerformSelection(Populations.IPopulation population, int size)
            {
                //Getting all of the chromosomes that are in population.
                Chromosomes.IChromosome[] individuals = population.GetChromosomes ();

                //Calculating the number of the those chromosomes.
                int sz = individuals.Length;

                //Calculating the fitness of each chromosome.
                double[] f = new double[sz];
                double[] fitnesses = population.GetFitnesses();
                for (int i = 0; i < sz; ++i)
                    f[i] = fitnesses[i];

                //Sorting the population by descending fitness values.
                Sort (individuals, f, 0, sz - 1);

                //Defining the to-be-returned array.
                Chromosomes.IChromosome[] ret = new Chromosomes.IChromosome[size];

                //Selecting the parents from the population and putting them in ret.
                for (int i = 0; i < size; ++i)
                    ret[i] = individuals[i].Clone();

                //Returning the result.
                return ret;
            }
            public Chromosomes.IChromosome[] PerformSelection(Populations.IPopulation population, int size)
            {
                //Getting all of the chromosomes that are in population.
                Chromosomes.IChromosome[] individuals = population.GetChromosomes();

                //Calculating the number of the those chromosomes.
                int sz = individuals.Length;

                //Calculating the fitness of each chromosome.
                double[] f = new double[sz];
                double[] fitnesses = population.GetFitnesses();
                for (int i = 0; i < sz; ++i)
                    f[i] = fitnesses[i];

                //Defining the to-be-returned array.
                Chromosomes.IChromosome[] ret = new Chromosomes.IChromosome[size];

                //Selecting the parents from the population and putting them in ret.
                for (int i = 0; i < size; ++i)
                {
                    int parentidx=-1;
                    for (int j=0;j<TournamentSize;++j){
                        int idx=random.Next(size);
                        if (parentidx==-1||f[parentidx]<f[idx]){
                            parentidx=idx;
                        }
                    }
                    ret[i]=individuals[parentidx].Clone();
                }
                //Returning the result.
                return ret;
            }
        public override string ToString()
        {
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            string updatesString = Populations.Select(population => population.batchedUpdates.size() + " updates").collect(joining(", ", "[", "]"));

            return("BatchingMultipleIndexPopulator{activeTasks=" + _activeTasks + ", executor=" + _executor + ", " +
                   "batchedUpdates = " + updatesString + ", queuedUpdates = " + UpdatesQueue.Count + "}");
        }
Exemplo n.º 6
0
        protected void UpdateMaxNodes(IMap map)
        {
            var atualNodes = Populations.Sum(o => o.ListNodes.Count);

            if (atualNodes >= map.GetMaxExpandedNodes())
            {
                map.SetMaxExpandedNodes(atualNodes);
            }
        }
Exemplo n.º 7
0
        private async Task CalcFitness()
        {
            await CalcGenomeRoutesAsync();

            Populations.ForEach(e => e.CalcFitness(Fitness));
            Populations = Populations
                          .OrderBy(o => o.Fitness).ToList();

            /*.OrderBy(e =>
             *  e.Trucks.Any(t => t.Routes.Any(r => r.Late)))
             *  .ThenBy(o => o.Fitness).ToList();*/
        }
 /// <summary>
 /// Remove a population from the RPM.
 /// </summary>
 public void RemovePopulation(Population population)
 {
     if (!Populations.Contains(population))
     {
         return;
     }
     Populations.Remove(population);
     TypesOfTerrain.Remove(population);
     openID.Enqueue(PopulationToID[population]);
     PopulationByID.Remove(PopulationToID[population]); // free ID
     PopulationToID.Remove(population);                 // free ID
     CleanupAccessMapForRecycledID();
 }
Exemplo n.º 9
0
        internal override void Plus(XDocument xdoc)
        {
            foreach (var element in xdoc.Root.Elements())
            {
                var val = element.Value;
                int valI;
                int.TryParse(val, out valI);

                switch (element.Name.LocalName)
                {
                case "id":
                case "type":
                    break;

                case "coords":
                    if (Coords == null)
                    {
                        Coords = new List <Point>();
                    }
                    foreach (var coordSplit in val.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(coord => coord.Split(',')).Where(coordSplit => coordSplit.Length == 2))
                    {
                        Coords.Add(new Point(Convert.ToInt32(coordSplit[0]), Convert.ToInt32(coordSplit[1])));
                    }
                    break;

                case "population":
                    if (Populations == null)
                    {
                        Populations = new Dictionary <Race, int>();
                    }
                    foreach (var popSplit in val.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(pop => pop.Split(',')).Where(popSplit => popSplit.Length == 3))
                    {
                        if (Populations.ContainsKey(World.Races[Convert.ToInt32(popSplit[0])]))
                        {
                            Populations[World.Races[Convert.ToInt32(popSplit[0])]] += Convert.ToInt32(popSplit[1]);
                        }
                        else
                        {
                            Populations.Add(World.Races[Convert.ToInt32(popSplit[0])], Convert.ToInt32(popSplit[1]));
                        }
                    }
                    break;

                default:
                    DFXMLParser.UnexpectedXmlElement(xdoc.Root.Name.LocalName + "\t" + "Region", element, xdoc.Root.ToString());
                    break;
                }
            }
        }
Exemplo n.º 10
0
        public EconomicsViewModel()
        {
            Factions = GameState.Instance.Factions;

            if (Factions == null)
            {
                return;
            }

            CurrentFaction = Factions.FirstOrDefault();

            if (Populations != null)
            {
                CurrentPopulation = Populations.FirstOrDefault();
            }
        }
Exemplo n.º 11
0
 public Builder setPopulation(PopulationType populationType, int count)
 {
     if (count == 0)
     {
         Populations.Remove(populationType);
         return(this);
     }
     if (Populations.ContainsKey(populationType))
     {
         Populations[populationType] = count;
     }
     else
     {
         Populations.Add(populationType, count);
     }
     return(this);
 }
Exemplo n.º 12
0
 async Task CalcGenomeRoutesAsync()
 {
     if (ProcessChunk == 1)
     {
         foreach (var item in Populations)
         {
             await item.CalcRoutesAsync(routeService);
         }
     }
     else
     {
         await Populations
         .ToObservable(ThreadPoolScheduler.Instance)
         .Select(n => Observable.FromAsync(_ => n.CalcRoutesAsync(routeService)))
         .Merge(ProcessChunk);
     }
 }
Exemplo n.º 13
0
 public void AddPopulations(List <Population> populations)
 {
     foreach (Population population in populations)
     {
         Population popMatch = Populations.FirstOrDefault(pop => pop.Race.NamePlural.Equals(population.Race.NamePlural, StringComparison.InvariantCultureIgnoreCase));
         if (popMatch != null)
         {
             popMatch.Count += population.Count;
         }
         else
         {
             Populations.Add(new Population(population.Race, population.Count));
         }
     }
     Populations = Populations.OrderByDescending(pop => pop.Count).ToList();
     Parent?.AddPopulations(populations);
 }
Exemplo n.º 14
0
 public void AddPopulations(List <Population> populations)
 {
     foreach (Population population in populations)
     {
         Population popMatch = Populations.FirstOrDefault(pop => pop.Race == population.Race);
         if (popMatch != null)
         {
             popMatch.Count += population.Count;
         }
         else
         {
             Populations.Add(new Population(population.Race, population.Count));
         }
     }
     Populations = Populations.OrderByDescending(pop => pop.Count).ToList();
     Parent?.AddPopulations(populations);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Clear the Population and SeedGenres entries
        /// </summary>
        public void Clear()
        {
            foreach (Population population in Populations)
            {
                GenrePopulations.RemovePopulation(population.SeedPopulation);
            }

            if (SeedGenres != null)
            {
                GenrePopulations.RemovePopulation(SeedGenres);
                SeedGenres = null;
            }

            Populations.Clear();
            GenresAlreadyIncluded.Clear();
            AlbumsAlreadyIncluded.Clear();
        }
Exemplo n.º 16
0
        private void removeRow(object obj)
        {
            Population tempPop = new Population();

            tempPop.Date  = SelectedPopulation.Date;
            tempPop.Sex   = SelectedPopulation.Sex;
            tempPop.Value = SelectedPopulation.Value;

            for (int i = 0; i < Populations.Count(); i++)
            {
                if ((Populations[i].Date.Equals(tempPop.Date)) && (Populations[i].Sex.Equals(tempPop.Sex)) &&
                    (Populations[i].Value.Equals(tempPop.Value)))
                {
                    Populations.RemoveAt(i);
                }
            }
        }
Exemplo n.º 17
0
        public void UpdatePopulations()
        {
            if (SelectedSort == 0)//enum
            {
                populations = populations.OrderBy(p => p.City).ToList();
            }
            else
            {
                populations = populations.OrderByDescending(p => p.PopulationNum).ToList();
            }

            Populations.Clear();
            foreach (Population p in populations)
            {
                Populations.Add(p);
            }
        }
Exemplo n.º 18
0
        private static List <Populations> GetPopulations()
        {
            var pops        = new List <Populations>();
            var populations = File.ReadAllLines(filePath + "Populations.txt");

            foreach (var item in populations)
            {
                var info   = item.Split(' ');
                var newPop = new Populations
                {
                    Iso3       = info[0],
                    Population = double.Parse(info[1])
                };
                pops.Add(newPop);
            }

            return(pops);
        }
    /// <summary>
    /// Add a population to the RPM.
    /// </summary>
    public void AddPopulation(Population population)
    {
        if (!Populations.Contains(population))
        {
            // ignore their old id and assign it a new one
            int id = openID.Dequeue();

            // since IDs after maxPopulation-1 are recycled ids, we need to do clean up old values
            if (id == lastRecycledID)
            {
                CleanupAccessMapForRecycledID();
            }
            PopulationToID.Add(population, id);
            PopulationByID.Add(id, population);
            Populations.Add(population);

            TypesOfTerrain.Add(population, new int[(int)TileType.TypesOfTiles]);
            // generate the map with the new id
            GenerateMap(population);
        }
    }
Exemplo n.º 20
0
        /// <summary>
        /// Intialise the Population list from the GenrePopulation records
        /// </summary>
        public void InitialisePopulations()
        {
            // Get all the GenrePopulation records associated with this Autoplay and order by the population index
            IEnumerable <GenrePopulation> genrePopulations = GenrePopulations.GenrePopulationCollection.Where(gp => gp.AutoplayId == Id).OrderBy(gp => gp.Index);

            // Create a Population for each GenrePopulation and add it to the list
            foreach (GenrePopulation population in genrePopulations)
            {
                // If this is the original set of genres then save it separately
                if (population.Index == -1)
                {
                    SeedGenres = population;
                }
                else
                {
                    // Get all the new genres and albums
                    List <string>       populationGenres = population.Genres.Where(gen => GenresAlreadyIncluded.Add(gen) == true).ToList();
                    IEnumerable <Album> populationAlbums = GetAlbumsFromGenres(populationGenres);

                    Populations.Add(new Population(population, populationGenres, populationAlbums));
                }
            }
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
        public override bool Find(IMap map, IHeuristic heuristic)
        {
            if (Mutate == null || Crossover == null || Fitness == null || Selection == null)
            {
                throw new System.Exception("GA cant run without all operators");
            }

            if (Fitness.Heuristic == null)
            {
                Fitness.Heuristic = heuristic;
            }

            var Adaptation = new Adaptation(map);
            var rand       = RandomFactory.Rand;
            var startNode  = map.StartNode;
            var endNode    = map.EndNode;

            for (int i = 0; i < PopulationSize; i++)
            {
                Populations.Add(new Genome(map));
            }


            CalcFitness();


            var step = 0;

            OnStart(BuildArgs(step, map));
            for (int i = 0; i < GenerationLimit; i++)
            {
                var newpopulations = new List <IGenome>();
                Populations = Populations.OrderBy(o => o.Fitness).ToList();
                for (int j = 0; j < BestSolutionToPick; j++)
                {
                    Populations[j].Fitness = Fitness.Calc(Populations[j]);
                    newpopulations.Add(Populations[j]);
                }
                var ran   = rand.Next(1, Populations.Count);
                var best  = Populations.First().ListNodes;
                var best2 = Selection.Select(Populations).ListNodes;
                endNode = best.Last();
                if (endNode.Equals(map.EndNode))
                {
                    endNode.Direction = DirectionMovement.None;
                    map.EndNode       = endNode;

                    map.UpdateClosedList(new List <Node>());
                    map.UpdateOpenList(new List <Node>());


                    //if (!best.First().Equals(map.StartNode))
                    OnEnd(BuildArgs(step, map, true));
                    Generations = i;
                    return(true);
                }
                map.UpdateClosedList(best);
                map.UpdateOpenList(best2);

                while (newpopulations.Count < Populations.Count)
                {
                    // Selection
                    var nodemom = Selection.Select(Populations);
                    var nodedad = Selection.Select(Populations);
                    // CrossOver
                    var cross = Crossover.Calc(new CrossoverOperation(nodemom, nodedad));

                    //if (!cross.Mom.ListNodes.First().Equals(map.StartNode)) { }
                    //if (!cross.Dad.ListNodes.First().Equals(map.StartNode)) { }

                    // Mutation
                    nodemom = Mutate.Calc(cross.Mom);
                    nodedad = Mutate.Calc(cross.Dad);

                    //if (!nodemom.ListNodes.First().Equals(map.StartNode)) { }
                    //if (!nodedad.ListNodes.First().Equals(map.StartNode)) { }

                    // Adaptation
                    nodemom         = Adaptation.Calc(nodemom);
                    nodedad         = Adaptation.Calc(nodedad);
                    nodemom.Fitness = Fitness.Calc(nodemom);
                    nodedad.Fitness = Fitness.Calc(nodedad);

                    //if (!nodemom.ListNodes.First().Equals(map.StartNode)) { }
                    //if (!nodedad.ListNodes.First().Equals(map.StartNode)) { }

                    // Add in new population
                    newpopulations.Add(nodemom);
                    newpopulations.Add(nodedad);
                }
                Populations = newpopulations.ToList();
                OnStep(BuildArgs(step++, map));
            }
            Generations = GenerationLimit;
            OnEnd(BuildArgs(step, map, false));
            return(false);
        }
            public Chromosomes.IChromosome[] PerformSelection(Populations.IPopulation population, int size)
            {
                //Getting all of the chromosomes that are in population.
                Chromosomes.IChromosome[] individuals = population.GetChromosomes();

                //Calculating the number of the those chromosomes.
                int sz = individuals.Length;

                //Calculating the fitness of each chromosome.
                double[] f = new double[sz];
                double[] fitnesses = population.GetFitnesses();
                for (int i = 0; i < sz; ++i)
                    f[i] = fitnesses[i];

                //Calculating the sum of the fitnesses.
                double sum = 0.0;
                for (int i = 0; i < sz; ++i)
                    sum += f[i];

                //The normalization step.
                for (int i = 0; i < sz; ++i)
                    f[i] /= sum;

                //Sorting the population by descending fitness values.
                RouletteWheelSelectionMethod.Sort(individuals, f, 0, sz - 1);

                //The accumulation step.
                for (int i = 1; i < sz; ++i)
                    f[i] += f[i - 1];

                f[sz - 1] = 1.0; //To ensure that the sum of all the fitnesses is equal to 1.0.

                //Defining the to-be-returned array.
                Chromosomes.IChromosome[] ret = new Chromosomes.IChromosome[size];

                //Selecting the parents from the population and putting them in ret.
                for (int i = 0; i < size; ++i)
                {
                    int idx = RouletteWheelSelectionMethod.Find(f, RouletteWheelSelectionMethod.random.NextDouble());
                    ret[i] = individuals[idx].Clone();
                }

                //Returning the result.
                return ret;
            }
Exemplo n.º 24
0
 public void Dirty()
 {
     Populations.Dirty();
     ResearchTable.Dirty();
 }