public void Expand( Random randomness_provider, PD_Game gameState, PD_AI_PathFinder pathFinder, PD_AI_Macro_Agent_Base defaultPolicyAgent ) { PD_Game generator_GameState = gameState.Request_Randomized_Copy(randomness_provider); int initialTurn = generator_GameState.game_state_counter.turn_index; int finalTurn = initialTurn + MaxGenomeLength - Genome.Count; int currentTurn = initialTurn; // prepare the dictionary of macros! Dictionary <int, List <PD_MacroAction> > macroActionsPerTurn = new Dictionary <int, List <PD_MacroAction> >(); for (int i = initialTurn; i < finalTurn; i++) { macroActionsPerTurn.Add( i, new List <PD_MacroAction>() ); } // create the new macros and put them in the dictionary while ( generator_GameState.GQ_Is_Ongoing() && currentTurn < finalTurn ) { var nextMacro = defaultPolicyAgent.GetNextMacroAction( randomness_provider, generator_GameState, pathFinder ); macroActionsPerTurn[currentTurn].Add(nextMacro); generator_GameState.Apply_Macro_Action( randomness_provider, nextMacro ); currentTurn = generator_GameState.game_state_counter.turn_index; } // expand the genome for (int i = initialTurn; i < finalTurn; i++) { if (macroActionsPerTurn[i].Count > 0) { RH_Gene gene = new RH_Gene( i, macroActionsPerTurn[i] ); Genome.Add(gene); } } }
internal static Population <List <Genome>, Problem, Fitness> InitializePopulation( Problem problem, Second target, int population_size, int round_count) { IRandomGenerator random = new RandomGenerator(); // generate a list of cities to place. List <int> cities = new List <int>(); for (int city_to_place = 0; city_to_place < problem.Cities; city_to_place++) { cities.Add(city_to_place); } // create the population Population <List <Genome>, Problem, Fitness> population = new Population <List <Genome>, Problem, Fitness>( null, false); // create the fitness calculator. FitnessCalculator fitness_calculator = new FitnessCalculator(5); while (population.Count < population_size) { OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.VRP.MultiSalesman.Facade", System.Diagnostics.TraceEventType.Information, "Initializing population individual {0}/{1}...", population.Count + 1, population_size); // create copy of cities List <int> cities_list = new List <int>(cities); // create new individuals. Individual individual = new Individual(new List <Genome>()); // place one random city in each round. for (int round_idx = 0; round_idx < round_count; round_idx++) { // select a random city to place. int city_idx = random.Generate(cities_list.Count); int city = cities_list[city_idx]; cities_list.RemoveAt(city_idx); // create new genome. Genome genome = new Genome(); genome.Add(city); individual.Genomes.Add(genome); } individual = BestPlacementHelper.Do( problem, fitness_calculator, individual, cities_list); // add inidividual to the population. population.Add(individual); OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.VRP.MultiSalesman.Facade", System.Diagnostics.TraceEventType.Information, "Done!"); } return(population); }
private void CommonInitialization() { Polygon.ShiftCentroid(new Point(0, 0)); //normalize polygon's position Point polygonCentroid = Polygon.Centroid; foreach (var vertex in Polygon.Vertices) { Genome.Add(new SimplePolygonGene(vertex, polygonCentroid)); } }
public Genome CopyGenome() { Genome copied = new Genome(); foreach (Gene gene in this.genes) { copied.Add(gene.CopyGene()); } return(copied); }
// Use this for initialization void Start() { GameManager.instance.worldManager.allCreatures.Add(this); size = 0.5f; if (genome == null) { genome = new Genome(); Colour color = new Colour(new Color32(50, 150, 122, 255)); genome.Add(color); MovementSpeed movementSpeed = new MovementSpeed(10f); genome.Add(movementSpeed); ViewRadius viewRange = new ViewRadius(20f); genome.Add(viewRange); LifeSpan lifeSpan = new LifeSpan(40f); genome.Add(lifeSpan); Acceleration acceleration = new Acceleration(20f); genome.Add(acceleration); } Init(); }
internal static void PlaceInGenome(Genome smallest, int city_idx, int city) { if (smallest.Count == city_idx) { smallest.Add(city); } else { smallest.Insert(city_idx, city); } }
public Genome ToGenomeFromCompleteGraph() { Genome P = new Genome(); foreach (Edges cycle in Cycles()) { Chromosome chromosome = cycle.ToChromosome(); P.Add(chromosome); } return(P); }
/* * GraphToGenome(GenomeGraph) * P ← an empty set of chromosomes * for each cycle Nodes in GenomeGraph * Chromosome ← CycleToChromosome(Nodes) * add Chromosome to P * return P */ public Genome ToGenome() { Genome P = new Genome(); foreach (Nodes cycle in CycleNodes()) { Chromosome chromosome = cycle.ToChromosome(); P.Add(chromosome); } return(P); }
internal static List <Genome> EstimateVehicles <EdgeType, VertexType>( Problem problem, Second min, Second max) where EdgeType : class where VertexType : class, IEquatable <VertexType> { // create the fitness calculator. FitnessCalculator fitness_calculator = new FitnessCalculator(5); IRandomGenerator random = new RandomGenerator(); double average_time = (min.Value + max.Value) / 2.0; double previous_time = average_time; // generate a list of cities to place. List <int> cities = new List <int>(); for (int city_to_place = 0; city_to_place < problem.Cities; city_to_place++) { cities.Add(city_to_place); } // first optimize the number of vehicles; this means generate rounds that are as close to the max as possible. List <Genome> generated_rounds = new List <Genome>(); bool new_round = true; Genome current_round = null; while (cities.Count > 0) { OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.VRP.MultiSalesman.Facade", System.Diagnostics.TraceEventType.Information, "Placing cities {0}/{1}", cities.Count, problem.Cities); if (_registered_progress_reporter != null) { ProgressStatus status = new ProgressStatus(); status.TotalNumber = problem.Cities; status.CurrentNumber = problem.Cities - cities.Count; status.Message = "Placing cities..."; _registered_progress_reporter.Report(status); } // create a new round if needed. int city; int city_idx; if (new_round) { new_round = false; current_round = new Genome(); // select a random city to place. city_idx = random.Generate(cities.Count); city = cities[city_idx]; cities.RemoveAt(city_idx); current_round.Add(city); previous_time = average_time; } if (cities.Count > 0) { // find the best city to place next. // calculate the best position to place the next city. BestPlacementHelper.BestPlacementResult new_position_to_place = BestPlacementHelper.CalculateBestPlacementInGenome( problem, fitness_calculator, current_round, cities); city = new_position_to_place.City; // remove the node from the source list. cities.Remove(city); // place the node. current_round.Insert(new_position_to_place.CityIdx, new_position_to_place.City); // calculate the time. double time = fitness_calculator.CalculateTime( problem, current_round); if (average_time < time) { // time limit has been reached. double diff_average = time - average_time; double diff_previous = average_time - previous_time; if (diff_average > diff_previous) { // remove the last added city. current_round.Remove(city); cities.Add(city); } else { // keep the last city. } // keep the generated round. generated_rounds.Add(current_round); new_round = true; } previous_time = time; } } return(generated_rounds); }
/// <summary> /// Ermittelt alle Nachbarn aus zwei Genomen für ein bestimmtes Allel /// </summary> /// <returns>Liste mit Nachbarn</returns> /// <param name="value">Allel</param> /// <param name="genomeA">Genome A</param> /// <param name="genomeB">Genome B</param> private Genome GetNeighboursOfValue(double value, Genome genomeA, Genome genomeB) { //Kreisgenom simulieren List<double> a = genomeA.ToList(); a.Insert(0,genomeA[genomeA.Count-1]); a.Add(genomeA[0]); List<double> b = genomeB.ToList(); b.Insert(0,genomeB[genomeB.Count-1]); b.Add(genomeB[0]); //Nachbarn Genome neighbours = new Genome(); neighbours.Add(a[genomeA.IndexOf(value)]); neighbours.Add(a[genomeA.IndexOf(value)+2]); neighbours.Add(b[genomeB.IndexOf(value)]); neighbours.Add(b[genomeB.IndexOf(value)+2]); //Doppelte Einträge entfernen und ab damit return new GenomeReal(neighbours.Distinct().ToArray()); }
static void Main(string[] args) { //just loop endlessly until user gets bored :0) while (true) { //storage for our population of chromosomes. var Population = new Genome(); //get a target number from the user. double Target; Console.WriteLine("Please, enter a number:"); while(!Double.TryParse(Console.ReadLine(), out Target)) { Console.WriteLine("You must enter a Number. PLease try again!"); Console.WriteLine("Please, enter a number:"); } int GenerationsRequiredToFindASolution = 0; //we will set this flag if a solution has been found bool bFound = false; //enter the main GA loop while (!bFound) { // test and update the fitness of every chromosome in the // population for (int i = 0; i < Population.Count; i++) { Population[i].Fitness = AssignFitness(Population[i].Bits, Target); } // check to see if we have found any solutions (fitness will be 999) for (int i = 0; i < Genome.POP_SIZE; i++) { if (Population[i].Fitness >= 999.0) { Console.WriteLine("Solution found in {0} generations!", GenerationsRequiredToFindASolution); PrintChromo(Population[i].Bits); bFound = true; break; } } // create a new population by selecting two parents at a time and creating offspring // by applying crossover and mutation. Do this until the desired number of offspring // have been created. //define some temporary storage for the new population we are about to create var temp = new Genome(true); //loop until we have created POP_SIZE new chromosomes while (Population.Count > 0) { // we are going to create the new population by grabbing members of the old population // two at a time via roulette wheel selection. var offspring1 = Population.Roulette(); var offspring2 = Population.Roulette(); //add crossover dependent on the crossover rate offspring1.Crossover(ref offspring2); //now mutate dependent on the mutation rate offspring1.Mutate(); offspring2.Mutate(); //reset fitness offspring1.Fitness = offspring2.Fitness = 0.0; //add these offspring to the new population. (assigning zero as their //fitness scores) temp.Add(offspring1.Copy()); temp.Add(offspring2.Copy()); }//end loop //copy temp population into main population array Population = temp; ++GenerationsRequiredToFindASolution; // exit app if no solution found within the maximum allowable number // of generations if (GenerationsRequiredToFindASolution > Chromosome.MAX_ALLOWABLE_GENERATIONS) { Console.Write("No solutions found this run!"); bFound = true; } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); }//end while }