public override bool EquivalentTo(IFitness fitness) { var other = (NSGA2MultiObjectiveFitness)fitness; return((Rank == ((NSGA2MultiObjectiveFitness)fitness).Rank) && (Sparsity == other.Sparsity)); }
/// <summary> /// Constructor for genetic algorithm. /// Genetic algorithms imitate natural biological processes, /// </summary> /// <param name="population">Init population. </param> /// <param name="fitness">Fitness.</param> /// <param name="selection">Selection operator.</param> /// <param name="xover">Xover operator.</param> /// <param name="mutation">Mutation operator.</param> /// <param name="elitizmus">Elitizmus.</param> /// <param name="termination">Termination GA.</param> /// <param name="executor">Executor.</param> /// <param name="mutationProbability">Mutation probability.</param> /// <param name="xoverProbability">Xover probability.</param> public GeneticAlgorithm(IPopulation population, IFitness fitness, ISelection selection, IXover xover, IMutation mutation, IElite elitizmus, ITermination termination, IExecutor executor, float mutationProbability, float xoverProbability) { Population = population; this.fitness = fitness; this.selection = selection; this.xover = xover; this.mutation = mutation; this.elitizmus = elitizmus; this.executor = executor; this.termination = termination; // base probability this.xoverProbability = xoverProbability; this.mutationProbability = mutationProbability; TimeEvolving = TimeSpan.Zero; CurrentGenerationsNumber = 1; }
private GeneticAlgorithm RunGeneticAlgorithm(Population population, IFitness fitness, int generations) { var selection = new EliteSelection(); var crossover = new TwoPointCrossover(); var mutation = new ReverseSequenceMutation(); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation) { Termination = new GenerationNumberTermination(generations), TaskExecutor = new ParallelTaskExecutor() { MinThreads = 100, MaxThreads = 250 }, }; var latestFitness = 0.0; ga.GenerationRan += (sender, e) => { var bestfitness = ga.BestChromosome.Fitness ?? 0; if (bestfitness != latestFitness) { latestFitness = bestfitness; testOutputHelper.WriteLine($"Current best fitness: {bestfitness}"); } }; ga.Start(); return(ga); }
public void Initialize() { game = GameObject.FindObjectOfType(typeof(GameBehaviourScript)) as GameBehaviourScript; switch (Args.GameMode) { case GameMode.Simple1v1WithoutBall: { new Optimizer1v1WithoutBall().Initialize(); fitnessCounter = new Fitness1v1WithoutBall(); } break; case GameMode.Simple1v1WithBall: { new Optimizer1v1WithBall().Initialize(); fitnessCounter = new FitnessSimple1v1WithBall(); } break; case GameMode.Simple1v1Play: { new Optimizer1v1WithoutBall().Initialize(); fitnessCounter = new FitnessSimple1v1Play(); } break; case GameMode.Simple2v2WithoutBall: { new Optimizer2v2WithoutBall().Initialize(); fitnessCounter = new FitnessSimple2v2Play(); } break; } }
public void Evaluate(IFitness fitnessFunction) { foreach (IChromosome chromosome in m_Chromosomes) { chromosome.EvaluateFitness(fitnessFunction); } }
/// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.GeneticAlgorithm"/> class. /// </summary> /// <param name="population">The chromosomes population.</param> /// <param name="fitness">The fitness evaluation function.</param> /// <param name="selection">The selection operator.</param> /// <param name="crossover">The crossover operator.</param> /// <param name="mutation">The mutation operator.</param> public GeneticAlgorithm( IPopulation population, IFitness fitness, ISelection selection, ICrossover crossover, IMutation mutation) { ExceptionHelper.ThrowIfNull("population", population); ExceptionHelper.ThrowIfNull("fitness", fitness); ExceptionHelper.ThrowIfNull("selection", selection); ExceptionHelper.ThrowIfNull("crossover", crossover); ExceptionHelper.ThrowIfNull("mutation", mutation); Population = population; Fitness = fitness; Selection = selection; Crossover = crossover; Mutation = mutation; Reinsertion = new ElitistReinsertion(); Termination = new GenerationNumberTermination(1); CrossoverProbability = DefaultCrossoverProbability; MutationProbability = DefaultMutationProbability; TimeEvolving = TimeSpan.Zero; State = GeneticAlgorithmState.NotStarted; TaskExecutor = new LinearTaskExecutor(); }
/// <summary> /// Main program. /// </summary> static void Main(string[] args) { // Get the selected fitness type. IFitness myFitness = GetFitnessMethod(); // Genetic algorithm setup. _ga = new GA(_crossoverRate, _mutationRate, 100, 10000000, _genomeSize); // Get the target fitness for this method. _targetFitness = myFitness.TargetFitness; // Run the genetic algorithm and get the best brain. string program = GAManager.Run(_ga, fitnessFunction, OnGeneration); // Display the final program. Console.WriteLine(program); Console.WriteLine(); // Compile to executable. BrainPlus.Compile(program, "output.exe", myFitness); // Run the result for the user. string result = myFitness.RunProgram(program); Console.WriteLine(result); Console.ReadKey(); }
public void Configure(IFitness fItness, IMutate mutate, ICrossover crossover, ISelection selection) { Mutate = mutate; Crossover = crossover; Fitness = fItness; Selection = selection; }
// Take the N copies of the original individuals and fold their fitnesses back into the original // individuals, replacing them with the original individuals in the process. See expand(...) void Contract(IEvolutionState state) { // swap back Population pop = state.Population; state.Population = oldpop; // merge fitnesses again for (int i = 0; i < pop.Subpops.Count; i++) { IFitness[] fits = new IFitness[numTests]; for (int j = 0; j < state.Population.Subpops[i].Individuals.Count; j++) { for (int k = 0; k < numTests; k++) { fits[k] = pop.Subpops[i].Individuals[numTests * j + k].Fitness; } if (mergeForm == MERGE_MEAN) { state.Population.Subpops[i].Individuals[j].Fitness.SetToMeanOf(state, fits); } else if (mergeForm == MERGE_MEDIAN) { state.Population.Subpops[i].Individuals[j].Fitness.SetToMedianOf(state, fits); } else // MERGE_BEST { state.Population.Subpops[i].Individuals[j].Fitness.SetToBestOf(state, fits); } state.Population.Subpops[i].Individuals[j].Evaluated = true; } } }
static async Task Main(string[] args) { Console.WriteLine($"[{DateTime.Now}] Tuner start"); SettingsLoader.Init("settings.json"); IFitness fitness = null; IChromosome chromosome = null; _webService = new WebService(); await _webService.EnableIfAvailable(); _testId = await _webService.RegisterTest(new RegisterTestRequest { Type = TestType.Texel }); var scalingFactorMode = args.Contains("scaling_factor"); if (scalingFactorMode) { SettingsLoader.Data.Genes.Clear(); SettingsLoader.Data.Genes.Add(new GeneInfo { Name = "ScalingFactor", MinValue = 0, MaxValue = 2000 }); SettingsLoader.Data.Genes.Add(new GeneInfo { Name = "Unused", MinValue = 0, MaxValue = 1 }); fitness = new ScalingFactorFitness(_testId, _webService); chromosome = new ScalingFactorChromosome(); } else { fitness = new EvaluationFitness(_testId, _webService); chromosome = new EvaluationChromosome(); } var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new UniformMutation(true); var population = new Population(SettingsLoader.Data.MinPopulation, SettingsLoader.Data.MaxPopulation, chromosome); var geneticAlgorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation); geneticAlgorithm.Termination = new GenerationNumberTermination(SettingsLoader.Data.GenerationsCount); geneticAlgorithm.GenerationRan += GeneticAlgorithm_GenerationRan; _generationStopwatch = new Stopwatch(); _generationStopwatch.Start(); geneticAlgorithm.Start(); Console.WriteLine("Best solution found has {0} fitness.", geneticAlgorithm.BestChromosome.Fitness); Console.ReadLine(); }
/// <summary> /// Constructor for DE. /// </summary> /// <param name="fitness">Fitness func.</param> /// <param name="population">Init pop</param> public DifferentialEvolution(IFitness fitness, IPopulation population) : base(fitness, population) { this.XoverProbability = 0.01; this.F = 0.5; termination = new TerminationMaxNumberGeneration(); termination.InitializeTerminationCondition(15_000); }
/// <summary> /// Most of the rules for a GA implementation need to be here. Most of the other parts should be relatively loosely coupled to a specific implementation or set of parameters /// </summary> /// <param name="db">Database which the algorithm is going to be run on</param> /// <param name="selector"></param> public FlatTestAlgorithm(IFitness selector) : base() { //Setup params for most of the class here: _matingPool = new Population(_selector); _selector = selector ?? throw new ArgumentNullException(nameof(selector)); _flatFactory = (validColumn, validData) => new FlatIndividual(PerformanceTester.ValidColumnGetter(), PerformanceTester.ValidDataGetter); _population = new Population(PerformanceTester.ValidColumnGetter(), PerformanceTester.ValidDataGetter, _selector, _flatFactory); }
/// <summary> /// Returns true if I'm equivalent in fitness (neither better nor worse) /// to _fitness. The rule I'm using is this: /// If one of us is better in one or more criteria, and we are equal in /// the others, then equivalentTo is false. If each of us is better in /// one or more criteria each, or we are equal in all criteria, then /// equivalentTo is true. /// </summary> public override bool EquivalentTo(IFitness fitness) { var other = (MultiObjectiveFitness)fitness; var abeatsb = false; var bbeatsa = false; if (Objectives.Length != other.Objectives.Length) { throw new InvalidOperationException( "Attempt made to compare two multiobjective fitnesses; but they have different numbers of objectives."); } for (var x = 0; x < Objectives.Length; x++) { if (Maximize[x] != other.Maximize[x]) // uh oh { throw new InvalidOperationException( "Attempt made to compare two multiobjective fitnesses; but for objective #" + x + ", one expects higher values to be better and the other expectes lower values to be better."); } if (Maximize[x]) { if (Objectives[x] > other.Objectives[x]) { abeatsb = true; } if (Objectives[x] < other.Objectives[x]) { bbeatsa = true; } if (abeatsb && bbeatsa) { return(true); } } else { if (Objectives[x] < other.Objectives[x]) { abeatsb = true; } if (Objectives[x] > other.Objectives[x]) { bbeatsa = true; } if (abeatsb && bbeatsa) { return(true); } } } if (abeatsb || bbeatsa) { return(false); } return(true); }
public EVA(IFitness fitness, IPopulation population) { this.fitness = fitness; this.population = population; TimeEvolving = TimeSpan.Zero; executor = new LinearExecutor(); CurrentGenerationsNumber = 1; }
/// <summary> /// Initializes a new instance of the <see cref="AutoConfigFitness"/> class. /// </summary> /// <param name="targetFitness">The target fitness.</param> /// <param name="targetChromosome">The target chromosome.</param> public AutoConfigFitness(IFitness targetFitness, IChromosome targetChromosome) { m_targetFitness = targetFitness; m_targetChromosome = targetChromosome; PopulationMinSize = 100; PopulationMaxSize = 100; Termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(30)); TaskExecutor = new LinearTaskExecutor(); }
UsingEvaluation <TIndividual, TGeneStructure, TGene>( this IEvolutionaryAlgorithm <TIndividual, TGeneStructure, TGene> algo, IFitness <TIndividual, TGeneStructure, TGene> fitness) where TIndividual : IIndividual <TGeneStructure, TGene> where TGeneStructure : ICloneable { algo.Fitness = fitness; return(algo); }
public void Evaluate(IFitness <T> fitnessFunction) { foreach (IChromosome <T> chromosome in m_Chromosomes) { chromosome.EvaluateFitness(fitnessFunction); } //m_Chromosomes.Sort(); }
public GeneticSolver(IPopulationFactory populationFactory, IFitness fitness, int maxEpoch = 10, int stagnantGenerationsNumber = 30, int maxFitness = int.MaxValue) { _populationFactory = populationFactory; _fitness = fitness; StagnantGenerationsNumber = stagnantGenerationsNumber; MaxFitness = maxFitness; MaxEpoch = maxEpoch; }
/// <summary> /// Most of the rules for a GA implementation need to be here. Most of the other parts should be relatively loosely coupled to a specific implementation or set of parameters /// </summary> /// <param name="db">Database which the algorithm is going to be run on</param> /// <param name="selector"></param> public TreeSelectionAlgorithm(DBAccess db, IFitness selector) : base() { //Setup params for most of the class here: _population = new Population(db.ValidColumnGetter(), db.ValidDataGetter, _selector, (validCols, validData) => new TreeIndividual(validCols, validData)); _matingPool = new Population(_selector); _db = db; _selector = selector ?? throw new ArgumentNullException(nameof(selector)); _treeFactory = (validColumn, validData) => new TreeIndividual(db.ValidColumnGetter(), db.ValidDataGetter); }
private void ResetSample() { m_sampleContext.Population = null; var r = drawingArea.Allocation; m_sampleContext.DrawingArea = new Rectangle(0, 100, r.Width, r.Height - 100); m_sampleController.Reset(); m_fitness = m_sampleController.CreateFitness(); UpdateSample(); }
/// <summary> /// Evolutionary strategy /// </summary> /// <param name="fitness">fit. func.</param> /// <param name="population">init pop</param> public ES_μ_λ(IFitness fitness, IPopulation population) : base(fitness, population) { xover = new XoverUniform(); elite = new EliteByFitness(0.1); selection = new SelectionTournament(); termination = new TerminationMaxNumberGeneration(); termination.InitializeTerminationCondition(15_000); mutationProbability = 0.01f; xoverProbability = 0.5f; }
/// The following methods handle modifying the auxillary data when the /// genome is messed around with. void ResetAuxillaryInformation() { Neighborhood = null; NeighborhoodBestGenome = null; NeighborhoodBestFitness = null; PersonalBestGenome = null; PersonalBestFitness = null; for (int i = 0; i < Velocity.Length; i++) { Velocity[i] = 0.0; } }
public Genetic(Population _population, ISelection _selection, ICrossover _crossover, IFitness _fitness, Elitisme _elitisme, Mutation _mutation, bool _elit) { selection = _selection; crossover = _crossover; mutation = _mutation; population = _population; fitness = _fitness; elitisme = _elitisme; elit = _elit; fitness.Calculate(population.Seeds); }
/// <summary> /// Parallel fitness evaluation. /// </summary> /// <param name="fitness">Fitness.</param> /// <param name="population">Input Population</param> public override void EvaluateFitness(IFitness fitness, IList <IIndividual> population) { Parallel.ForEach(population, ind => { if (!ind.Fitness.HasValue) { ind.Fitness = fitness.Evaluate(ind); } }); // population.Individuals = population.Individuals.OrderByDescending(c => c.Fitness.Value).ToList(); }
public void Update(IEvolutionState state, int subpop, int myindex, int thread) { // update personal best if (PersonalBestFitness == null || Fitness.BetterThan(PersonalBestFitness)) { PersonalBestFitness = (Fitness)Fitness.Clone(); PersonalBestGenome = (double[])genome.Clone(); } // initialize Neighborhood if it's not been created yet PSOBreeder psob = (PSOBreeder)state.Breeder; if (Neighborhood == null || psob.Neighborhood == PSOBreeder.C_NEIGHBORHOOD_RANDOM_EACH_TIME) { if (psob.Neighborhood == PSOBreeder.C_NEIGHBORHOOD_RANDOM ) // "random" scheme is the only thing that is available for now { Neighborhood = CreateRandomPattern(myindex, psob.IncludeSelf, state.Population.Subpops[subpop].Individuals.Count, psob.NeighborhoodSize, state, thread); } else if (psob.Neighborhood == PSOBreeder.C_NEIGHBORHOOD_TOROIDAL || psob.Neighborhood == PSOBreeder.C_NEIGHBORHOOD_RANDOM_EACH_TIME) { Neighborhood = CreateToroidalPattern(myindex, psob.IncludeSelf, state.Population.Subpops[subpop].Individuals.Count, psob.NeighborhoodSize); } else // huh? { state.Output.Fatal("internal error: invalid PSO Neighborhood style: " + psob.Neighborhood); } } // identify Neighborhood best NeighborhoodBestFitness = Fitness; // initially me NeighborhoodBestGenome = genome; for (int i = 0; i < Neighborhood.Length; i++) { int ind = Neighborhood[i]; if (state.Population.Subpops[subpop].Individuals[ind].Fitness.BetterThan(Fitness)) { NeighborhoodBestFitness = state.Population.Subpops[subpop].Individuals[ind].Fitness; NeighborhoodBestGenome = ((DoubleVectorIndividual)(state.Population.Subpops[subpop].Individuals[ind])) .genome; } } // clone Neighborhood best NeighborhoodBestFitness = (Fitness)(NeighborhoodBestFitness.Clone()); NeighborhoodBestGenome = (double[])(NeighborhoodBestGenome.Clone()); }
public int CompareConstraintViolations(IFitness x, IFitness y) { if (x.ConstraintViolation > 0 && y.ConstraintViolation > 0) { var comparison = x.ConstraintViolation.CompareTo(y.ConstraintViolation); return(comparison); } if (x.ConstraintViolation > 0) { return(1); } return(-1); }
/// <summary> /// Linear fitness evaluation. /// </summary> /// <param name="fitness">Fitness.</param> /// <param name="population">Input Population</param> public virtual void EvaluateFitness(IFitness fitness, IList <IIndividual> population) { foreach (var ind in population) { //non-fitness value if (!ind.Fitness.HasValue) { // recalculation fitness for cur. individual ind.Fitness = fitness.Evaluate(ind); } } // sorts population by fitness // population.Individuals = population.Individuals.OrderByDescending(c => c.Fitness.Value).ToList(); }
/// <summary> /// Compare two multiobjective fitness value nondominated pareto way /// </summary> /// <returns>1 if y dominates x, -1 if x dominates y, 0 otherwise</returns> public int Compare(IFitness x, IFitness y) { if (ConstraintsAreViolated(x, y)) { return(CompareConstraintViolations(x, y)); } if (Dominates(x, y)) { return(1); } if (Dominates(y, x)) { return(-1); } return(0); }
private void ShowResult(IChromosome chromosome, IFitness fitness) { for (var i = 0; i < 30; i++) { Console.Write(fitness.Evaluate(chromosome) + " "); foreach (var gene in chromosome.GetGenes()) { var server = (Server)gene.Value; var serviceNames = server.Services.Select(x => x.Name.ToString()).ToList(); Console.Write("Сервер - " + server.Name + ":{ "); serviceNames.ForEach(x => Console.Write(x + ";")); Console.Write("} "); } Console.WriteLine(); Console.WriteLine("Next"); } }
/// <summary> /// We specify the tournament selection criteria, Rank (lower /// values are better) and Sparsity (higher values are better) /// </summary> /// <param name="fitness"></param> /// <returns></returns> public override bool BetterThan(IFitness fitness) { var other = (NSGA2MultiObjectiveFitness)fitness; // Rank should always be minimized. if (Rank < ((NSGA2MultiObjectiveFitness)fitness).Rank) { return(true); } if (Rank > ((NSGA2MultiObjectiveFitness)fitness).Rank) { return(false); } // otherwise try sparsity return(Sparsity > other.Sparsity); }
public Population(IFitness<Gene> pFitness, int pSize, int pMutationRate, bool pUse2PointCrossOver, DateTime pInitialDate, DateTime pFinalDate, string pStrPriority) { IIndividual<Gene> lvIndividual = null; bool lvValidIndividual = false; mFitness = pFitness; mMutationRate = pMutationRate; USE_CROSSOVER_2_PONTOS = pUse2PointCrossOver; mInitialDate = pInitialDate; mFinalDate = pFinalDate; mPriority = new Dictionary<string, int>(); if (DateTime.Now.Date == mInitialDate.Date) { mDateRef = DateTime.Now; } else { mDateRef = mFinalDate; } if (!bool.TryParse(ConfigurationManager.AppSettings["ALLOW_NO_DESTINATION_TRAIN"], out mAllowNoDestinationTrain)) { mAllowNoDestinationTrain = true; } if (!double.TryParse(ConfigurationManager.AppSettings["INVALID_FITNESS_VALUE"], out mInvalidIndividualFitness)) { mInvalidIndividualFitness = 10000.0; } if (!Int32.TryParse(ConfigurationManager.AppSettings["INITIAL_VALID_COORDINATE"], out mInitialValidCoordinate)) { mInitialValidCoordinate = Int32.MinValue; } if (!Int32.TryParse(ConfigurationManager.AppSettings["END_VALID_COORDINATE"], out mInitialValidCoordinate)) { mEndValidCoordinate = Int32.MaxValue; } mStopLocationOcupation = new Dictionary<StopLocation, HashSet<Gene>>(); mStopLocationDeparture = new Dictionary<StopLocation, Gene[]>(); foreach (StopLocation lvStopLocation in StopLocation.GetList()) { mStopLocationOcupation.Add(lvStopLocation, new HashSet<Gene>()); mStopLocationDeparture.Add(lvStopLocation, new Gene[lvStopLocation.Capacity]); } LoadTrainList(pStrPriority); DebugLog.Logar(" "); DebugLog.Logar("Gerando Individuos:"); mSize = pSize; mIndividuals = new List<IIndividual<Gene>>(); for (int i = 0; i < pSize; i++) { lvIndividual = new TrainIndividual(mFitness, mDateRef, mStopLocationOcupation, mStopLocationDeparture); DebugLog.Logar("Individuo " + lvIndividual.GetUniqueId() + ":"); lvValidIndividual = lvIndividual.GenerateIndividual(mTrainList, mPlanList); DebugLog.Logar("Individuo Info = " + lvIndividual.ToString()); DebugLog.Logar(" "); if (lvValidIndividual) { mIndividuals.Add(lvIndividual); } } DebugLog.Logar(" "); }
/// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.GeneticAlgorithm"/> class. /// </summary> /// <param name="population">The chromosomes population.</param> /// <param name="fitness">The fitness evaluation function.</param> /// <param name="selection">The selection operator.</param> /// <param name="crossover">The crossover operator.</param> /// <param name="mutation">The mutation operator.</param> public GeneticAlgorithm( Population population, IFitness fitness, ISelection selection, ICrossover crossover, IMutation mutation) { ExceptionHelper.ThrowIfNull("Population", population); ExceptionHelper.ThrowIfNull("fitness", fitness); ExceptionHelper.ThrowIfNull("selection", selection); ExceptionHelper.ThrowIfNull("crossover", crossover); ExceptionHelper.ThrowIfNull("mutation", mutation); Population = population; Fitness = fitness; Selection = selection; Crossover = crossover; Mutation = mutation; Reinsertion = new ElitistReinsertion(); Termination = new GenerationNumberTermination(1); CrossoverProbability = DefaultCrossoverProbability; MutationProbability = DefaultMutationProbability; TimeEvolving = TimeSpan.Zero; State = GeneticAlgorithmState.NotStarted; TaskExecutor = new LinearTaskExecutor(); }
/// <summary> /// Compiles brainfuck code into an executable. /// </summary> /// <param name="program">Brainfuck source code</param> /// <param name="pathName">Executable file path</param> /// <param name="fitness">IFitness</param> /// <param name="includeHeader">True to display the header (Brainfuck .NET Compiler 1.0, Created by ...).</param> public static void Compile(string program, string pathName, IFitness fitness, bool includeHeader = true) { Compile(program, pathName, fitness.GetType().Name, fitness.GetConstructorParameters()); }
/// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.Fitnesses.FitnessException"/> class. /// </summary> /// <param name="fitness">The fitness where occurred the error.</param> /// <param name="message">The error message.</param> /// <param name="innerException">Inner exception.</param> public FitnessException(IFitness fitness, string message, Exception innerException) : base("{0}: {1}".With(fitness != null ? fitness.GetType().Name : String.Empty, message), innerException) { Fitness = fitness; }