private void RunGA(){ _teams = LoadTeams(); _winners = _teams.FindAll(l => l.Winner == true); _losers = _teams.FindAll(l => l.Winner == false); const double crossoverProbability = 0.85; const double mutationProbability = 0.15; const int elitismPercentage = 5; var population = new Population(1000, 72, true, false, ParentSelectionMethod.TournamentSelection); var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.DoublePoint }; var mutation = new BinaryMutate(mutationProbability, true); var ga = new GeneticAlgorithm(population, EvaluateFitness); ga.OnGenerationComplete += ga_OnGenerationComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); ga.Run(TerminateAlgorithm); }
private static void xMain(string[] args) { const double crossoverProbability = 0.85; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create a Population of 100 random chromosomes of length 44 var population = new Population(100, 44, false, false); //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, EvaluateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(TerminateAlgorithm); }
private static void SetupGeneticAlgorithm() { //create the elite operator var elite = new Elite(5); //create the crossover operator var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint //SinglePoint or DoublePoint }; //create the mutation operator var mutate = new SwapMutate(0.02); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); //run the GA ga.Run(Terminate); }
private Population runAlgorithem(Population population, int amountOfGenerations) { const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new SwapPlayerMutation(mutationProbability, this.players, this.groupedPlayers); //create the GA itself var ga = new GeneticAlgorithm(population, evaluateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += this.getOnGenerationComplete(); //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(GetTerminateFunction(amountOfGenerations)); this.performanceMonitor.SavePerformanceLog("./results"); return(ga.Population); }
private static void Main(string[] args) { const int populationSize = 100; //get our cities var cities = CreateCities().ToList(); //Each city is an object the chromosome is a special case as it needs //to contain each city only once. Therefore, our chromosome will contain //all the cities with no duplicates //we can create an empty population as we will be creating the //initial solutions manually. var population = new Population(); //create the chromosomes for (var p = 0; p < populationSize; p++) { var chromosome = new Chromosome(); foreach (var city in cities) { var gene = new Gene(city); chromosome.Genes.Add(gene); } var rnd = GAF.Threading.RandomProvider.GetThreadRandom(); chromosome.Genes.ShuffleFast(rnd); population.Solutions.Add(chromosome); } //create the elite operator var elite = new Elite(5); //create the crossover operator var crossover = new Crossover(0.9) { CrossoverType = CrossoverType.DoublePointOrdered }; //create the mutation operator var mutate = new SwapMutate(0.2); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); //run the GA ga.Run(Terminate); Console.Read(); }
public Genetics(Main form1, Func <string, int, string, bool> populateM) { pop = populateM; form1.Text = "test"; form = form1; var population = new Population(populationSize, 576, false, false); //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself ga = new GeneticAlgorithm(population, EvaluateFitness); ga.OnGenerationComplete += ga_OnGenerationComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); }
public void TestMethod1() { /* Chromosome representation StockLength*item */ for (int i = 0; i < 10; i++) { items.Add(new Item(3, 5)); items.Add(new Item(5, 1)); items.Add(new Item(5, 2)); } var population = CreateInitialePopulation(500); var elite = new Elite(2); var crossover = new Crossover(0.85) { CrossoverType = CrossoverType.DoublePointOrdered }; var mutate = new SwapMutate(0.001); var ga = new GeneticAlgorithm(population, CalculateFitness); ga.OnGenerationComplete += Ga_OnGenerationComplete; ga.OnRunComplete += Ga_OnRunComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); ga.Run(200); }
public void Run() { if (running) { return; } //create the elite operator var elite = new Elite(ElitismPercentage); //create the mutation operator var mutate = new MutateInterval(MutationPercentage, ChromosomeUtils.NUMBER_GENES); var swap = new MutateSwapInterval(MutationPercentage, ChromosomeUtils.NUMBER_GENES); //create the GA var ga = new GeneticAlgorithm(population, fitness.CalculateFitness); //hook up to some useful events ga.OnRunComplete += OnRunComplete; //add the operators ga.Operators.Add(elite); //ga.Operators.Add(mutate); //ga.Operators.Add(swap); ga.Operators.Add(new BinaryMutate(MutationPercentage)); ga.Operators.Add(new CrossoverIndex(CrossOverPercentage, ChromosomeUtils.NUMBER_GENES, true, GAF.Operators.CrossoverType.DoublePoint, ReplacementMethod.GenerationalReplacement)); //run the GA running = true; ga.Run(TerminateFunction); }
public static EliteBinds getBinds(ref Dictionary <string, object> state, ref Dictionary <string, string> textValues, ref Dictionary <string, bool?> booleanValues, Elite.MessageBus messageBus) { EliteBinds eliteBinds = null; if (needsBindsReload(ref state, ref textValues, ref booleanValues) == true) { Tuple <string, string> tResponse = Elite.getBindsFilename(); string bindsPreset = tResponse.Item1; string bindsFile = tResponse.Item2; if (bindsPreset != null && bindsFile != null) { Debug.Write("Current Binds file: " + bindsFile); var bindsTree = XElement.Load(bindsFile); state["VAEDbindsFile"] = bindsFile; state["VAEDbindsPreset"] = bindsPreset; state["VAEDlastPresetTimestamp"] = File.GetLastWriteTime(bindsPreset); state["VAEDlastBindsTimestamp"] = File.GetLastWriteTime(bindsFile); XElement keyboardLayout = bindsTree.Element("KeyboardLayout"); string lang = keyboardLayout.Value.ToString(); Debug.Write("Elite key bindings language set to: " + lang); state["VAEDbindsLanguage"] = lang; eliteBinds = new EliteBinds(bindsTree, lang); state["VAEDeliteBinds"] = eliteBinds; } } else { eliteBinds = (EliteBinds)state["VAEDeliteBinds"]; } return(eliteBinds); }
// Using Genetic Algorithms public static void RunThrowAndStick(this House house) { boundaryXDim = house.Boundary.XDim; boundaryYDim = house.Boundary.YDim; var population = new Population(populationSize, bitsToAdjustRoom * house.RoomCount, false, false); //create the genetic operators var elite = new Elite(5); var crossover = new Crossover(0.85, true, CrossoverType.SinglePoint); var mutation = new BinaryMutate(0.2, true); //create the GA itself var ga = new GeneticAlgorithm(population, chromosome => EvaluateFitness(chromosome, house)); //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); // Events subscription ga.OnGenerationComplete += (sender, e) => WriteLine($"Fitness is {e.Population.GetTop(1)[0].Fitness}"); ga.OnRunComplete += (sender, e) => ga_OnRunComplete(sender, e, house); // Run the GA WriteLine("Starting the GA"); ga.Run(Terminate); }
private static void Main(string[] args) { //get our cities _cities = CreateCities().ToList(); //Each city can be identified by an integer within the range 0-15 //our chromosome is a special case as it needs to contain each city //only once. Therefore, our chromosome will contain all the integers //between 0 and 15 with no duplicates //we can create an empty population as we will be creating the //initial solutions manually. var population = new Population(); //create the chromosomes for (var p = 0; p < 5000; p++) { var chromosome = new Chromosome(); for (var g = 0; g < 16; g++) { chromosome.Genes.Add(new Gene(g)); } var rnd = GAF.Threading.RandomProvider.GetThreadRandom(); chromosome.Genes.ShuffleFast(rnd); population.Solutions.Add(chromosome); } //create the elite operator var elite = new Elite(15); //create the crossover operator var crossover = new Crossover(0.7) { CrossoverType = CrossoverType.DoublePointOrdered }; //create the mutation operator var mutate = new SwapMutate(0.02); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); //run the GA ga.Run(Terminate); Console.Read(); }
private Page CreateOpDetailPage(OpDetail op, int index) { Elite e = op.Elites[index]; DiscordEmbedBuilder embed = new DiscordEmbedBuilder() .WithTitle($"[{op.Rarity}★] {op.Name}") .AddField($"Level 1 → {e.MaxLevel}", $"{Formatter.Bold("Health:")} {e.Hp} → {e.MaxHp}\n" + $"{Formatter.Bold("Attack:")} {e.Atk} → {e.MaxAtk}\n" + $"{Formatter.Bold("Defense:")} {e.Def} → {e.MaxDef}\n" + $"{Formatter.Bold("Resistance:")} {e.MagicResistance}", true) .AddField("\u200b", $"{Formatter.Bold("Cost:")}{e.Cost}\n" + $"{Formatter.Bold("Block:")} {e.BlockCnt}\n" + $"{Formatter.Bold("Attack Time:")} 100\n" + $"{Formatter.Bold("Respawn Time:")} {e.RespawnTime}\n", true) .AddField("Range", AttackRange.GetAttackRange(op.Elites[index].RangeId), true); string img = string.Empty; switch (index) { case 1: { if (op.OperatorCode.Equals("Amiya")) { embed.WithThumbnail($"{s3.Url}avatars/{op.OperatorCode}_1+.png"); } else { embed.WithThumbnail($"{s3.Url}avatars/{op.OperatorCode}.png"); } break; } case 2: { embed.WithThumbnail($"{s3.Url}avatars/{op.OperatorCode}_2.png"); break; } } if (op.Talents != null && op.Talents.Count > 0) { string talent = string.Empty; foreach (Talent t in op.Talents) { if (t.Phase == index) { talent += $"{Formatter.Bold(t.Name + ':')} {t.Description} (Lvl.1,Potential {t.RequirePotential})\n"; } } if (!string.IsNullOrEmpty(talent)) { talent = talent.Substring(0, talent.Count() - 1); embed.AddField("Talents", talent); } } return(new Page { Embed = embed.Build() }); }
public Board GetBoardSuggestion() { var population = new Population(); var randomGen = new Random(); //create the chromosomes for (var p = 0; p < 100; p++) { var chromosome = new Chromosome(); for (var g = 0; g < this.tasks.Length; g++) { chromosome.Genes.Add(new Gene(randomGen.Next(0, this.users.Length))); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the elite operator var elite = new Elite(5); //create the crossover operator var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint }; //create the mutation operator var mutate = new SwapMutate(0.02); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); this.watch.Start(); //run the GA ga.Run(Terminate); var suggestedBoard = createBoardFromChromose(ga.Population.GetTop(1).First()); var doneTasks = board.tasks.Where(t => t.status.Equals("done")); board.tasks = suggestedBoard.tasks; board.tasks.AddRange(doneTasks); return(board); }
private static void Main(string[] args) { const int populationSize = 100; const int elitismPercentage = 5; const double crossoverProbability = 0.8; const double mutationProbability = 0.02; // Get the cities var cities = Helper.CreateCities(); // Initialize a population var population = new Population(); // Create the chromosomes for (var p = 0; p < populationSize; p++) { var chromosome = new Chromosome(); foreach (var city in cities) { chromosome.Genes.Add(new Gene(city)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } // Create the elite operator var elite = new Elite(elitismPercentage); // Create the crossover operator var crossover = new Crossover(crossoverProbability) { CrossoverType = CrossoverType.DoublePointOrdered }; // Create the mutation operator var mutate = new SwapMutate(mutationProbability); // Create the GA var ga = new GeneticAlgorithm(population, Helper.CalculateFitness); // Hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; // Add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); // Run the GA ga.Run(Helper.Terminate); // Finalize the program Helper.PrintEnd(); }
public IEnumerable <Player> FindSolution() { const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create the population var population = new Population(); Random rnd = new Random(); //create the chromosomes for (var p = 0; p < 100; p++) { var chromosome = new Chromosome(); for (var g = 0; g < 11; g++) { chromosome.Genes.Add(new Gene(rnd.Next(0, this.players.Count()))); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new SwapPlayerMutation(0.02, this.players); //create the GA itself var ga = new GeneticAlgorithm(population, evaluateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(TerminateAlgorithm); var topSolution = this.getPlayersFromChromosome(ga.Population.GetTop(1).First()); this.calculator.PrintFitnessDetails(topSolution); return(topSolution.OrderBy(p => p.type)); }
static void Main(string[] args) { // Initialize the game table, matches and distances WorldCupChronogram.Initialize(); Distances.Initialize(); // Population, with a chromossome length var population = new Population(CHROMOSOME_SIZE); // Random seed var random = new Random(); // Initialize the population for (int i = 0; i < INITIAL_POPULATION_SIZE; i++) { var chromossome = new Chromosome(); for (int j = 0; j < CHROMOSOME_SIZE; j++) { // Somedays have more or less games var maxGamesInDays = WorldCupChronogram.Days[j].NumberOfGames; var gene = new Gene(random.Next(maxGamesInDays)); chromossome.Add(gene); } population.Solutions.Add(chromossome); } // Elite operator var elite = new Elite(ETILISM); // Crossover operator var crossover = new Crossover(CROSSOVER_PROBABILITY); // Mutation operador var mutate = new SwapMutate(MUTATION_PROBABILITY); // GA var ga = new GeneticAlgorithm(population, CalculateFitness); // Add operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); // Handlers ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; ga.Run(Terminate); Console.ReadLine(); }
public static int[,] Generate() { const int populationSize = 200; var population = new Population(); Random random = new Random(); boardSize = 4; int[,] board = new int[boardSize, boardSize]; for (var i = 0; i < boardSize; i++) { for (var j = 0; j < boardSize; j++) { board[i, j] = random.Next(0, 3); } } //start point and end point board[0, 0] = 2; board[boardSize - 1, boardSize - 1] = 0; for (var p = 0; p < populationSize; p++) { var chromosome = new Chromosome(); foreach (var field in board) { chromosome.Genes.Add(new Gene(field)); } population.Solutions.Add(chromosome); } var elite = new Elite(10); var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint }; var mutate = new SwapMutate(0.1); var ga = new GeneticAlgorithm(population, CalculateFitness); ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); ga.Run(Terminate); return(chromosome2Board(ga.Population.GetTop(1)[0])); }
private static void Main(string[] args) { const int populationSize = 100; //get our cities var nodes = CreateNodes().ToList(); var population = new Population(); //create the chromosomes for (var p = 0; p < populationSize; p++) { var chromosome = new Chromosome(); foreach (var node in nodes) { chromosome.Genes.Add(new Gene(node)); } var rnd = GAF.Threading.RandomProvider.GetThreadRandom(); chromosome.Genes.ShuffleFast(rnd); population.Solutions.Add(chromosome); } //create the elite operator var elite = new Elite(5); //create the crossover operator var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.DoublePointOrdered }; //create the mutation operator var mutate = new SwapMutate(0.02); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); //run the GA ga.Run(Terminate); Console.Read(); }
public EliteDto(Elite a) { if (a != null) { UnitId = a.UnitId; Counter = a.Counter; Price = a.Price; Salary = a.Salary; Food = a.Food; Atk = a.Atk; Def = a.Def; } }
public async Task <Unit> postS(int id) { var country = _dbcontext.Countries.Where(c => c.CountryId == id).SingleOrDefault(); var a = new Elite() { OwnerCountry = country }; _dbcontext.Elites.Add(a); await _dbcontext.SaveChangesAsync(); return(a); }
public Cut[] getBestOrder(Cut[] cuts) { const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; bestOrder = new Cut[cuts.Length]; var population = new Population(); //create the chromosomes for (var p = 0; p < 100; p++) { var chromosome = new Chromosome(); foreach (var cut in cuts) { chromosome.Genes.Add(new Gene(cut)); } //chromosome.Genes.ShuffleFast; population.Solutions.Add(chromosome); } //create the elite operator var elite = new Elite(5); //create the crossover operator var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.DoublePointOrdered }; //create the mutation operator var mutate = new SwapMutate(0.1); //create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); //hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); //run the GA ga.Run(Terminate); return(bestOrder); }
public static void geneticAlgorithm(object sender, EventArgs e, Label totalPrice, Label totalDistance, Label totalChanges, Label orderOfDests) { var population = new Population(); for (var p = 0; p < globals.chromosomeLength; p++) { var chromosome = new Chromosome(); for (var g = 0; g < globals.chromosomeLength; g++) { chromosome.Genes.Add(new Gene(g)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } var elite = new Elite(8); var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.DoublePointOrdered }; var mutate = new SwapMutate(0.04); var ga = new GeneticAlgorithm(population, objectiveValue); ga.OnRunComplete += ga_OnRunComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); ga.Run(Terminate); globals.order = String.Join(",", globals.orderOfDestinations.ToArray()); totalPrice.Text = Convert.ToString(globals.totalPrice); totalDistance.Text = Convert.ToString(globals.totalDistance); totalChanges.Text = Convert.ToString(globals.totalChanges); orderOfDests.Text = Convert.ToString(globals.order); if (globals.errorOutput == true) { _Default form1 = new _Default(); form1.ErrorMessage(); } }
public void OptimizeStrategicPlan(PersonalPlanDto personalPlan) { PersonalPlan = personalPlan; var population = new Population(); for (var p = 0; p < 20; p++) { var chromosome = new Chromosome(); foreach (var activitySlotDto in personalPlan.Activities) { chromosome.Genes.Add(new Gene(activitySlotDto)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } // create the elite operator var elite = new Elite(10); // create the crossover operator var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.DoublePointOrdered }; // create the mutation operator var mutate = new SwapMutate(0.02); // create the GA var ga = new GeneticAlgorithm(population, CalculateFitness); // hook up to some useful events ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; // add the operators ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); // run the GA ga.Run(Terminate); }
static void yMain(string[] args) { int populationSize = 100; double crossoverProbability = 0.65; double mutationProbability = 0.02; int elitismPercentage = 5; var cities = CreateCities().ToList(); Population population = new Population(); for (var p = 0; p < populationSize; p++) { Chromosome chromosome = new Chromosome(); foreach (City city in cities) { chromosome.Genes.Add(new Gene(city)); } var rnd = GAF.Threading.RandomProvider.GetThreadRandom(); chromosome.Genes.ShuffleFast(rnd); population.Solutions.Add(chromosome); } //Once the population has been defined, the genetic algorithm can be initialised. GeneticAlgorithm ga = new GeneticAlgorithm(population, CalculateFitness); //To monitor progress of the algorithm, several events are available ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; Crossover crossover = new Crossover(crossoverProbability) { CrossoverType = CrossoverType.DoublePointOrdered }; Elite elite = new Elite(elitismPercentage); SwapMutate mutate = new SwapMutate(mutationProbability); ga.Operators.Add(crossover); ga.Operators.Add(elite); ga.Operators.Add(mutate); ga.Run(Terminate); }
public void RunGA() { const double crossoverProbability = 0.8; const double mutationProbability = 0.02; const int elitismPercentage = 5; //create the population var population = new Population(); //create the chromosomes foreach (User currUser in GA.currBoard.boardMembers) { var chromosome = new Chromosome(); chromosome.Genes.Add(new Gene(currUser)); chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, CalculateFitness); //subscribe to the GAs Generation Complete event //ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(TerminateAlgorithm); }
private static void Main(string[] args) { for (int i = 0; i < K; i++) { Factory tmp = new Factory(names[i], 0); ListOfFactories.Add(tmp); } // GAF components const int populationSize = 25; var tasks = CreateTasks().ToList(); var population = new Population(); for (var p = 0; p < populationSize; p++) { var chromosome = new Chromosome(); foreach (var work in tasks) { chromosome.Genes.Add(new Gene(work)); } var rnd = GAF.Threading.RandomProvider.GetThreadRandom(); chromosome.Genes.ShuffleFast(rnd); population.Solutions.Add(chromosome); } var elite = new Elite(5); var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.DoublePointOrdered }; var mutate = new SwapMutate(0.02); var ga = new GeneticAlgorithm(population, CalculateFitness); ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); ga.Run(Terminate); Console.Read(); }
private static void Main(string[] args) { const double crossoverProbability = 0.85; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create a Population of 100 random chromosomes of length 44 var population = new Population(100, 44, false, false); //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability); //create the GA itself passing in the fitness function. var ga = new GeneticAlgorithm(population, EvaluateFitness); /* ------------------------------------------------------------------------------------ * if the fitness is defined in a separate assembly (see documentation), * the following class can be used to load the assembly and access the * fitness function * * var fitnessAssembly = new FitnessAssembly ("Example.IFitness.dll"); * var ga = new GeneticAlgorithm (population, fitnessAssembly.FitnessFunction); * ------------------------------------------------------------------------------------*/ //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(TerminateAlgorithm); }
public void TestGAF() { var population = new Population(); int popSize = 100; for (int i = 0; i < popSize; i++) { var tmpStock = new int[stocks.Length]; var tmpItemsCount = new int[itemsCount.Length]; stocks.CopyTo(tmpStock, 0); itemsLength.CopyTo(tmpItemsCount, 0); Debug.WriteLine("************************************"); Debug.WriteLine("Create new Chromosome"); var chromosome = new Chromosome(); for (int k = 0; k < stocks.Length; k++) { Gene gene; if (Rnd(k, ref tmpItemsCount, out gene)) chromosome.Genes.Add(gene); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } var elite = new Elite(10); var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint }; var mutate = new SwapMutate(0.02); var ga = new GeneticAlgorithm(population, CalculateFitness); ga.OnGenerationComplete += Ga_OnGenerationComplete; ga.OnRunComplete += Ga_OnRunComplete; ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); ga.Run(50); }
//En este metodo se configura los operadores y sus parametros para la corrida public void correrAlgoritmoGenetico(ProgressBar progressBar, int cantPoblacion, int cantIteraciones) { reloj.Start(); this.progress = progressBar; this.cantIteraciones = cantIteraciones; this.fitnessRequired = 630; var population = new Population(populationSize: cantPoblacion, chromosomeLength: 63, reEvaluateAll: true, useLinearlyNormalisedFitness: true, selectionMethod: ParentSelectionMethod.FitnessProportionateSelection); var crossover = new Crossover(0.4) { AllowDuplicates = true, CrossoverType = CrossoverType.SinglePoint }; var binaryMutate = new BinaryMutate(mutationProbability: 0.05D, allowDuplicates: true); var randomReplace = new RandomReplace(numberToReplace: 9, allowDuplicates: true); var elite = new Elite(1); var tempMutate = new MutacionPorTemperatura(0.01D, 0.3D, cantIteraciones, true); var ga = new GeneticAlgorithm(population, CalculateFitness) { UseMemory = false }; ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; //aca se agregan los operadores para el algoritmo genetico ga.Operators.Add(crossover); //ga.Operators.Add(randomReplace); ga.Operators.Add(tempMutate); //ga.Operators.Add(binaryMutate); ga.Operators.Add(elite); ga.Run(Terminate); }
public Elites(Elite e) { RangeId = e.RangeId; MaxLevel = e.MaxLevel; Hp = e.Hp; MaxHp = e.MaxHp; Def = e.Def; MaxDef = e.MaxDef; MagicResistance = e.MagicResistance; Cost = e.Cost; BlockCnt = e.BlockCnt; RespawnTime = e.RespawnTime; EliteCosts = new List <EliteCost>(); if (e.EvolveCosts != null) { foreach (EvolveCost ec in e.EvolveCosts) { EliteCosts.Add(new EliteCost(ec)); } } }
public EliteBinds() { // TODO: move hard-coded file names to defines or similar var bindsFile = Elite.getBindsFilename(); // TODO: do something if file not found var bindsTree = XElement.Load(bindsFile); _bindList = new Dictionary<string, List<string>>(); foreach (var element in bindsTree.Elements()) { var keys = ParseBindControlNode(element); if (keys == null) continue; _bindList.Add(element.Name.LocalName, keys); } _bindList.Add("HUD", new List < string >{ "LeftControl", "LeftAlt", "G" } ); _bindList.Add("FrameRate", new List<string> { "LeftControl", "F" }); _bindList.Add("ConnectionStatus", new List<string> { "LeftControl", "B" }); _bindList.Add("Snapshot", new List<string> { "F10" }); _bindList.Add("HighResSnapshot", new List<string> { "LeftAlt", "F10" }); _bindList.Add("CloseQuickComms", new List<string> { "Esc" }); // TODO: look at version in file and balk if unknown }
static void ga() { vrange = new double[6]; vrange[1] = GAF.Math.GetRangeConstant(p.geo_amax - p.geo_amin, 10); vrange[2] = GAF.Math.GetRangeConstant(p.geo_tmax - p.geo_tmin, 10); vrange[3] = GAF.Math.GetRangeConstant(p.geo_bwmax - p.geo_bwmin, 10); vrange[4] = GAF.Math.GetRangeConstant(p.geo_lmax - p.geo_lmin, 10); vrange[5] = GAF.Math.GetRangeConstant(p.geo_nlmax - p.geo_nlmin, 10); var pop = new Population(p.ga_pop, 50); var elite = new Elite(Convert.ToInt32(p.ga_elit)); var crossover = new Crossover(p.ga_cros); var mutacao = new BinaryMutate(p.ga_mut); var ag = new GeneticAlgorithm(pop, fapt2d); ag.Operators.Add(elite); ag.Operators.Add(crossover); ag.Operators.Add(mutacao); ag.OnGenerationComplete += geracao2d; Console.WriteLine("----------------------------------"); Console.WriteLine("Starting..."); Console.WriteLine("----------------------------------"); ag.Run(fim2d); }
public static void Main(string[] args) { _ads = SetupAppDomain(); const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create the population //var population = new Population(100, 44, false, false); var population = new Population(); //create the chromosomes for (var p = 0; p < 10; p++) { var chromosome = new Chromosome(); for (int i = 0; i < 2; i++) { ConfigVars v = new ConfigVars(); v.vars ["EMA_VAR1"] = RandomNumberBetweenInt(0, 20); v.vars ["EMA_VAR2"] = RandomNumberBetweenInt(0, 100); //v.vars ["LTD3"] = RandomNumberBetweenInt (0, 100); //v.vars ["LTD4"] = RandomNumberBetweenInt (2, 200); chromosome.Genes.Add(new Gene(v)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, CalculateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline // ga.Operators.Add(elite); // ga.Operators.Add(crossover); // ga.Operators.Add(mutation); var cv_operator = new ConfigVarsOperator(); ga.Operators.Add(cv_operator); //run the GA ga.Run(Terminate); }
public void RunGAInstance() { // We can create an empty population as we will be creating the // initial solutions manually. var population = new Population(); // Create the chromosomes. for (var p = 0; p < POPULATION_SIZE; p++) { var chromosome = new Chromosome(); for (var g = 0; g < NUMBER_OF_CITIES; g++) { chromosome.Genes.Add(new Gene(g)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } // Create the elite operator. var elite = new Elite(5); // Create the crossover operator. var crossover = new Crossover(CROSSOVER_PROBABILITY) { CrossoverType = CrossoverType.DoublePointOrdered }; // Create the mutation operator. var mutate = new SwapMutate(MUTATION_PROBABILITY); // Create the GA. var ga = new GeneticAlgorithm(population, CalculateFitness); // Hook up to some useful events. ga.OnGenerationComplete += ga_OnGenerationComplete; ga.OnRunComplete += ga_OnRunComplete; // Add the operators. ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutate); // Begin timing. STOPWATCH.Restart(); // Run the GA. ga.Run(Terminate); }
public static void Main(string[] args) { _ads = SetupAppDomain (); const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create the population //var population = new Population(100, 44, false, false); var population = new Population(); //create the chromosomes for (var p = 0; p < 10; p++) { var chromosome = new Chromosome(); for (int i = 0; i < 2; i++) { ConfigVars v = new ConfigVars (); v.vars ["EMA_VAR1"] = RandomNumberBetweenInt (0, 20); v.vars ["EMA_VAR2"] = RandomNumberBetweenInt (0, 100); //v.vars ["LTD3"] = RandomNumberBetweenInt (0, 100); //v.vars ["LTD4"] = RandomNumberBetweenInt (2, 200); chromosome.Genes.Add (new Gene (v)); } chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, CalculateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline // ga.Operators.Add(elite); // ga.Operators.Add(crossover); // ga.Operators.Add(mutation); var cv_operator = new ConfigVarsOperator (); ga.Operators.Add (cv_operator); //run the GA ga.Run(Terminate); }
public void EvaluateProbe(List<IPosOnlyFeedback> test_probe_data, List<IPosOnlyFeedback> training_probe_data, List<IList<int>> test_users, List<IMapping> user_mapping, List<IMapping> item_mapping, int n = -1) { List<IList<int>> candidate_items = new List<IList<int>>(); List<RepeatedEvents> repeated_events = new List<RepeatedEvents>(); List<IBooleanMatrix> training_user_matrix = new List<IBooleanMatrix>(); List<IBooleanMatrix> test_user_matrix = new List<IBooleanMatrix>(); for (int i = 0; i < m_recommenders.Count; i++) { candidate_items.Add(new List<int>(test_probe_data[i].AllItems.Union(training_probe_data[i].AllItems))); repeated_events.Add(RepeatedEvents.No); if (candidate_items[i] == null) throw new ArgumentNullException("candidate_items"); if (test_probe_data[i] == null) test_users[i] = test_probe_data[i].AllUsers; training_user_matrix.Add(training_probe_data[i].UserMatrix); test_user_matrix.Add(test_probe_data[i].UserMatrix); } int num_users = 0; var result = new ItemRecommendationEvaluationResults(); // make sure that the user matrix is completely initialized before entering parallel code foreach (int user_id in test_users[0]) { string original = user_mapping[0].ToOriginalID(user_id); List<IList<Tuple<int, float>>> list_of_predictions = new List<IList<Tuple<int, float>>>(); HashSet<int> correct_items = new HashSet<int>(); List<HashSet<int>> ignore_items_for_this_user = new List<HashSet<int>>(); List<int> num_candidates_for_this_user = new List<int>(); correct_items = new HashSet<int>(test_user_matrix[0][user_id]); correct_items.IntersectWith(candidate_items[0]); for (int i = 0; i < m_recommenders.Count; i++) { int internalId = user_mapping[i].ToInternalID(original); ignore_items_for_this_user.Add(new HashSet<int>(training_user_matrix[i][internalId])); /* if (correct_items[i].Count == 0) continue; */ ignore_items_for_this_user[i].IntersectWith(candidate_items[i]); num_candidates_for_this_user.Add(candidate_items[i].Count - ignore_items_for_this_user[i].Count); /*if (correct_items[i].Count == num_candidates_for_this_user[i]) continue; */ //Recomenda var listaRecomendacao = m_recommenders[i].Recommend(user_id, candidate_items: candidate_items[i], n: n, ignore_items: ignore_items_for_this_user[i]); for (int j = 0; j < listaRecomendacao.Count; j++) { string idOriginal = item_mapping[i].ToOriginalID(listaRecomendacao[j].Item1); int idMappingZero = item_mapping[0].ToInternalID(idOriginal); Tuple<int, float> tupla = new Tuple<int, float>(idMappingZero, listaRecomendacao[j].Item2); listaRecomendacao[j] = tupla; } list_of_predictions.Add(listaRecomendacao); } //Usar o melhor double maiorMapping = 0; int idMaiorMapping = 0; //Testar cada individual for (int k = 0; k < list_of_predictions.Count; k++) { int[] prediction_probe = (from t in list_of_predictions[k] select t.Item1).ToArray(); double resultado = PrecisionAndRecall.AP(prediction_probe, correct_items); if (resultado > maiorMapping) { maiorMapping = resultado; idMaiorMapping = k; } } //Set global so Fitness itens can see. list_prediction_probes = list_of_predictions; correct_items_global = correct_items; //Algortimo Genetico /* // Crossover = 80% // Mutation = 5% // Population size = 100 // Generations = 2000 // Genome size = 2 GA ga = new GA(0.8, 0.05, 40, 400, list_prediction_probes.Count); ga.FitnessFunction = new GAFunction(Fitness); //ga.FitnessFile = @"H:\fitness.csv"; ga.Elitism = true; ga.Go(); double[] values; double fitness; ga.GetBest(out values, out fitness);*/ //create the GA using an initialised population and user defined Fitness Function const double crossoverProbability = 0.85; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create a Population of random chromosomes of length 44 var population = new Population(40, list_of_predictions.Count * 10, false, false); //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.DoublePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, CalculateFitness); //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(Terminate); var best = population.GetTop(1)[0]; double rangeConst = 1 / (System.Math.Pow(2, 10) - 1); ga_weights[original] = new List<double>(); for (int i = 0; i < list_prediction_probes.Count; i++) { string str = best.ToBinaryString((i * 10), 10); Int64 convertInt32 = Convert.ToInt32(str, 2); double x = (convertInt32 * rangeConst); ga_weights[original].Add(x); } best_alg[original] = idMaiorMapping; num_users++; if (num_users % 10 == 0) Console.Error.Write("."); if (num_users % 100 == 0) Console.Error.WriteLine(""); } }
public void Initialize() { _maxEvaluation = SolverParameter.MaxEvaluation; _initialPopulationCount = SolverParameter.InitialPopulationCount; eliteOperator = new Elite(SolverParameter.ElitePercentage); crossoverOperator = new Crossover(SolverParameter.CrossoverProbability) { CrossoverType = CrossoverType.DoublePointOrdered }; mutateOperator = new SwapMutate(SolverParameter.MutationProbability); CuttingWidth = SolverParameter.CuttingWidth; MiniLength = SolverParameter.MiniLength; internalInit(); }
public static void Main(string[] args) { //Initialize: string mode = "RELEASE"; var liveMode = Config.GetBool("live-mode"); #if DEBUG mode = "DEBUG"; #endif // Console.WriteLine("Running " + algorithm + "..."); Config.Set("live-mode", "false"); Config.Set("messaging-handler", "QuantConnect.Messaging.Messaging"); Config.Set("job-queue-handler", "QuantConnect.Queues.JobQueue"); Config.Set("api-handler", "QuantConnect.Api.Api"); //Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.OptimizationResultHandler"); Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.ConsoleResultHandler"); Config.Set("EMA_VAR1", "10"); _ads = SetupAppDomain(); //rc = new RunClass(); const double crossoverProbability = 0.65; const double mutationProbability = 0.08; const int elitismPercentage = 5; //create the population //var population = new Population(100, 44, false, false); var population = new Population(); //create the chromosomes for (var p = 0; p < 100; p++) { var chromosome = new Chromosome(); for (int i = 0; i < 100; i++) chromosome.Genes.Add(new Gene(i)); chromosome.Genes.ShuffleFast(); population.Solutions.Add(chromosome); } //create the genetic operators var elite = new Elite(elitismPercentage); var crossover = new Crossover(crossoverProbability, true) { CrossoverType = CrossoverType.SinglePoint }; var mutation = new BinaryMutate(mutationProbability, true); //create the GA itself var ga = new GeneticAlgorithm(population, CalculateFitness); //subscribe to the GAs Generation Complete event ga.OnGenerationComplete += ga_OnGenerationComplete; //add the operators to the ga process pipeline ga.Operators.Add(elite); ga.Operators.Add(crossover); ga.Operators.Add(mutation); //run the GA ga.Run(Terminate); }