/// <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)))); }
/// <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); } } } }
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; } } }
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); }
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); }
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); } }
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); }
/// <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); } }
/// <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)); } } }
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); }
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); }