public void Simulate(int count, int length, int min, int max, int maxGeneration) { m_Population = new Population(count, length, min, max); m_Population.Evaluate(Fitness); Debug.Log(m_Population); while (m_Population.Generation < maxGeneration) { do { IChromosome parent1 = Selection.Select(m_Population); IChromosome parent2 = Selection.Select(m_Population); IChromosome offspring1, offspring2; Crossover.Crossover(parent1, parent2, out offspring1, out offspring2); Mutation.Mutate(ref offspring1, min, max); Mutation.Mutate(ref offspring2, min, max); m_Population.AddChromosomeInNewPopulation(offspring1); m_Population.AddChromosomeInNewPopulation(offspring2); } while (!m_Population.IsFullNewGeneration); m_Population.SwapGeneration(); m_Population.Evaluate(Fitness); Debug.Log(m_Population); } }
/// <summary> /// Crosses the specified parents. /// </summary> /// <param name="parents">The parents.</param> /// <returns>The result chromosomes.</returns> private IList <IChromosome> Cross(IList <IChromosome> parents) { var offspring = new List <IChromosome>(); //Console.WriteLine("Crossover probability: {0}", CrossoverProbability); for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber) { var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList(); double randomDouble = ThreadSafeRandom.ThisThreadsRandom.NextDouble(); //Console.WriteLine("Random Number generated to Cross or Not: {0}", randomDouble); // If match the probability cross is made, otherwise the offspring is an exact copy of the parents. // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can // have some rest chromosomes. if (selectedParents.Count == Crossover.ParentsNumber && randomDouble <= CrossoverProbability) { offspring.AddRange(Crossover.Cross(selectedParents)); } //else //{ // Console.WriteLine("No Crossover operation is done"); //} } return(offspring); }
public void Crossover_TwoChromosomesOnePercentProbability_CrossoverNotHappend() { var probability = 0.1m; var representation1 = new IGene <decimal> [2]; var representation2 = new IGene <decimal> [2]; var gene1Representation = new[] { 1.2m, 1.3m, 1.4m, 1.5m }; var gene2Representation = new[] { 1.6m, 1.7m, 1.8m, 1.9m }; var gene3Representation = new[] { 2.6m, 2.7m, 2.8m, 2.9m }; representation1[0] = new Gene <decimal>(gene1Representation, probability); representation1[1] = new Gene <decimal>(gene2Representation, probability); representation2[0] = new Gene <decimal>(gene1Representation, probability); representation2[1] = new Gene <decimal>(gene3Representation, probability); var x = new Chromosome <decimal>(representation1); var y = new Chromosome <decimal>(representation2); var crossover = new Crossover(0.01m); var crossed = crossover.RunCrossover(x, y, probability); Assert.AreEqual(crossed.Representation[1].Representation[0], gene2Representation[0]); Assert.AreEqual(crossed.Representation[1].Representation[1], gene2Representation[1]); Assert.AreEqual(crossed.Representation[1].Representation[2], gene2Representation[2]); Assert.AreEqual(crossed.Representation[1].Representation[3], gene2Representation[3]); }
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 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); }
public void SetCrossover(Crossover crossover, float mixProbabilityUniformCrossover = 0.5f) { switch (crossover) { case Crossover.UniformCrossover: _crossover = new GeneticSharp.Domain.Crossovers.UniformCrossover(mixProbabilityUniformCrossover); //ймовірність змішування хромосом break; case Crossover.OnePointCrossover: _crossover = new GeneticSharp.Domain.Crossovers.OnePointCrossover(); break; case Crossover.TwoPointCrossover: _crossover = new GeneticSharp.Domain.Crossovers.TwoPointCrossover(); break; case Crossover.ThreeParentCrossover: _crossover = new GeneticSharp.Domain.Crossovers.ThreeParentCrossover(); break; //case Crossover.CutAndSpliceCrossover: // _crossover = new GeneticSharp.Domain.Crossovers.CutAndSpliceCrossover(); // break; default: throw new Exception("Не існує такого виду кроссовера!"); break; } }
protected override IList <IGenome> DoProduction( IList <IGenome> sampleGenomes, GenomeProductionSession thisSession, GenomeProductionSession totalSession) { var selections = (int)Math.Ceiling((float)thisSession.requiredNb / Crossover.NbOfChildren); var totalNbToSelct = selections * Crossover.NbOfParents; Selection.Prepare( sampleGenomes, thisSession, totalSession, totalNbToSelect: totalNbToSelct); Crossover.Prepare( sampleGenomes, thisSession, totalSession); while (thisSession.CurrentlyProduced.Count < thisSession.requiredNb) { var parents = Selection.Select(Crossover.NbOfParents).ToArray(); var children = Crossover.Cross(parents); var usedChildren = thisSession.AddNewProducedGenomes(children); foreach (var child in usedChildren) { this.MutationManager.ApplyMutations(child); } } return(thisSession.CurrentlyProduced); }
/// <summary> /// Crosses the specified parents. /// </summary> /// <param name="parents">The parents.</param> /// <returns>The result chromosomes.</returns> private IList <IChromosome> Cross(IList <IChromosome> parents) { var offspring = new List <IChromosome>(); for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber) { var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList(); // If match the probability cross is made, otherwise the offspring is an exact copy of the parents. // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can // have some rest chromosomes. if (selectedParents.Count == Crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= CrossoverProbability) { offspring.AddRange(Crossover.Cross(selectedParents)); } } if (_debugging) { Console.WriteLine("{0} parents created {1} children", parents.Count, offspring.Count); if (offspring.Count < parents.Count) { Console.WriteLine("Time for debugging! This is a bp"); } } return(offspring); }
public void WhenCrossoverIsPerformed_RandomCrossover_50pcChance_ShouldBeApprox50pcCrossoverBetweenParents() { ConfigurationProvider.Crossover.ChanceOfRandomGeneCrossover = .5d; Population <bool> population = new Population <bool> (); int genomeLength = 100000; population.Initialise(2, genomeLength); population [0].Code.For((item, i) => population [0] [i] = false); population [1].Code.For((item, i) => population [1] [i] = true); double acceptableMin = (double)genomeLength * ((double)4.5d / 10); double acceptableMax = (double)genomeLength * ((double)5.5d / 10); int crossoverCount = 0; Crossover crossover = CrossoverProvider.GetCrossover(Crossover.CrossoverType.Random); var child = crossover.PerformCrossover(population [0], population [1]); child.Code.ForEach(b => crossoverCount += b ? 1 : 0); Assert.LessOrEqual(crossoverCount, acceptableMax); Assert.GreaterOrEqual(crossoverCount, acceptableMin); }
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); }
/// <summary> /// Method takes care of generating a new generation /// </summary> /// <param name="c">Method to calculate how to mutate</param> public void generateNextGeneration(Crossover c) { //Setting the elite from the previous generation Chromosome[] newGen = new Chromosome[this.popSize]; for (int i = 0; i < (this.eliteRate * this.popSize); i++) { newGen[i] = this.currentG[i]; } int indexerForGen = (int)(this.eliteRate * this.popSize); //Loops through the new gen and sets the chromosomes to offspring from the parents while (indexerForGen < this.popSize) { Chromosome firstParent = this.currentG.SelectParent(); Chromosome secondParent = this.currentG.SelectParent(); Chromosome[] mutated = firstParent.Reproduce(secondParent, c, this.mutationRate); for (int j = 0; j < mutated.Length; j++) { newGen[indexerForGen] = mutated[j]; indexerForGen++; } } //Setting the currentgeneration to the new gen this.currentG = new Generation(newGen); }
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); }
// 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 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); }
public List <Chromosome> Cross(List <Chromosome> parents) { var left = parents[0]; var right = parents[1]; return(Crossover.OnePoint(left, right, 2)); }
public List <Genome> CrossoverMutation(List <Genome> selected) { Crossover crossover = new Crossover(); List <Genome> newGenomes = new List <Genome>(); for (int i = 0; i < agents.Count - survivors; i++)//crossover and mutation { Genome parent1 = selected[Random.Range(0, selected.Count)]; //Genome child = parent1.Copy();//crossover.CrossoverGenes(parent1, parent2, gt); Genome child = null; if (Random.Range(0.0f, 1.0f) <= crossoverProbability) { Genome parent2 = selected[Random.Range(0, selected.Count)]; child = crossover.CrossoverGenes(parent1, parent2, gt); } else { child = parent1.Copy(); } //Debug.Log(child); child.Mutate(); newGenomes.Add(child); //Debug.Log(newGenomes[i]); //Debug.Log(child); } return(newGenomes); }
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 Chromosome[] Reproduce(Chromosome spouse, Crossover f, double mutationRate) { //value determines whether or not to mutate double mutate; Chromosome[] children = f(this, spouse); //iterrating through every child for (int i = 0; i < children.Length; i++) { //temporary array to store old and mutated values Allele[] temp = new Allele[this.Length]; for (int j = 0; j < children[i].Length; j++) { //Assigning the value for whether or not we should mutate mutate = Helpers.rand.NextDouble(); //Checking if mutation should happen if (mutate < mutationRate) { temp[j] = (Allele)Helpers.rand.Next(0, Enum.GetNames(typeof(Allele)).Length); } else { temp[j] = children[i][j]; } } children[i] = new Chromosome(temp); } return(children); }
/// <summary> /// Creating a vehicle object according to the input. /// </summary> /// <param name="vehicleType"></param> /// <param name="licensePlate"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="length"></param> /// <returns> a vehicle according to its data</returns> public static Vehicle GetVehicle(string vehicleType, string licensePlate, int width, int height, int length) { Vehicle vehicle = null; switch (vehicleType) { case ("motorcycle"): vehicle = new Motorcycle(licensePlate, width, height, length); break; case ("private"): vehicle = new PrivateVehicle(licensePlate, width, height, length); break; case ("crossover"): vehicle = new Crossover(licensePlate, width, height, length); break; case ("van"): vehicle = new Van(licensePlate, width, height, length); break; case ("truck"): vehicle = new Truck(licensePlate, width, height, length); break; case ("suv"): vehicle = new SUV(licensePlate, width, height, length); break; } return(vehicle); }
public CrossoverFourWayFilter(IAudioFilter source, Crossover crossover) { if (source.NumberOfChannels != 2) { throw new ArgumentException("Audio source must have 2 channels", "source"); } if (source.SampleRate != crossover.sampleRate) { throw new ArgumentException("Crossover sample rate does not match input source", "crossover"); } if (crossover.crossoverType != Crossover.CROSSOVER_TYPES.FOUR_WAY) { throw new ArgumentException("Crossover must be a FOUR_WAY type", "crossover"); } this.source = source; this.crossover = crossover; this.currentState = States.Normal; this.lastOverallPosition = 0; this.lastInputBufferPosition = -1; initializeFilterKernels(); }
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 GeneticEngine(GeneticConfig geneticConfig) { this.geneticConfig = geneticConfig; Crossover = new Crossover(geneticConfig); Mutation = new Mutation(); Selection = new Selection(geneticConfig.PopulationSize); }
public ActionResult DeleteConfirmed(int id) { Crossover crossover = db.Crossovers.Find(id); db.Crossovers.Remove(crossover); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Contrutor com os parâmetros iniciais /// </summary> public GeneticAlgorithm() { this.crossover = CrossoverPMX; this.selection = Tournament; this.rateCrossover = ConfigurationGA.rateCrossover; this.rateMutation = ConfigurationGA.rateMutation; }
public GeneticAlgorithm() { //Parametros iniciais crossover = CrossoverPMX; //selection = Tournament; rateCrossover = ConfigurationGA.rateCrossover; rateMutation = ConfigurationGA.rateMutation; }
public void WhenCustomCrossoverProviderRequested_ShouldReturnCorrectCrossover() { CrossoverProvider.AddCrossover(new CustomCrossover()); Crossover crossover = CrossoverProvider.GetCrossover(Crossover.CrossoverType.Custom); Assert.AreEqual(Crossover.CrossoverType.Custom, crossover.CrossoverMethod); }
public GeneticAlgorithm() { CrossoverDelegateFunction = CrossoverPMX; SelectionDelegateFunction = Tournament; RateCrossover = ConfigurationGA.RateCrossover; RateMutation = ConfigurationGA.RateMutation; }
private EvolutionThread() { GenerationCounter = 0; Timestamp = System.DateTime.Now; Fitness = FitnessFunctionFactory.CreateDefaultFunction(); Crossover = CrossoverFactory.CreateDefaultCrossover(); Mutation = MutationFactory.CreateDefaultMutation(); }
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(); }
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); }
public List <Strategy> CrossoverStrategies(List <Strategy> strategies) { var result = new List <Strategy>(); result.AddRange(Crossover.GetPanmixia(strategies)); result.AddRange(Crossover.GetInbreed(strategies)); result.AddRange(Crossover.GetOutbreed(strategies)); return(result); }
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 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); }
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); }
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 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 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 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(""); } }