public void Initialize(FitnessFunction func, int dim = 2, int iterations = 100000, int scoutsCount = 10, int bestAgentsCount = 5, int eliteAgentsCount = 2, int bestPatchesCount = 3, int elitePatchesCount = 2, double patchSize = 1) { PatchSize = patchSize; Size = scoutsCount + bestAgentsCount * bestPatchesCount + eliteAgentsCount * elitePatchesCount; Iterations = iterations; BestAgentsCount = bestAgentsCount; EliteAgentsCount = eliteAgentsCount; BestPatchesCount = bestPatchesCount; ElitePatchesCount = elitePatchesCount; FitFunction = FitnessFunctions.RosenbrocsSaddle; Dimension = dim; CurrentIteration = 0; Fitness = Double.MaxValue; Position = new Point(dim); PrevAverageFitness = double.MaxValue; // first agents initialization for (int i = 0; i < scoutsCount; i++) { Agents.Add(new Agent(Agent.RoleTypes.Scout)); } for (int i = 0; i < bestAgentsCount * bestPatchesCount; i++) { Agents.Add(new Agent(Agent.RoleTypes.Employed)); } for (int i = 0; i < eliteAgentsCount * elitePatchesCount; i++) { Agents.Add(new Agent(Agent.RoleTypes.Onlooker)); } AverageFitness = Agents.Where(a => a.Role != Agent.RoleTypes.Scout).Sum(a => a.Fitness) / (Size - BestAgentsCount); }
private Task RunTask(System.Collections.Queue syncQueue, FitnessFunction fitnessFunctionDelegate, int taskId) { //create a simple task that calls the locally defined Evaluate function var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; //.Net 4.5 option //var task = Task.Run (() => EvaluateTask (syncQueue, fitnessFunctionDelegate, taskId, token), token); //.Net 4.0/4.5 option var task = new Task(() => EvaluateTask(syncQueue, fitnessFunctionDelegate, taskId, token), token); task.Start(); task.ContinueWith(t => { var exception = t.Exception; if (OnEvaluationException != null && t.Exception != null) { var message = new StringBuilder(); foreach (var ex in t.Exception.InnerExceptions) { message.Append(ex.Message); message.Append("\r\n"); } var eventArgs = new ExceptionEventArgs("RunTask", message.ToString()); OnEvaluationException(this, eventArgs); } }, TaskContinuationOptions.OnlyOnFaulted); return(task); }
public static float EvaluateFitness(this FitnessFunction fitnessFunction, GenerationInstance instance) { var f = instance.dieOnCollision && instance.Collided ? .5f : 1f; float val; switch (fitnessFunction) { case FitnessFunction.Linear: val = instance.transform.position.y; break; case FitnessFunction.Gate: val = instance.transform.position.y * (Array.IndexOf(MainHandler.Gates, instance.currentGate) + 1); break; case FitnessFunction.VerticalWithGates: var goodDistance = instance.transform.position.y; var wasteDistance = instance.totalDistance - goodDistance; // we want to credit those, who move upwards // but we dont want them to just stand val = Mathf.Max(0, goodDistance * (Array.IndexOf(MainHandler.Gates, instance.currentGate) + 1) - wasteDistance); break; default: return(0f); } return(val * f); }
private String ga(Set <String> population, FitnessFunction fitnessFn) { // new_population <- empty set HashSet <String> newPopulation = new HashSet <String>(); // for i = 1 to SIZE(population) do for (int i = 0; i < population.Count; i++) { // x <- RANDOM-SELECTION(population, FITNESS-FN) String x = randomSelection(population, fitnessFn); // y <- RANDOM-SELECTION(population, FITNESS-FN) String y = randomSelection(population, fitnessFn); // child <- REPRODUCE(x, y) String child = reproduce(x, y); // if (small random probability) then child <- MUTATE(child) if (random.nextDouble() <= this.mutationProbability) { child = mutate(child); } // add child to new_population newPopulation.Add(child); } // population <- new_population population.clear(); population.AddRange(newPopulation); return(retrieveBestIndividual(population, fitnessFn)); }
private static PsoParameters SetupOptimizer(PsoParameters initialSettings, out FitnessFunction function) { var particlesNum = initialSettings.ParticlesCount; var settings = initialSettings; settings.TargetValueCondition = false; settings.IterationsLimitCondition = true; function = new FitnessFunction(Problem.evaluateFunction); FunctionFactory.SaveToCache(Problem.Id, function); var upper = Problem.getLargestValuesOfInterest(); var bounds = Problem.getSmallestValuesOfInterest() .Select((x, i) => new DimensionBound(x, upper[i])) .ToArray(); function.FitnessDim = Problem.getNumberOfObjectives(); function.LocationDim = Problem.getDimension(); settings.FunctionParameters = new FunctionParameters { Dimension = function.LocationDim, SearchSpace = bounds, FitnessFunctionType = Problem.Id }; settings.FunctionParameters.SearchSpace = bounds; return(settings); }
/// <summary> /// A function that calculates the FITNESS for each krill in the population /// </summary> public void EvaluatePopulation(FitnessFunction fitnessFunctionDelegate) { foreach (var krill in Population) { krill.Evaluate(fitnessFunctionDelegate); } }
// Use this for initialization void Start() { robots = findtag("robot"); numrobot = robots.Length; Area[] aree = ConvexOverlapping.divideSpaceIntoArea(); positions = new Vector3[aree.Length]; numaree = aree.Length; for (int i = 0; i < aree.Length; i++) { positions[i] = aree[i].center3D; } ff = new FitnessFunction(numrobot, robots, positions); ga = new GeneticAlgorithm(numrobot + aree.Length, 10, maxIteration, ff); /* * int[] solution = ga.run (); * * string log = "GA: ["; * for (int i=0; i<solution.Length; i++) { * log += solution[i] + ", "; * } * log = "]"; * Debug.Log (log); */ ga.first_generation(ga._population); }
public ECOptimizationTest( string id, IECTestsConfig testsConfig, IECChromosome ancestor, FitnessFunction fitnessFunction) : base(id, testsConfig) { this.population = new ECPopulation(testsConfig, ancestor, fitnessFunction); this.RandomProportionProgress = new StatisticalQuantity(testsConfig.MaxIterations); }
public static void Main(string[] args) { if (args.Length < 1) { Console.Error.WriteLine("You have to at least specify the data file path"); return; } var mutation = new UniformMutation(MutationProbability); var selection = new KTournamentSelection(TournamentSize); var crossover = new ArithmeticCrossover(); var fitnessFunction = new FitnessFunction(args[0]); IGeneticAlgorithm <DecimalArrayChromosome> geneticAlgorithm; if (args.Length == 2 && args[1].ToLower() == "gen") { geneticAlgorithm = new GenerationGeneticAlgorithm(mutation, selection, crossover, fitnessFunction, IterationLimit, FitnessTerminator, PopulationSize); } else { geneticAlgorithm = new EliminationGeneticAlgorithm(mutation, selection, crossover, fitnessFunction, IterationLimit, FitnessTerminator, PopulationSize); } var optimum = geneticAlgorithm.FindOptimum(); Console.WriteLine(); Console.WriteLine(optimum); }
public GameObject generateMonsterAtPosition(Vector3 pos, bool shouldWalk = true) { List <GameObject> goList = new List <GameObject> (); GameObject o = root.generateMonster(pos, 0, null, monsterMat, new Color(Random.Range(.5f, .8f), Random.Range(.5f, .8f), Random.Range(.5f, .8f)), goList); Creature cr = o.AddComponent <Creature> (); cr.nodeSetup(goList, monster.GetInstructions()); cr.setShouldWalk(true); FitnessFunction fn = o.AddComponent <FitnessFunction>(); fn.AssignMonster(monster); if (eye != null) { float eyeSmall = .3f; float eyeLarge = .5f; float eyeSize = Random.Range(eyeSmall, eyeLarge); float eyeDiff = Random.Range(eyeSize / 2, .5f - eyeSize / 2); GameObject e1 = GameObject.Instantiate(eye); e1.transform.SetParent(o.transform); e1.transform.localScale = new Vector3(eyeSize, eyeSize, eyeSize / 2); e1.transform.localPosition = new Vector3(-eyeDiff, 0, -.5f); GameObject e2 = GameObject.Instantiate(eye); e2.transform.SetParent(o.transform); e2.transform.localScale = new Vector3(eyeSize, eyeSize, eyeSize / 2); e2.transform.localPosition = new Vector3(eyeDiff, 0, -.5f); } return(o); }
public GeneticAlgorithm(int selectedFitnessFunction, int populationSize, int iterationsNumber, int selectedMethod) { this.selectedMethod = selectedMethod; ISelectionMethod selectionMethot = GetSelectionMethod(); DoubleArrayChromosome chromosome = new DoubleArrayChromosome(new AForge.Math.Random.StandardGenerator(), new AForge.Math.Random.StandardGenerator(), new AForge.Math.Random.StandardGenerator(), 2); FitnessFunction fitnessfunction = new FitnessFunction(selectedFitnessFunction); Population population = new Population(populationSize, chromosome, fitnessfunction, selectionMethot); double[,] tmp = new double[iterationsNumber, 2]; this.result = new double[iterationsNumber, 2]; int i; for (i = 0; i < iterationsNumber; i++) { population.RunEpoch(); DoubleArrayChromosome bestChromosome = (DoubleArrayChromosome)population.BestChromosome; double x = (double)bestChromosome.Value.GetValue(0); double y = (double)bestChromosome.Value.GetValue(1); tmp[i, 0] = x; tmp[i, 1] = y; if (fitnessfunction.Evaluate(bestChromosome) == 100) { break; } } this.result = new double[i, 2]; for (int j = 0; j < i; j++) { result[j, 0] = tmp[j, 0]; result[j, 1] = tmp[j, 1]; } }
/// <summary> /// Computes the gradient vector of a given function at some specified input values. /// </summary> /// <param name="func">Function to compute the fitness error.</param> /// <param name="inputValues">Input values to compute the fitness from.</param> /// <returns>List of all partial derivatives at the specified input values.</returns> private List <double> ComputeGradient(FitnessFunction func, List <double> inputValues) { var gradient = new List <double>(); // Obtain partial derivatives of all inputs and their added squares. double derivativeSquareSum = 0; for (var i = 0; i < inputValues.Count; i++) { var dV = this.ComputePartialDerivative( i, func, inputValues, this.Options.DerivativeStep); gradient.Add(dV * this.Options.LearningRate); derivativeSquareSum += dV * dV; } // Root of the sum of squares is the length var gradientLength = Math.Sqrt(derivativeSquareSum); // gradientLength = Math.Sqrt(gradientLength); // Divide the gradient values by the gradient lenght gradient.ForEach(value => value /= gradientLength); return(gradient); }
/// <summary> /// Fitness function calculating /// </summary> /// <param name="generation"></param> /// <param name="unsafeMode"></param> /// <returns></returns> private List <FitnessFunction> CalculateFitnessFunctionValues(List <List <double> > generation, bool unsafeMode) { // Creating real neural networks by weights lists: List <NeuralNetworkGeneticAlg> networksList = generation.Select(t => new NeuralNetworkGeneticAlg(t, NetworkStructure)).ToList(); // Calculating values: List <FitnessFunction> fitnessFuncValues = new List <FitnessFunction>(); Parallel.For(0, networksList.Count, i => { FitnessFunction fitnessFunction = new FitnessFunction { ChromosomeIndex = i }; fitnessFunction.CalculateValue(networksList[i], InputDatasets, OutputDatasets, unsafeMode); lock (_sync) { fitnessFuncValues.Add(fitnessFunction); } }); return(fitnessFuncValues); }
public void Evaluate() { Parallel.ForEach(GenePool, genotype => { genotype.Fitness = FitnessFunction.Evaluate(genotype); }); }
/// <summary> /// Run gradient descent algorithm. /// </summary> /// <param name="function">Delegate function to compute the fitness.</param> /// <param name="inputValues">Input values to compute the fitness from.</param> public void Minimize(FitnessFunction function, List <double> inputValues) { this.Result.Values = inputValues; // Run minimization at least once var iter = 0; double gLength; do { var gradient = this.ComputeGradient(function, this.Result.Values); // Compute gradient length gLength = 0; gradient.ForEach(g => gLength += g * g); gLength = Math.Sqrt(gLength); // Update values for (var i = 0; i < this.Result.Values.Count; i++) { this.Result.Values[i] -= gradient[i]; } this.Result.Error = function(this.Result.Values); this.Result.GradientLength = gLength; iter++; // Increase iteration count } while (gLength > this.Options.Limit && iter < this.Options.MaxIterations && this.Result.Error > this.Options.ErrorThreshold); Console.ResetColor(); }
/// <summary> /// This is the method that invokes the operator. This should not normally be called explicitly. /// </summary> /// <param name="currentPopulation"></param> /// <param name="newPopulation"></param> /// <param name="fitnessFunctionDelegate"></param> public void Invoke(Population currentPopulation, ref Population newPopulation, FitnessFunction fitnessFunctionDelegate) { //if the new population is null, create an empty population if (newPopulation == null) { newPopulation = currentPopulation.CreateEmptyCopy(); } if (!Enabled) { return; } if (currentPopulation.Solutions == null || currentPopulation.Solutions.Count == 0) { throw new ArgumentException("There are no Solutions in the current Population."); } if (currentPopulation.Solutions[0].Genes.Any(g => g.GeneType != GeneType.Binary)) { throw new Exception("Only Genes with a GeneType of Binary can be handled by the RandomReplace operator."); } _fitnessFunctionDelegate = fitnessFunctionDelegate; Replace(currentPopulation, ref newPopulation, this.Percentage, this.AllowDuplicates, _fitnessFunctionDelegate); }
public KrillHerdAlgorithm(KrillPopulation krillPopulation, FitnessFunction fitnessFunctionDelegate, Vector <double> LB_vector, Vector <double> UB_vector) { this.LB_vector = LB_vector; this.UB_vector = UB_vector; KrillPopulation = krillPopulation; FitnessFunction = fitnessFunctionDelegate; }
void testFitness() { robots = findtag("robot"); numrobot = robots.Length; Area[] aree = ConvexOverlapping.divideSpaceIntoArea(); positions = new Vector3[aree.Length]; for (int i = 0; i < aree.Length; i++) { positions[i] = aree[i].center3D; } //Debug.Log (positions.Length); FitnessFunction ff = new FitnessFunction(numrobot, robots, positions); GeneticAlgorithm ga = new GeneticAlgorithm(numrobot + aree.Length, 10, 1000, ff); int[] individual = new int[] { 0, 1, 2, 3, 4, 5, 6 }; Debug.Log("Fitness: " + ga.calculateFitness(individual)); individual = new int[] { 0, 1, 2, 3, 6, 4, 5 }; Debug.Log("Fitness: " + ga.calculateFitness(individual)); individual = new int[] { 0, 2, 3, 6, 1, 4, 5 }; Debug.Log("Fitness: " + ga.calculateFitness(individual)); makeItMove(individual); }
public void Evaluate(FitnessFunction fitnessFunctionDelegate) { foreach (var item in Solutions) { item.Evaluate(fitnessFunctionDelegate); } }
/// <summary> /// This is the method that invokes the operator. This should not normally be called explicitly. /// </summary> /// <param name="currentPopulation"></param> /// <param name="newPopulation"></param> /// <param name="fitnessFunctionDelegate"></param> public void Invoke(Population currentPopulation, ref Population newPopulation, FitnessFunction fitnessFunctionDelegate) { //if the new population is null, create an empty population if (newPopulation == null) { newPopulation = currentPopulation.CreateEmptyCopy(); } if (!Enabled) { return; } _fitnessFunctionDelegate = fitnessFunctionDelegate; _currentPopulation = currentPopulation; _newPopulation = newPopulation; //need to store this as we cannot handle a change until once this generation has started _replacementMethodS = ReplacementMethod; this.Process(); //TODO: Test this, we shouldn't need it. newPopulation = _newPopulation; }
/// <summary> /// This is the method that invokes the operator. This should not normally be called explicitly. /// </summary> /// <param name="currentPopulation"></param> /// <param name="newPopulation"></param> /// <param name="fitnessFunctionDelegate"></param> public new virtual void Invoke(Population currentPopulation, ref Population newPopulation, FitnessFunction fitnessFunctionDelegate) { if (currentPopulation.Solutions == null || currentPopulation.Solutions.Count == 0) { throw new ArgumentException("There are no Solutions in the current Population."); } if (newPopulation == null) { newPopulation = currentPopulation.CreateEmptyCopy(); } CurrentPopulation = currentPopulation; NewPopulation = newPopulation; FitnessFunction = fitnessFunctionDelegate; if (!Enabled) { return; } //need to store this as we cannot handle a change until once this generation has started _replacementMethodS = ReplacementMethod; this.Process(); //TODO: Test this, we shouldn't need it. newPopulation = NewPopulation; }
internal Population(Configuration config, GeneticTask task) { Size = config.PopSize; _config = config; _task = task; _fitnessFunc = task.Fitness; _genomes = new Genome[Size]; _next = new Genome[Size]; }
public VirtualFood(KrillPopulation krillPopulation, FitnessFunction fitnessFunction, Vector <double> UB_Vector, Vector <double> LB_Vector) { this.UB_Vector = UB_Vector; this.LB_Vector = LB_Vector; KrillPopulation = krillPopulation; FitnessFunction = fitnessFunction; PositionOfFood = Vector <double> .Build.Dense(krillPopulation.Population[0].Coordinates.Count); }
private EvolutionThread() { GenerationCounter = 0; Timestamp = System.DateTime.Now; Fitness = FitnessFunctionFactory.CreateDefaultFunction(); Crossover = CrossoverFactory.CreateDefaultCrossover(); Mutation = MutationFactory.CreateDefaultMutation(); }
/// <summary> /// Constuctor, requires a configured Population object. /// </summary>/// <param name="population">Population.</param> /// <param name="fitnessFunctionDelegate">Fitness function delegate.</param> public GeneticAlgorithm(Population population, FitnessFunction fitnessFunctionDelegate) { _population = population; FitnessFunction = fitnessFunctionDelegate; this.Operators = new List <IGeneticOperator> (); }
/// <summary> /// Реализация интерфейса IComparable, для сортировки векторов. /// </summary> public int CompareTo(Vectors other) { if (Function == null) { throw new ArgumentException("Не зада исследуемая функция."); } return(FitnessFunction.CompareTo(other.FitnessFunction)); }
public GeneticTrainer(IList <T> population, FitnessFunction <T> fitnessFunction, ISelection selection) { this._eveolveFunctions = new List <IEvolveFunction>(); this._population = new Population <T>(population); this._fitnessFunction = fitnessFunction; this._selection = selection; this.FittestChromosome = population[0]; this.CurrentGeneration = 0; }
public InducedMotion(KrillPopulation KrillPopulation, FitnessFunction fitnessFunction, int maxIteration, double N_max) : base(KrillPopulation, fitnessFunction) { this.KrillPopulation = KrillPopulation; Neighbourhood = new Neighbourhood(this.KrillPopulation); InducedSpeedHistory = new Dictionary <Tuple <int, int>, Vector <double> >(); MaxIteration = maxIteration; this.N_max = N_max; }
private void InitializePopulation() { for (var i = 0; i < PopulationSize; i++) { var chromosome = new Chromosome(ChromosomeSize); chromosome.Fitness = FitnessFunction.CalculateFitness(chromosome); Population.Add(chromosome); } }
/// <summary> /// This is the method that invokes the operator. This should not normally be called explicitly. /// </summary> /// <param name="currentPopulation"></param> /// <param name="newPopulation"></param> /// <param name="fitnessFunctionDelegate"></param> public override void Invoke(Population currentPopulation, ref Population newPopulation, FitnessFunction fitnessFunctionDelegate) { if (currentPopulation.Solutions == null || currentPopulation.Solutions.Count == 0) { throw new ArgumentException("There are no Solutions in the current Population."); } if (newPopulation == null) { newPopulation = currentPopulation.CreateEmptyCopy(); } CurrentPopulation = currentPopulation; NewPopulation = newPopulation; FitnessFunction = fitnessFunctionDelegate; if (!Enabled) { return; } //get the pool of solutions to choose from //this is safe as the current population also has the elite property set by the Elite operator //var populationSize = currentPopulation.Solutions.Count(s => !s.IsElite); var populationSize = currentPopulation.Solutions.Count(); var chromosomes = currentPopulation.Solutions; var numberToCopy = (int)System.Math.Round((chromosomes.Count() / 100.0) * this.Percentage); //get local copy to saves locking this member unnecessarily if (numberToCopy > populationSize) { numberToCopy = populationSize; } switch (_copyMethod) { case CopyMethod.Fittest: { CopyFittest(currentPopulation, ref newPopulation, numberToCopy); break; } case CopyMethod.Random: { CopyRandom(currentPopulation, ref newPopulation, numberToCopy); break; } default: { CopyFittest(currentPopulation, ref newPopulation, numberToCopy); break; } } }
public CopyTaskEnvironment(CopyTaskProperties props) { _vectorSize = props.VectorSize; MaxSequenceLength = props.MaxSequenceLength; LengthRule = props.LengthRule; _fitnessFunction = props.FitnessFunction; RandomSeed = props.RandomSeed; EliminiateZeroVectors = props.EliminateZeroVectors; }
public CopyTaskProperties(XmlElement xmlConfig) { Iterations = XmlUtils.TryGetValueAsInt(xmlConfig, "Iterations") ?? DEFAULT_ITERATIONS; RandomSeed = XmlUtils.TryGetValueAsInt(xmlConfig, "RandomSeed") ?? 0; VectorSize = XmlUtils.GetValueAsInt(xmlConfig, "VectorSize"); MaxSequenceLength = XmlUtils.TryGetValueAsInt(xmlConfig, "MaxLength") ?? DEFAULT_SEQUENCE_MAXLENGTH; LengthRule = (LengthRule)Enum.Parse(typeof(LengthRule), XmlUtils.GetValueAsString(xmlConfig, "LengthRule")); FitnessFunction = (FitnessFunction)Enum.Parse(typeof(FitnessFunction), XmlUtils.GetValueAsString(xmlConfig, "FitnessFunction")); EliminateZeroVectors = XmlUtils.TryGetValueAsBool(xmlConfig, "EliminateZeroVectors") ?? false; }
// creates a basic genetics object with an initial population of genestrings and mutations of those strings. public BasicGenetics(GeneString[] initial, BasicGeneticInstanceParameters parameters) { fitnessFunction = parameters.fitnessFunction; if (initial != null) parameters.generatorParameters.initial = initial; GeneString[] initialPopulation = parameters.generator.generatePopulation(parameters.generatorParameters); population = evaluateAll(initialPopulation); population.Sort(); }
// function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public String geneticAlgorithm(Set<String> population, FitnessFunction fitnessFn, GoalTest goalTest) { String bestIndividual = null; validatePopulation(population); clearInstrumentation(); setPopulationSize(population.Count); // repeat int cnt = 0; do { bestIndividual = ga(population, fitnessFn); cnt++; // until some individual is fit enough, or enough time has elapsed } while (!goalTest.isGoalState(bestIndividual)); setIterations(cnt); // return the best individual in population, according to FITNESS-FN return bestIndividual; }
public static IFitnessFunction<double[], double[]> GetFitnessFunction(FunctionParameters parameters) { if (functionCache.ContainsKey(parameters.FitnessFunctionType)) { return functionCache[parameters.FitnessFunctionType]; } if (parameters.FitnessFunctionType.Contains("bbob")) { var functionId = parameters.FitnessFunctionType; Problem problem; /* Iterate over all problems in the suite */ restartBbob(parameters.Dimension); while ((problem = benchmark.getNextProblem()) != null) { if (problem.Id != functionId) continue; var upper = problem.getLargestValuesOfInterest(); var bounds = problem.getSmallestValuesOfInterest() .Select((x, i) => new DimensionBound(x, upper[i])) .ToArray(); parameters.SearchSpace = bounds; var function = new FitnessFunction(problem.evaluateFunction); return function; } } switch (parameters.FitnessFunctionType) { case "quadratic": return new QuadraticFunction(parameters); case "rastrigin": return new RastriginFunction(parameters); case "rosenbrock": return new RosenbrockFunction(parameters); default: throw new ArgumentException("Unknown function type."); } }
public void Invoke(Population currentPopulation, ref Population newPopulation, FitnessFunction fitnesFunctionDelegate) { //take top 3 var num = 3; var min = System.Math.Min (num, currentPopulation.Solutions.Count); var best = currentPopulation.GetTop (min); var cutoff = best [min-1].Fitness; var genecount = best [0].Genes.Count; try { var config_vars = (ConfigVars)best[rand.Next(0,min-1)].Genes [rand.Next(0,genecount-1)].ObjectValue; var index = rand.Next(0, config_vars.vars.Count-1); var key = config_vars.vars. ElementAt(index).Key; newPopulation.Solutions.Clear(); foreach (var chromosome in currentPopulation.Solutions) { if (chromosome.Fitness < cutoff) { foreach (var gene in chromosome.Genes) { var target_config_vars = (ConfigVars)gene.ObjectValue; target_config_vars.vars [key] = config_vars.vars [key]; } } newPopulation.Solutions.Add (chromosome); } _invoked++; } catch(Exception e) { Console.WriteLine ("OOPS! " + e.Message + " " + e.StackTrace); } }
private String ga(Set<String> population, FitnessFunction fitnessFn) { // new_population <- empty set HashSet<String> newPopulation = new HashSet<String>(); // for i = 1 to SIZE(population) do for (int i = 0; i < population.Count; i++) { // x <- RANDOM-SELECTION(population, FITNESS-FN) String x = randomSelection(population, fitnessFn); // y <- RANDOM-SELECTION(population, FITNESS-FN) String y = randomSelection(population, fitnessFn); // child <- REPRODUCE(x, y) String child = reproduce(x, y); // if (small random probability) then child <- MUTATE(child) if (random.nextDouble() <= this.mutationProbability) { child = mutate(child); } // add child to new_population newPopulation.Add(child); } // population <- new_population population.clear(); population.AddRange(newPopulation); return retrieveBestIndividual(population, fitnessFn); }
private static PsoParameters SetupOptimizer(PsoParameters initialSettings, out FitnessFunction function) { var particlesNum = initialSettings.ParticlesCount; var settings = initialSettings; settings.TargetValueCondition = false; settings.IterationsLimitCondition = true; function = new FitnessFunction(Problem.evaluateFunction); FunctionFactory.SaveToCache(Problem.Id, function); var upper = Problem.getLargestValuesOfInterest(); var bounds = Problem.getSmallestValuesOfInterest() .Select((x, i) => new DimensionBound(x, upper[i])) .ToArray(); function.FitnessDim = Problem.getNumberOfObjectives(); function.LocationDim = Problem.getDimension(); settings.FunctionParameters = new FunctionParameters { Dimension = function.LocationDim, SearchSpace = bounds, FitnessFunctionType = Problem.Id }; settings.FunctionParameters.SearchSpace = bounds; return settings; }
public BasicGeneticInstanceParameters(Generator generator, GeneratorParameters generatorParameters, FitnessFunction fitnessFunction) { this.generator = generator; this.generatorParameters = generatorParameters; this.fitnessFunction = fitnessFunction; }
private String randomSelection(Set<String> population, FitnessFunction fitnessFn) { String selected = null; // Determine all of the fitness values double[] fValues = new double[population.Count]; String[] popArray = population.toArray(new String[population.Count]); for (int i = 0; i < popArray.length; i++) { fValues[i] = fitnessFn.getValue(popArray[i]); } // Normalize the fitness values fValues = Util.normalize(fValues); double prob = random.nextDouble(); double totalSoFar = 0.0; for (int i = 0; i < fValues.length; i++) { // Are at last element so assign by default // in case there are rounding issues with the normalized values totalSoFar += fValues[i]; if (prob <= totalSoFar) { selected = popArray[i]; break; } } // selected may not have been assigned // if there was a rounding error in the // addition of the normalized values (i.e. did not total to 1.0) if (null == selected) { // Assign the last value selected = popArray[popArray.length - 1]; } return selected; }
// function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public String geneticAlgorithm(Set<String> population, FitnessFunction fitnessFn, int iterations) { String bestIndividual = null; validatePopulation(population); clearInstrumentation(); setPopulationSize(population.Count); // repeat // until some individual is fit enough, or enough time has elapsed for (int i = 0; i < iterations; i++) { bestIndividual = ga(population, fitnessFn); } setIterations(iterations); // return the best individual in population, according to FITNESS-FN return bestIndividual; }
private String retrieveBestIndividual(Set<String> population, FitnessFunction fitnessFn) { String bestIndividual = null; double bestSoFarFValue = Double.NEGATIVE_INFINITY; foreach (String individual in population) { double fValue = fitnessFn.getValue(individual); if (fValue > bestSoFarFValue) { bestIndividual = individual; bestSoFarFValue = fValue; } } return bestIndividual; }
public GeneticBackend() { _objCalcData = new CalcDataObject(); _FitnessFunction = new FitnessFunction(_objCalcData); }
private CopyTaskEnvironment CreateEnvironment(FitnessFunction fitnessFunction) { CopyTaskProperties props = new CopyTaskProperties { Iterations = 10, VectorSize = 2, FitnessFunction = fitnessFunction, MaxSequenceLength = 10, LengthRule = LengthRule.Fixed, }; return new CopyTaskEnvironment(props); }