Esempio n. 1
0
 public Fitness Clone()
 {
     var retVal = new Fitness(f.Length);
     f.CopyTo(retVal.f,0);
     retVal.size = size;
     return retVal;
 }
        public string Fitness(string name, int procedureTime)
        {
            IAnimal animal  = GetAnimal(name, procedureTime);
            Fitness fitness = new Fitness();

            fitness.DoService(animal, procedureTime);

            AddToHistory(fitness.GetType().Name, animal);

            string result = $"{animal.Name} had fitness procedure";

            return(result);
        }
        /// <summary>
        /// Runs the evaluate fitness.
        /// </summary>
        /// <param name="chromosome">The chromosome.</param>
        private void RunEvaluateFitness(object chromosome)
        {
            var c = chromosome as IChromosome;

            try
            {
                c.Fitness = Fitness.Evaluate(c);
            }
            catch (Exception ex)
            {
                throw new FitnessException(Fitness, "Error executing Fitness.Evaluate for chromosome: {0}".With(ex.Message), ex);
            }
        }
 public GeneticKeyboard(OptimizationParameters optimizationParameters, Random random)
 {
     int[][] population = InitializeKeyboardPopulation(optimizationParameters.PopulationSize);
     _genetic = new BaseGenetic(optimizationParameters, population, pop =>
     {
         double[] fitness = new double[pop.Length];
         for (int i = 0; i < pop.Length; i++)
         {
             fitness[i] = Fitness.CalculateFitness(pop[i], _frequency, _weights);
         }
         return(fitness);
     }, CancellationToken.None, random);
 }
Esempio n. 5
0
        public static void RunTestAdder()
        {
            TestAdder               network = new TestAdder();
            Fitness <TestAdder>     fit     = x => x.RunTests();
            EvolSpecies <TestAdder> evol    = new EvolSpecies <TestAdder>(500, 1.0, fit);

            evol.Initialise(network);

            TestAdder best = new TestAdder();

            for (int i = 0; i < MAX_GEN; i++)
            {
                evol.Evolve();
                evol.GetTopSpec(best);

                double fitness = evol.TopFitness;
                int    species = evol.NumSpecies;

                int    nodes = best.NumNurons;
                int    axons = best.NumAxons;
                double fx    = evol.TopFitness;

                Console.WriteLine();
                Console.WriteLine("Generation " + i + ": " + nodes + " " + axons + " " + fx);
                Console.WriteLine("Num Species: " + evol.NumSpecies);
                Console.WriteLine("Threshold: " + evol.Threshold.ToString("0.00"));


                if (fitness > 0.999)
                {
                    Console.WriteLine();
                    Console.WriteLine("#############################################################");
                    Console.WriteLine("TARGET FITNESS REACHED!!!");
                    Console.WriteLine("#############################################################");
                    Console.WriteLine();

                    best.ReduceNetwork();
                    nodes = best.NumNurons;
                    axons = best.NumAxons;
                    fx    = fit(best);

                    Console.WriteLine("Final Network: " + nodes + " " + axons + " " + fx);

                    Console.WriteLine("Press any key...");
                    Console.ReadKey(true);
                    break;
                }

                //Thread.Sleep(500);
            }
        }
Esempio n. 6
0
        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());
        }
Esempio n. 7
0
        private void Evaluation()
        {
            outputs = pop.Evaluate(coords);

            // SaveImage(outputs[pop.Genomes[0].ID], subdivisions, count++);

            fits = Fitness.Function(pop, outputs, coords, targetValues, subdivisions, metrics);

            if ((metrics & Metrics.Displacement) == Metrics.Displacement)
            {
                femModels = pop.Genomes.Select(g => FEM.MakeFrame(g.FEMModel, FEM.GetDisplacements(g.FEMModel)).Item1).ToList();
                femModels = GenerateFEMs(femModels, pop.Genomes.Count);
            }
        }
Esempio n. 8
0
        public void FixedFitPopTest_RandomPop_ShouldPass()
        {
            var rd        = DefaultResearchParameters.GetDefaultResearchDefinitions();
            var listOfPop = Chromosome.NewRandomPopulation(rd, 10);
            var list      = Fitness.FixedFitPop(listOfPop, out var lowestKey);

            _testOutputHelper.WriteLine($"Lowest key {lowestKey}");
            Assert.True(lowestKey > 0);
            foreach (var chromosome in list)
            {
                Assert.True(chromosome.Fitness >= 0);
                _testOutputHelper.WriteLine($"{chromosome.Fitness}");
            }
        }
Esempio n. 9
0
        public string Fitness(string name, int procedureTime)
        {
            CheckForAnimal(name);
            Fitness fitness = new Fitness();
            Animal  animal  = hotel.Animals.Values.FirstOrDefault(x => x.Name == name);

            fitness.DoService(animal, procedureTime);
            if (!history.ContainsKey("Fitness"))
            {
                history.Add("Fitness", new List <Animal>());
            }
            history["Fitness"].Add(animal);
            return($"{name} had fitness procedure");
        }
Esempio n. 10
0
        public string Fitness(string name, int procedureTime)
        {
            if (IsExistInHotel(name))
            {
                throw new ArgumentException($"Animal {name} does not exist");
            }
            Procedure procedure = new Fitness();

            procedure.DoService(animalsInHotel[name], procedureTime);
            procedures.Add(procedure);
            string result = $"{name} had fitness procedure";

            return(result);
        }
Esempio n. 11
0
        // GET: Fitnesses/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Fitness fitness = db.Fitnesses.Find(id);

            if (fitness == null)
            {
                return(HttpNotFound());
            }
            return(View(fitness));
        }
Esempio n. 12
0
        public MainWindow()
        {
            InitializeComponent();
            DataContext  = this;
            SelectedType = SelectionMethods.First();
            QueueTask    = () =>
            {
                while (Queue.Count != complited)
                {
                    Fitness    fitnessFunc = new Fitness(map.Count, false);
                    Population population  = new Population(Queue[complited].PopulationCount,
                                                            new Chromosome(Cities, r, (ushort)r.Next(CitiesCount), true, (ushort)ConnectionsCount, Queue[complited].CrossoverMix, Queue[complited].KillBothParents),
                                                            fitnessFunc,
                                                            Queue[complited].SelectionMethod)
                    {
                        CrossoverRate          = Queue[complited].CrossOver,
                        MutationRate           = Queue[complited].Mutation,
                        RandomSelectionPortion = Queue[complited].RandomSelectionPortion,
                        AutoShuffling          = Queue[complited].AutoShufling
                    };

                    int  i          = 0;
                    bool needToStop = false;
                    while (!needToStop)
                    {
                        population.RunEpoch();
                        Queue[complited].Results.Add(new Result(i,
                                                                (population.BestChromosome as Chromosome).Path,
                                                                population.BestChromosome.Fitness,
                                                                population.FitnessAvg,
                                                                fitnessFunc.GetLength(population.BestChromosome),
                                                                (population.BestChromosome as Chromosome).Path.Count()
                                                                ));
                        System.Diagnostics.Debug.WriteLine("Best path: " + String.Join(",", (population.BestChromosome as Chromosome).Path) + $"\nBest fit: {population.BestChromosome.Fitness}");
                        System.Diagnostics.Debug.WriteLine("Avarge fit: " + population.FitnessAvg);
                        System.Diagnostics.Debug.WriteLine("Best length: " + fitnessFunc.GetLength(population.BestChromosome));
                        System.Diagnostics.Debug.WriteLine("Edges visited: " + (population.BestChromosome as Chromosome).Path.Count() + $"\nGeneartion: {i}");

                        if (i > Queue[complited].GenerationCount)
                        {
                            break;
                        }
                        i++;
                    }
                    Queue[complited].Name += ": " + (int)fitnessFunc.GetLength(population.BestChromosome);
                    complited++;
                }
            };
        }
Esempio n. 13
0
        public IActionResult Detail(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Fitness fitness = _db.Fitnesses.Include(c => c.FitnessDetail)
                              .FirstOrDefault(c => c.IsDeleted == false && c.Id == id);

            if (fitness == null)
            {
                return(NotFound());
            }
            return(View(fitness));
        }
Esempio n. 14
0
        public IList <NumericChromosome> Select(IList <NumericChromosome> chromosomes)
        {
            double                    randomNumber            = -1.0d;
            int                       randomIndex             = -1;
            double                    fitnessesSum            = 0.0d;
            List <double>             fitnesses               = new List <double>(chromosomes.Count);
            IList <double>            probabilities           = new List <double>(chromosomes.Count);
            IList <double>            cumulativeProbabilities = new List <double>(chromosomes.Count);
            IList <NumericChromosome> newChromosomes          = new List <NumericChromosome>(chromosomes.Count);

            // Calculate probabilities
            for (int i = 0; i < chromosomes.Count; i++)
            {
                fitnesses.Add(Fitness.Fitness(Evaluator.Evaluate(chromosomes[i])));
            }

            fitnessesSum = fitnesses.Sum();

            for (int i = 0; i < fitnesses.Count; i++)
            {
                probabilities.Add(fitnesses[i] / fitnessesSum);
            }

            // Calculate cumulative probabilities
            for (int i = 0; i < chromosomes.Count - 1; i++)
            {
                cumulativeProbabilities.Add(probabilities.Take(i + 1).Sum());
            }

            // Last cumulative probability is always 1
            cumulativeProbabilities[cumulativeProbabilities.Count - 1] = 1.0d;

            // For each chromosome...
            for (int i = 0; i < chromosomes.Count; i++)
            {
                // Pick a random number [0, 1)
                randomNumber = Randomizer.Double();

                // Find a the last index our random number is smaller than
                randomIndex = cumulativeProbabilities.IndexOf(cumulativeProbabilities.First(
                                                                  x => randomNumber < x));

                newChromosomes.Add(chromosomes[randomIndex].DeepClone());
            }

            return(newChromosomes);
        }
Esempio n. 15
0
        public int Compare(Fitness f1, Fitness f2)
        {
            if (f1 == null && f2 == null)
            {
                return(0);
            }
            else if (f1 == null)
            {
                return(-1);
            }
            else if (f2 == null)
            {
                return(1);
            }

            return(Fitness.CompareByMode(Fitness.CompareMode, Value(f1), Value(f2)));
        }
Esempio n. 16
0
        public string Fitness(string name, int procedureTime)
        {
            AnimalDoesntExist(name);

            IAnimal animal = TakeAnimal(name);

            IProcedure fitness = new Fitness();

            fitness.DoService(animal, procedureTime);

            AddTypeProcedure(fitness);

            return(string.Format(
                       ConstantMessages.HadProcedure,
                       animal.Name,
                       "fitness"));
        }
Esempio n. 17
0
        public Fitness EvaluatePhloemTransportationFitness(Plant plant)
        {
            Fitness fitness    = new Fitness();
            Branch  rootBranch = plant.GeometryStorage.GetRootBranch();

            if (rootBranch == null)
            {
                return(fitness);
            }

            TransportEnergyToParent(rootBranch, ref fitness);

            //Clean up to save memory
            plant.GeometryStorage.Delete();

            return(fitness);
        }
Esempio n. 18
0
        private int CompareSolutions(Fitness f1, Fitness f2)
        {
            Stage s1 = f1.GetUserData <Stage>("StagePSOStage");
            Stage s2 = f2.GetUserData <Stage>("StagePSOStage");

            if (s1.Priority > s2.Priority)
            {
                return(1);
            }

            if (s2.Priority > s1.Priority)
            {
                return(-1);
            }

            return(s1.Compare(f1, f2));
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            DataModel   data_model   = new DataModel();
            InputReader input_reader = new InputReader();

            ReadWatch.Start();
            // input_reader.ReadDataFromFile("data/me_at_the_zoo.in");
            input_reader.ReadDataFromFile("data/videos_worth_spreading.in");
            // input_reader.ReadDataFromFile("data/trending_today.in");
            // input_reader.ReadDataFromFile("data/kittens.in");
            ReadWatch.Stop();
            Console.WriteLine($"{ReadWatch.ElapsedMilliseconds}");
            var selection = new EliteSelection();
            var crossover = new CutAndSpliceCrossover();
            var mutation  = new AddGenesMutation(10);

            var fitness    = new Fitness();
            var chromosome = new Chromosome(3000);
            var population = new Population(1000, 1000, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ga.MutationProbability = 0.25f;
            ga.Termination         = new GenerationNumberTermination(250);
            int i = 0;

            ga.GenerationRan += (_, __) => {
                var bestC = ga.BestChromosome as Chromosome;
                SaveToFile.Save(bestC, @"data\output");
                Console.WriteLine($@"G.num.: {i++}, Fitness: {ga.BestChromosome.Fitness}, Lenght: {ga.BestChromosome.Length}, generation time = {GenerationWatch.ElapsedMilliseconds}, Fitness time = {WholeFitnessWatch.ElapsedMilliseconds}, Fitness percentage: {((float)WholeFitnessWatch.ElapsedMilliseconds/(float)GenerationWatch.ElapsedMilliseconds)}");

                GenerationWatch.Restart();
                WholeFitnessWatch.Reset();
            };

            Console.WriteLine("GA running...");
            GenerationWatch.Start();
            ga.Start();
            Console.WriteLine($"GA done in {ga.GenerationsNumber} generations.");

            var bestChromosome = ga.BestChromosome as Chromosome;

            Console.WriteLine($"Best solution found has fitness: {bestChromosome.Fitness}.");

            Console.WriteLine("Done");
        }
Esempio n. 20
0
        public BookingHandler()
        {
            col                 = new Collector();
            _fitness            = new ObservableCollection <Event>();
            _yoga               = new ObservableCollection <Event>();
            _salsa              = new ObservableCollection <Event>();
            _karate             = new ObservableCollection <Event>();
            _zumba              = new ObservableCollection <Event>();
            _ballet             = new ObservableCollection <Event>();
            _poledance          = new ObservableCollection <Event>();
            _eventListSingleton = EventListSingleton.GetInstance();
            _eventListSingleton.SetEvents(col.Events);

            foreach (var Event in _eventListSingleton.GetDates())
            {
                if (Event.Type == "Fitness")
                {
                    Fitness.Add(Event);
                }
                if (Event.Type == "Yoga")
                {
                    Yoga.Add(Event);
                }
                if (Event.Type == "Salsa")
                {
                    Salsa.Add(Event);
                }
                if (Event.Type == "Pole dance")
                {
                    Poledance.Add(Event);
                }
                if (Event.Type == "Ballet")
                {
                    Ballet.Add(Event);
                }
                if (Event.Type == "Zumba")
                {
                    Zumba.Add(Event);
                }
                if (Event.Type == "Karate")
                {
                    Karate.Add(Event);
                }
            }
        }
Esempio n. 21
0
        public AnimalCentre()
        {
            this.hotel   = new Hotel();
            this.factory = new AnimalFactory();
            this.chip    = new Chip();
            this.care    = new DentalCare();
            this.fitness = new Fitness();
            this.trim    = new NailTrim();
            this.play    = new Play();
            this.vac     = new Vaccinate();

            this.procedures = new List <Procedure>()
            {
                chip, care, fitness, trim, play, vac
            };

            this.allAddoptedAnimals = new Dictionary <string, List <string> >();
        }
Esempio n. 22
0
    //sets up the initial GA
    public GeneticAlgo CreateGA(string[][] _sampleGenomes)
    {
        System.Random r = new System.Random(Time.frameCount);
        //specify the numbers of genes to the population.

        string selectType = "god mode";
        string mutateType = "randomChoice";
        string crossType  = "OnePt";

        Encoder    encoder    = _encode;
        Fitness    fitness    = new Fitness("");
        Population population = new Population(_childCount, encoder._symbols, samplePopulation: _sampleGenomes, variableGenomeLength: true);
        Selection  selection  = new Selection(selectType);
        CrossOver  crossover  = new CrossOver(crossType);
        Mutation   mutation   = new Mutation(mutateType, _mutationRate);

        return(new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation));
    }
Esempio n. 23
0
 public AnimalCentre(IHotel hotel,
                     IProcedure procedure,
                     Chip chip,
                     DentalCare dentalcare,
                     Fitness fitness,
                     NailTrim nailtrim,
                     Play play,
                     Vaccinate vaccinate)
 {
     this.hotel     = hotel;
     this.procedure = procedure;
     chip           = new Chip();
     dentalcare     = new DentalCare();
     fitness        = new Fitness();
     nailtrim       = new NailTrim();
     play           = new Play();
     vaccinate      = new Vaccinate();
 }
Esempio n. 24
0
 public void buildState(Unit unitInput)
 {
     unit = unitInput;
     try {
         fitness     = gameObject.GetComponent <Fitness>();
         transitions = gameObject.GetComponents <Transition>();
         foreach (var transition in transitions)
         {
             transition.buildTransition();
         }
         if (network.controllerLoadPath != "")
         {
             processed = true;
         }
     }
     catch (NullReferenceException) {
         Debug.Log("State buildState failure, " + name + " has no attached neural net.");
     }
 }
Esempio n. 25
0
        public static void TestGennetics3()
        {
            GenString target = new GenString(
                "Twas brillig, and the slithy toves did gyer and gimble in the wabe.");
            GenString best = new GenString("Hello");

            Console.WriteLine("Target: " + target);

            Fitness <GenString> fit = delegate(GenString gs)
            {
                double dist = gs.Distance(target);
                //return 1.0 / (dist + 1.0);
                //return -dist;

                dist = 100.0 - dist;
                if (dist < 0.1)
                {
                    dist = 0.1;
                }
                return(dist);
            };

            EvolSpecies <GenString> evol = new EvolSpecies <GenString>(1000, 0.1, fit);

            evol.Initialise(best);

            for (int i = 0; i < MAX_GEN; i++)
            {
                evol.Evolve();
                evol.GetTopSpec(best);

                double fitness = evol.TopFitness;
                int    species = evol.NumSpecies;

                Console.WriteLine();
                Console.WriteLine("Generation " + i + ": " + fitness);
                Console.WriteLine("Num Species: " + species);
                Console.WriteLine(best);

                //Thread.Sleep(500);
            }
        }
        public static PathFindingResult GetPathAndFitness(int[] order, OptimizationParameters optimizationParameters,
                                                          CancellationToken ct, Random random)
        {
            IPathFinder algorithmPathFinding = optimizationParameters.OptimizationMethod switch
            {
                OptimizationMethod.Permutations => new Permutations(optimizationParameters),
                OptimizationMethod.NearestNeighbor => new NearestNeighbor(optimizationParameters),
                OptimizationMethod.GeneticAlgorithm => new GeneticPathFinding(order, optimizationParameters,
                                                                              (population) =>
                {
                    double[] fitness = new double[population.Length];
                    for (int i = 0; i < population.Length; i++)
                    {
                        fitness[i] = Fitness.CalculateFitness(population[i]);
                    }
                    return(fitness);
                }, ct, random),
                _ => throw new ArgumentException("Incorrect optimization method in config file")
            };

            int[] objectOrder = algorithmPathFinding.FindShortestPath(order);

            if (optimizationParameters.Use2opt)
            {
                objectOrder = Optimizer2Opt.Optimize(objectOrder);
            }

            double pathLength = Fitness.CalculateFitness(objectOrder);

            if (optimizationParameters.ResultToFile)
            {
                Log log = new Log(optimizationParameters);
                log.SaveResult(objectOrder, pathLength);
            }

            return(new PathFindingResult()
            {
                Path = objectOrder,
                Fitness = pathLength
            });
        }
    }
Esempio n. 27
0
        private static void setFitness(string input)
        {
            switch (input)
            {
            case "AdjR2":
                fitness = new AdjustedR2();
                Write.Success("Set adjusted R2 as fitness criteria");
                break;

            case "AIC":
                fitness = new AIC();
                Write.Success("Set AIC as fitness criteria");
                break;

            default:
                Write.Error("Unexpected input");
                Write.Error("Possible paramameters: AIC, AdjR2");
                break;
            }
        }
Esempio n. 28
0
        private int NaturalSelection()
        {
            var accept = false;
            var rd     = 0;
            var rd2    = 0;

            while (!accept)
            {
                rd  = _rand.Next(PopulationSize);
                rd2 = _rand.Next((int)Fitness.Max());


                if (rd2 <= Fitness[rd])
                {
                    accept = true;
                }
            }

            return(rd);
        }
Esempio n. 29
0
        public string Fitness(string name, int procedureTime)
        {
            this.DoesExist(name);

            var animal = hotel.GetAnimal(name);

            if (this.procedures.Any(p => p.GetType().Name == "Fitness"))
            {
                this.procedures.First(p => p.GetType().Name == "Fitness")
                .DoService(animal, procedureTime);
            }
            else
            {
                Procedure procedure = new Fitness();
                procedure.DoService(animal, procedureTime);
                this.procedures.Add(procedure);
            }

            return($"{name} had fitness procedure");
        }
Esempio n. 30
0
        /*
         *  var functionUnderStudy = new Func<double, double>(x => 0.2 * Math.Pow(x, 3) + 0.1 * Math.Pow(x, 2) - 8 * x);
         *  var fitFunction = new Func<double, double>(x => -(0.2 * Math.Pow(x, 3) + 0.1 * Math.Pow(x, 2) - 8 * x));
         *
         *  var functionUnderStudy = new Func<double, double>(x => x - Math.Pow(x, 2) + Math.Pow(x, 3));
         *  var fitFunction = functionUnderStudy;
         *
         *  var functionUnderStudy = new Func<double, double>(Math.Sin);
         *  var fitFunction = functionUnderStudy;
         */
        public static void Main(string[] args)
        {
            var iterations         = 1000;
            var functionUnderStudy = new Func <double[], double>(x => 0.2 * Math.Pow(x[0], 3) + 0.1 * Math.Pow(x[0], 2) - 8 * x[0]);
            var fitFunction        = new Func <double[], double>(x => Math.Sin(x[0]));
            var cd = new ChromosomeDefinition(10);
            var fc = new Function(functionUnderStudy, fitFunction, -7, 7);
            var rd = new ResearchDefinitions(cd, fc, 100, 0.1, 0.5);
            var listOfMediumAbsFitness = new List <double>();

            var startPop = Fitness.FitPop(
                Chromosome.NewRandomPopulation(
                    rd,
                    rd.Population));

            listOfMediumAbsFitness.Add(startPop.Sum(x => x.Fitness) / startPop.Count);

            var preselectedPop = new RouletteWheel().DrawChromosomes(startPop);

            var nextGenPop     = Fitness.FitPop(PostSelection.CreateNewPopulation(preselectedPop, rd.CrossChance, rd.MutationChance));
            var bestChromosome = new BestChromosome()
            {
                bestChromosome = nextGenPop.Max(x => x),
                generation     = 1
            };

            listOfMediumAbsFitness.Add(nextGenPop.Sum(x => x.Fitness) / nextGenPop.Count);

            for (int i = 1; i < iterations; i++)
            {
                nextGenPop = Fitness.FitPop(PostSelection.CreateNewPopulation(nextGenPop, rd.CrossChance, rd.MutationChance));
                if (bestChromosome.bestChromosome.AbsFitness < nextGenPop.Max(x => x.AbsFitness))
                {
                    bestChromosome.bestChromosome = nextGenPop.FirstOrDefault(x => x.AbsFitness == nextGenPop.Max(y => y.AbsFitness));
                    bestChromosome.generation     = i + 1;
                }
                listOfMediumAbsFitness.Add(nextGenPop.Sum(x => x.Fitness) / nextGenPop.Count);
            }

            listOfMediumAbsFitness.ForEach(Console.WriteLine);
        }
Esempio n. 31
0
    public void CreateGA()
    {
        System.Random r = new System.Random(Time.frameCount);

        string selectType = "god mode";
        string mutateType = "randomChoice";
        string crossType  = "OnePt";

        Encoder    encoder    = new Encoder();
        string     target     = encoder.Encode(TextureNoise.CreateNoise(width, height, r));
        Fitness    fitness    = new Fitness(target);
        Population population = new Population(20, fitness._targetString)
        {
            _name = "images"
        };
        Selection selection = new Selection(selectType);
        CrossOver crossover = new CrossOver(crossType);
        Mutation  mutation  = new Mutation(mutateType);

        geneticAlgo = new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation);
    }
Esempio n. 32
0
 public override Fitness Evaluate(Position x)
 {
     var offset0 = new[]{
                             -3.9311900e+001, 5.8899900e+001, -4.6322400e+001, -7.4651500e+001, -1.6799700e+001,
                             -8.0544100e+001, -1.0593500e+001, 2.4969400e+001, 8.9838400e+001, 9.1119000e+000,
                             -1.0744300e+001, -2.7855800e+001, -1.2580600e+001, 7.5930000e+000, 7.4812700e+001,
                             6.8495900e+001, -5.3429300e+001, 7.8854400e+001, -6.8595700e+001, 6.3743200e+001,
                             3.1347000e+001, -3.7501600e+001, 3.3892900e+001, -8.8804500e+001, -7.8771900e+001,
                             -6.6494400e+001, 4.4197200e+001, 1.8383600e+001, 2.6521200e+001, 8.4472300e+001
                         };
     double f = -450;
     for (int d = 0; d < x.size; d++)
     {
         double xd = x.x[d];
         x.x[d] = xd - offset0[d];
         f = f + xd * xd;
     }
     var ff = new Fitness(Constants.fMax);
     ff.f[0] = Math.Abs(f - ObjectiveValue);
     //TODO: Refactor
     Program.nEval = Program.nEval + 1;
     return ff;
 }
        /// <summary>
        /// Author: Philipp Klein
        /// </summary>
        public void getParameter()
        {
            int count = 0;

            StopCriterion[] stop = new StopCriterion[3];
            AlgoSettings algoSettings = new AlgoSettings();

            algoSettings.strategy = (SelectionStrategy)sele.SelectedValue;
            algoSettings.populationSize = (uint)popu.Value;
            algoSettings.crossoverCount = Convert.ToUInt32(cross.Text);
            algoSettings.mutationRate = (float)muta.Value;

            if (Number_of_generations.IsChecked == true)
            {
                maxGeneration gen = new maxGeneration(Convert.ToUInt32(numGen.Text));
                stop[count] = gen;
                count++;
            }
            if (Runtime__s_.IsChecked == true)
            {
                Runtime run = new Runtime(Convert.ToUInt32(runTime.Text));
                stop[count] = run;
                count++;
            }
            if (Fitness__ms_.IsChecked == true)
            {
                Fitness fit = new Fitness(Convert.ToUInt32(fitness.Text));
                stop[count] = fit;
                count++;
            }
            StopCriterion[] s = new StopCriterion[count];

            for (int i = 0; i < count; i++)
                s[i] = stop[i];

            algoSettings.stop = s;
        }
        /// <summary>
        /// Gets the fitness of the specified route for a specified departure time.
        /// </summary>
        /// <param name="route">
        /// A route.
        /// </param>
        /// <param name="initialDepart">
        /// The departure time of the journey you are measuring the fitness of.
        /// </param>
        /// <returns>
        /// A <see cref="Fitness"/> object representing the fitness of the specified route and departure time.
        /// </returns>
        public Fitness GetFitness(Route route, DateTime initialDepart)
        {
            restart:

            // TODO: Remove this line
            // initialDepart = properties.DepartureTime;
            var fitness = new Fitness();
            var nodeDict = new Dictionary<int, int>();

            INetworkDataProvider provider = this.properties.NetworkDataProviders[0];

            var openRoutes = new List<int>();
            var closedRoutes = new List<int>();
            var closedRoutesIndex = new List<List<ClosedRoute>>();
            var routeIndex = new Dictionary<int, int>();

            for (int i = 0; i <= route.Count; i++)
            {
                var routes = new List<int>();

                if (i < route.Count)
                {
                    if (nodeDict.ContainsKey(route[i].Node.Id))
                    {
                        Logger.Log(this, "Loop detected! Removing and restarting...");
                        int index = nodeDict[route[i].Node.Id];
                        route.RemoveRange(index, i - index);
                        goto restart;
                    }

                    nodeDict.Add(route[i].Node.Id, i);

                    route[i].Node.RetrieveData();

                    // Console.Write("{0:00000}[{1}]: ", route[i].Id,((PtvNode)route[i]).StopSpecName);
                    closedRoutesIndex.Add(new List<ClosedRoute>());
                    routes = provider.GetRoutesForNode(route[i].Node);

                    foreach (int routeId in routes)
                    {
                        // Console.Write("{0:00000}, ", routeId);
                        if (!openRoutes.Contains(routeId))
                        {
                            // && !closedRoutes.Contains(routeId))
                            openRoutes.Add(routeId);
                            routeIndex[routeId] = i;
                        }
                    }

                    // Console.WriteLine();
                }

                var newOpenRoute = new List<int>();
                foreach (var openRoute in openRoutes)
                {
                    if (!routes.Contains(openRoute))
                    {
                        closedRoutes.Add(openRoute);
                        var cr = new ClosedRoute(openRoute, routeIndex[openRoute], i - 1);

                        if (cr.Length >= 1)
                        {
                            /*
                            if (route[cr.start].Node.Id == route[cr.end].Node.Id)
                            {
                                Logger.Log(this, "Loop detected! Removing and restarting...");
                                route.RemoveRange(cr.start, cr.end - cr.start);
                                goto restart;
                            }
                             * */
                            closedRoutesIndex[routeIndex[openRoute]].Add(cr);
                        }
                    }
                    else
                    {
                        newOpenRoute.Add(openRoute);
                    }
                }

                openRoutes = newOpenRoute;
            }

            /*
            StreamWriter writer = new StreamWriter("test.csv",false);
            for (int i = 0; i < closedRoutesIndex.Count; i++)
            {
                foreach (var closedRoute in closedRoutesIndex[i])
                {
                    writer.Write("{0:000000}: ", closedRoute.id);
                    for (int j = 0; j < closedRoute.start; j++)
                    {
                         writer.Write(" ");
                    }
                    for (int j = 0; j < closedRoute.end - closedRoute.start; j++)
                    {
                        writer.Write("*");
                    }
                    writer.WriteLine();

                }
             }

             *
             * */
            var pointer = 0;
            var totalTime = default(TransportTimeSpan);
            int legs = 0;
            int totalBus = 0;
            int totalTrain = 0;
            int totalTram = 0;
            int fakeLegs = 0;
            double totalDistance = 0;
            DateTime departTime = initialDepart;

            // Console.WriteLine("-------UnifiedFitnessScore Evaluation-------");
            while (pointer < route.Count - 1)
            {
                var t = closedRoutesIndex[pointer];
                TransportMode mode = TransportMode.Unknown;

                var bestArcs =
                    t.Select(
                        cr =>
                        provider.GetDistanceBetweenNodes(route[cr.Start].Node, route[cr.End].Node, departTime).FirstOrDefault()).ToList();

                bestArcs = (from arc in bestArcs where arc != default(Arc) select arc).ToList();

                if (!bestArcs.Any())
                {
                    mode = TransportMode.Walking;
                    var longest = (from cr in t where cr.Length == t.Max(i => i.Length) select cr).FirstOrDefault();
                    if (longest.Equals(default(ClosedRoute)))
                    {
                        // If there are no closed routes here, just walk to the next node.
                        bestArcs.Add(
                            this.properties.PointDataProviders[0].EstimateDistance(
                                (Location)route[pointer].Node, (Location)route[pointer + 1].Node));
                    }
                    else
                    {
                        // Calculate the walking disance
                        bestArcs.Add(
                            this.properties.PointDataProviders[0].EstimateDistance(
                                (Location)route[longest.Start].Node, (Location)route[longest.End].Node));
                    }
                }

                bestArcs =
                    (from a in bestArcs
                     where Math.Abs(a.Distance - bestArcs.Max(i => i.Distance)) < Epsilon
                     select a).ToList();

                var bestArc =
                    (from a in bestArcs where a.Time.TotalTime == bestArcs.Min(i => i.Time.TotalTime) select a).First();

                if (mode == TransportMode.Unknown)
                {
                    mode = route[pointer].Node.TransportType;
                }

                if (mode != TransportMode.Walking)
                {
                    switch (route[pointer].Node.TransportType)
                    {
                        case TransportMode.Train:
                            totalTrain++;
                            break;
                        case TransportMode.Bus:
                            totalBus++;
                            break;
                        case TransportMode.Tram:
                            totalTram++;
                            break;
                        default:
                            break;
                    }
                }

                fitness.JourneyLegs.Add(
                    new JourneyLeg(
                        mode,
                        (PtvNode)bestArc.Source,
                        (PtvNode)bestArc.Destination,
                        departTime,
                        bestArc.Time.TotalTime,
                        bestArc.RouteId.ToString()));

                if (mode != TransportMode.Walking)
                {
                    legs++;
                }

                fakeLegs++;
                totalTime += bestArc.Time;
                departTime += bestArc.Time.TotalTime;
                totalDistance += GeometryHelper.GetStraightLineDistance(bestArc.Source, bestArc.Destination);
                Assert.That(totalTime.TotalTime != TimeSpan.Zero, "Last arc was zero time.");
                Assert.That(departTime != default(DateTime), "DepartTime is zero.");

                Assert.IsFalse(
                    route[pointer].Node.Id == ((INetworkNode)bestArc.Destination).Id,
                    "Destination is source. There must be a loop.");

                // Advance pointer
                while (route[pointer].Node.Id != ((INetworkNode)bestArc.Destination).Id)
                {
                    pointer++;
                }

                Assert.IsTrue(pointer < route.Count, "Route pointer has overflowed.");
            }

            // route.Last().TotalTime = route[route.Count - 2].TotalTime;
            // writer.Close();
            // Console.WriteLine("Total Time: {0}", totalTime);
            // Console.WriteLine("------------------------------");
            fitness.TotalTravelTime = totalTime.TravelTime;
            fitness.TotalWaitingTime = totalTime.WaitingTime;
            fitness.TotalJourneyTime = totalTime.TotalTime;
            fitness.TotalDistance = totalDistance;
            fitness.Changes = legs;

            // fitness.PercentBuses = new[] { totalBus, totalTrain, totalTram }.Max() / (double) legs;
            if (legs != 0)
            {
                fitness.PercentBuses = (double)totalBus / legs;
                fitness.PercentTrains = (double)totalTrain / legs;
                fitness.PercentTrams = (double)totalTram / legs;
            }
            else
            {
                fitness.PercentBuses = 0;
                fitness.PercentTrains = 0;
                fitness.PercentTrams = 0;
            }

            double totalPercent = fitness.PercentBuses + fitness.PercentTrains + fitness.PercentTrams;

            Assert.That(totalPercent <= 1.01);

            // Console.WriteLine("Evaluated fitness: {0}" , fitness);
            return fitness;
        }
Esempio n. 35
0
 public UnitAttributes(int age = 18, int str = 1, int dex = 1, int con = 1, int wis = 1, int spi = 1, int luck = 1)
     : base(str, dex, con, wis, spi, luck)
 {
     this.age = age;
     this.sexIsMale = true;
     this.height = 184;
     this.weight = 77;
     //this.height = 185;      //later calc based on age/race/class etc.
     //this.weight = 72;       //- - - - same as above - - - - -
     this.fitness = Fitness.Striking;        //- - - - same as above - - - - -
     this.BMI = weight / (height * height);
     this.currentHealth = this.MaxHealth;
     this.lengthOfVision = 1;
     this.level = 0;
 }
Esempio n. 36
0
        public Swarm SW; // Final swarm

        #endregion Fields

        #region Constructors

        public Result()
        {
            SW=new Swarm(Constants.SMax);
            error=new Fitness(Constants.fMax);
        }
        /// <summary>
        /// Author: Philipp Klein
        /// </summary>
        /// <param name="algoSettings"></param>
        public void setParameter(AlgoSettings algoSettings)
        {
            sele.SelectedValue = algoSettings.strategy;
            popu.Value = algoSettings.populationSize;
            cross.Text = algoSettings.crossoverCount.ToString();
            muta.Value = algoSettings.mutationRate;

            maxGeneration m = new maxGeneration(1);
            Runtime r = new Runtime(1);
            Fitness f = new Fitness(1);

            for (int i = 0; i < algoSettings.stop.Length; i++)
            {
                if (algoSettings.stop[i].GetType().IsAssignableFrom(m.GetType()))
                {
                    Number_of_generations.IsChecked = true;
                    numGen.Text = ((maxGeneration)algoSettings.stop[i]).maxGen.ToString();
                }
                if (algoSettings.stop[i].GetType().IsAssignableFrom(r.GetType()))
                {
                    Runtime__s_.IsChecked = true;

                    runTime.Text = ((Runtime)algoSettings.stop[i]).runtime.ToString();

                }
                if (algoSettings.stop[i].GetType().IsAssignableFrom(f.GetType()))
                {
                    Fitness__ms_.IsChecked = true;
                    fitness.Text = ((Fitness)algoSettings.stop[i]).fitness.ToString();
                }
            }
        }
Esempio n. 38
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        public static void Main(string[] args)
        {
            int port = 8000;

            Console.WriteLine("RMIT Journey Planner Server");
            Console.WriteLine("Starting...");

            if (args.Length == 0)
            {
                var server = new Server();

                var parameters = new[] { Directory.GetCurrentDirectory() + "\\..\\" };
                parameters[0] = parameters[0].Replace("\\", "/");
                ConfigurationManager.AppSettings["MonoServerRootDir"] = parameters[0];
                ConfigurationManager.AppSettings["MonoServerPort"] = port.ToString();

                server.RealMain(
                    new[] { "--verbose", "--port", port.ToString() }, true, null, false);
            }
            else if (args[0] == "--collate")
            {
                // S:\Recovery\1 NTFS\Users\Sean\Dropbox\Study\RMITAssignments\Honours\JRPCServer\JSONStore\Journeys
                var journeys = Directory.GetDirectories(args[1]);
                foreach (var journey in journeys)
                {
                    var runs = Directory.GetDirectories(journey);

                    double[,] jvalues = new double[200, 15];
                    IEnumerable<object> names = null;

                    int runCount = 0;
                    bool success = true;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Processing journey: {0}", journey.Split(new[] { '\\' }).Last());

                    foreach (var run in runs)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("\tProcessing run: {0}", run.Split(new[] { '\\' }).Last());
                        runCount++;

                        double[,] values = new double[200, 15];
                        for (int i = 0; i < 200; i++)
                        {
                            if (!File.Exists(run + "\\iteration." + i + ".json"))
                            {
                                Console.WriteLine("\tWarning: Iteration doesnt exist. Skipping run.");
                                success = false;
                                runCount--;
                                break;
                            }
                            else
                            {
                                JsonObject iteration =
                                    JsonConvert.Import(File.ReadAllText(run + "\\iteration." + i + ".json")) as
                                    JsonObject;

                                values[i, 0] = i;
                                values[i, 1] = Convert.ToDouble(iteration["hypervolume"]);
                                values[i, 2] = Convert.ToDouble(iteration["cardinality"]);
                                var f = new Fitness[100];

                                var pop = (JsonArray)iteration["population"];
                                int ps = -1;

                                for (int j = 0; j < 100; j++)
                                {
                                    var p = (JsonObject)((JsonObject)((JsonObject)pop[j])["Critter"])["Fitness"];
                                    ps = p.Count;
                                    for (int k = 0; k < p.Count; k++)
                                    {
                                        var name = p.Names.OfType<object>().ElementAt(k).ToString();
                                        names = p.Names.OfType<object>();
                                        var value = p[name];
                                        checked
                                        {
                                            values[i, k + 3] += Convert.ToDouble(value);
                                        }
                                    }
                                }

                                for (int j = 0; j < ps; j++)
                                {
                                    values[i, j + 3] /= 100.0;
                                }
                            }
                        }

                        if (success)
                        {
                            for (int i = 0; i < jvalues.GetLength(0); i++)
                            {
                                for (int j = 0; j < jvalues.GetLength(1); j++)
                                {
                                    jvalues[i, j] += values[i, j];
                                }
                            }
                        }
                    }

                    Console.ForegroundColor = ConsoleColor.Green;

                    using (var writer = new StreamWriter(journey + "\\result2.csv"))
                    {
                        writer.Write("iteration,hypervolume,cardinality,");
                        foreach (var name in names)
                        {
                            writer.Write(name + ",");
                        }

                        writer.WriteLine();
                        if (runCount == 0)
                        {
                            Console.WriteLine("No intact runs for this journey!");
                            File.WriteAllText(journey + "\\fail.fail", "FAIL");
                            continue;
                        }

                        for (int i = 0; i < jvalues.GetLength(0); i++)
                        {
                            for (int j = 0; j < jvalues.GetLength(1); j++)
                            {
                                jvalues[i, j] /= runCount;
                                writer.Write(jvalues[i, j] + ", ");
                            }

                            writer.WriteLine();
                        }

                        Console.WriteLine("Wrote {0} runs!", runCount);
                    }
                }
            }
            else
            {
                Console.WriteLine("Invalid Param");
            }

            Console.ReadLine();
        }
Esempio n. 39
0
        public static Fitness perf(Position x, Problem pb)
        {
            // Evaluate the fitness value for the particle of rank s

            double c;
            int d;
            double DD;
            double dTheta;
            double dx1, dx2;
            int i, j, k;
            int n;
            double f = 0;
            Fitness ff = new Fitness(Constants.fMax);
            int grid;
            double p;
            double s11, s12, s21, s22;
            double sum1, sum2;
            double t0, tt, t1;
            double x1, x2, x3, x4;
            double xd;
            Position xs;
            double[,] xy = new double[8, 2];
            double y, y1, y2;
            double z, z2;
            double[,] zz = new double[8, 8];

            // Shifted Parabola/Sphere (CEC 2005 benchmark)
            double[] offset_0 = new[]
                                    {
                                        -3.9311900e+001, 5.8899900e+001, -4.6322400e+001, -7.4651500e+001, -1.6799700e+001,
                                        -8.0544100e+001, -1.0593500e+001, 2.4969400e+001, 8.9838400e+001, 9.1119000e+000,
                                        -1.0744300e+001, -2.7855800e+001, -1.2580600e+001, 7.5930000e+000, 7.4812700e+001,
                                        6.8495900e+001, -5.3429300e+001, 7.8854400e+001, -6.8595700e+001, 6.3743200e+001,
                                        3.1347000e+001, -3.7501600e+001, 3.3892900e+001, -8.8804500e+001, -7.8771900e+001,
                                        -6.6494400e+001, 4.4197200e+001, 1.8383600e+001, 2.6521200e+001, 8.4472300e+001
                                    };
            // Shifted Rosenbrock (CEC 2005 benchmark)
            double[] offset_2 = new[]
                                    {
                                        8.1023200e+001, -4.8395000e+001,  1.9231600e+001, -2.5231000e+000,  7.0433800e+001,
                                        4.7177400e+001, -7.8358000e+000, -8.6669300e+001,  5.7853200e+001, -9.9533000e+000,
                                        2.0777800e+001,  5.2548600e+001,  7.5926300e+001,  4.2877300e+001, -5.8272000e+001,
                                        -1.6972800e+001,  7.8384500e+001,  7.5042700e+001, -1.6151300e+001,  7.0856900e+001,
                                        -7.9579500e+001, -2.6483700e+001,  5.6369900e+001, -8.8224900e+001, -6.4999600e+001,
                                        -5.3502200e+001, -5.4230000e+001,  1.8682600e+001, -4.1006100e+001, -5.4213400e+001
                                    };
            // Shifted Rastrigin (CEC 2005)
            double[] offset_3 = new[]
                                    {
                                        1.9005000e+000, -1.5644000e+000, -9.7880000e-001, -2.2536000e+000,  2.4990000e+000,
                                        -3.2853000e+000,  9.7590000e-001, -3.6661000e+000,  9.8500000e-002, -3.2465000e+000,
                                        3.8060000e+000, -2.6834000e+000, -1.3701000e+000,  4.1821000e+000,  2.4856000e+000,
                                        -4.2237000e+000,  3.3653000e+000,  2.1532000e+000, -3.0929000e+000,  4.3105000e+000,
                                        -2.9861000e+000,  3.4936000e+000, -2.7289000e+000, -4.1266000e+000, -2.5900000e+000,
                                        1.3124000e+000, -1.7990000e+000, -1.1890000e+000, -1.0530000e-001, -3.1074000e+000
                                    };

            // Shifted Schwefel (F2 CEC 2005)
            double[] offset_4 = new[]
                                    {
                                        3.5626700e+001, -8.2912300e+001, -1.0642300e+001, -8.3581500e+001,  8.3155200e+001,
                                        4.7048000e+001, -8.9435900e+001, -2.7421900e+001,  7.6144800e+001, -3.9059500e+001,
                                        4.8885700e+001, -3.9828000e+000, -7.1924300e+001,  6.4194700e+001, -4.7733800e+001,
                                        -5.9896000e+000 ,-2.6282800e+001, -5.9181100e+001,  1.4602800e+001, -8.5478000e+001,
                                        -5.0490100e+001,  9.2400000e-001,  3.2397800e+001,  3.0238800e+001, -8.5094900e+001,
                                        6.0119700e+001, -3.6218300e+001, -8.5883000e+000, -5.1971000e+000,  8.1553100e+001
                                    };

            // Shifted Griewank (CEC 2005)
            double[] offset_5 = new[]
                                    {
                                        -2.7626840e+002, -1.1911000e+001, -5.7878840e+002, -2.8764860e+002, -8.4385800e+001,
                                        -2.2867530e+002, -4.5815160e+002, -2.0221450e+002, -1.0586420e+002, -9.6489800e+001,
                                        -3.9574680e+002, -5.7294980e+002, -2.7036410e+002, -5.6685430e+002, -1.5242040e+002,
                                        -5.8838190e+002, -2.8288920e+002, -4.8888650e+002, -3.4698170e+002, -4.5304470e+002,
                                        -5.0658570e+002, -4.7599870e+002, -3.6204920e+002, -2.3323670e+002, -4.9198640e+002,
                                        -5.4408980e+002, -7.3445600e+001, -5.2690110e+002, -5.0225610e+002, -5.3723530e+002
                                    };

            // Shifted Ackley (CEC 2005)
            double[] offset_6 = new[]
                                    {
                                        -1.6823000e+001,  1.4976900e+001,  6.1690000e+000,  9.5566000e+000,  1.9541700e+001,
                                        -1.7190000e+001, -1.8824800e+001,  8.5110000e-001, -1.5116200e+001,  1.0793400e+001,
                                        7.4091000e+000,  8.6171000e+000, -1.6564100e+001, -6.6800000e+000,  1.4543300e+001,
                                        7.0454000e+000, -1.8621500e+001,  1.4556100e+001, -1.1594200e+001, -1.9153100e+001,
                                        -4.7372000e+000,  9.2590000e-001,  1.3241200e+001, -5.2947000e+000,  1.8416000e+000,
                                        4.5618000e+000, -1.8890500e+001,  9.8008000e+000, -1.5426500e+001,  1.2722000e+000
                                    };

            // Data for center-bias test function (code 6)
            double radius = 10; //
            int shift = 1;  // Set to zero in order to have the center on {0, ...,0}, to 1 else
            double[] center = new[]
                                  {
                                      80, -20,  1.9231600e+001, -2.5231000e+000,  7.0433800e+001,
                                      4.7177400e+001, -7.8358000e+000, -8.6669300e+001,  5.7853200e+001, -9.9533000e+000,
                                      2.0777800e+001,  5.2548600e+001,  7.5926300e+001,  4.2877300e+001, -5.8272000e+001,
                                      -1.6972800e+001,  7.8384500e+001,  7.5042700e+001, -1.6151300e+001,  7.0856900e+001,
                                      -7.9579500e+001, -2.6483700e+001,  5.6369900e+001, -8.8224900e+001, -6.4999600e+001,
                                      -5.3502200e+001, -5.4230000e+001,  1.8682600e+001, -4.1006100e+001, -5.4213400e+001
                                  };
            Position summit = new Position(Constants.DMax);

            Program.nEval = Program.nEval + 1; // Number of fitness evaluations (global variable)

            //---------------------------------------------------

            xs = x;
            ff.size = 1; // Default value (no constraint)

            switch (pb.function)
            {
                default:
                    throw new ArgumentException("Wrong code function");
                    break;
                    // CEC 2005 benchmark
                case 100: // Parabola (Sphere) CEC 2005
                    f = -450;
                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d];
                        xs.x[d] = xd - offset_0[d];
                        f = f + xd * xd;
                    }
                    break;

                case 102:  // Rosenbrock

                    for (d = 0; d < xs.size; d++)
                    {
                        xs.x[d] = xs.x[d] - offset_2[d];
                    }

                    f = 390;
                    for (d = 1; d < xs.size; d++)
                    {
                        tt = xs.x[d - 1] - 1;
                        f = f + tt * tt;

                        tt = xs.x[d - 1] * xs.x[d - 1] - xs.x[d];
                        f = f + 100 * tt * tt;
                    }
                    break;

                case 103: // Rastrigin
                    for (d = 0; d < xs.size; d++)
                    {
                        xs.x[d] = xs.x[d] - offset_3[d];
                    }
                    f = -330;
                    k = 10;

                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d];
                        f = f + xd * xd - k * Math.Cos(2 * Math.PI * xd);
                    }
                    f = f + xs.size * k;
                    break;

                case 104: // Schwefel (F2)
                    for (d = 0; d < xs.size; d++)
                    {
                        xs.x[d] = xs.x[d] - offset_4[d];
                    }

                    f = -450;
                    for (d = 0; d < xs.size; d++)
                    {
                        sum2 = 0.0;
                        for (k = 0; k <= d; k++)
                        {
                            sum2 += xs.x[k];
                        }
                        f += sum2 * sum2;
                    }
                    break;

                case 105: // Griewank. WARNING: in the CEC 2005 benchmark it is rotated
                    sum1 = 0.0;
                    sum2 = 1.0;
                    f = -180;
                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d] - offset_5[d];
                        sum1 += xd * xd;
                        sum2 *= Math.Cos(xd / Math.Sqrt(1.0 + d));
                    }
                    f = f + 1.0 + sum1 / 4000.0 - sum2;
                    break;

                case 106: // Ackley
                    f = -140;

                    sum1 = 0.0;
                    sum2 = 0.0;
                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d] - offset_6[d];
                        sum1 += xd * xd;
                        sum2 += Math.Cos(2.0 * Math.PI * xd);
                    }
                    sum1 = -0.2 * Math.Sqrt(sum1 / xs.size);
                    sum2 /= xs.size;
                    f = f + 20.0 + Math.E - 20.0 * Math.Exp(sum1) - Math.Exp(sum2);
                    break;

                case 0:		// Parabola (Sphere)
                    f = 0.0;
                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d];
                        //xd = xs.x[d]-50; // Shifted

                        f = f + xd * xd;
                    }
                    //printf("\n2442  xs.size %i f %f x0 %f",xs.size,f,xs.x[0]);
                    break;

                case 1:		// Griewank
                    f = 0;
                    p = 1;

                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d];
                        //xd=xd-150;
                        f = f + xd * xd;
                        p = p * Math.Cos(xd / Math.Sqrt((double)(d + 1)));
                    }
                    f = f / 4000 - p + 1;
                    break;

                case 2:		// Rosenbrock
                    f = 0;
                    t0 = xs.x[0] + 1;	// Solution on (0,...0)
                    for (d = 1; d < xs.size; d++)
                    {

                        t1 = xs.x[d] + 1;
                        tt = 1 - t0;
                        f += tt * tt;
                        tt = t1 - t0 * t0;
                        f += 100 * tt * tt;
                        t0 = t1;
                    }
                    break;

                case 3:		// Rastrigin
                    f = 0;
                    k = 10;

                    for (d = 0; d < xs.size; d++)
                    {
                        xd = xs.x[d];
                        f = f + xd * xd - k * Math.Cos(2 * Math.PI * xd);
                    }
                    f = f + xs.size * k;
                    break;

                case 4:		// 2D Tripod function
                    // Note that there is a big discontinuity right on the solution
                    // point.
                    x1 = xs.x[0];
                    x2 = xs.x[1];
                    s11 = (1.0 - Tools.sign(x1)) / 2;
                    s12 = (1.0 + Tools.sign(x1)) / 2;
                    s21 = (1.0 - Tools.sign(x2)) / 2;
                    s22 = (1.0 + Tools.sign(x2)) / 2;

                    //f = s21 * (Math.Abs(x1) - x2); // Solution on (0,0)
                    f = s21 * (Math.Abs(x1) + Math.Abs(x2 + 50)); // Solution on (0,-50)
                    f = f + s22 * (s11 * (1 + Math.Abs(x1 + 50) + Math.Abs(x2 - 50))
                                   + s12 * (2 + Math.Abs(x1 - 50) + Math.Abs(x2 - 50)));
                    break;

                case 5:  // Ackley
                    sum1 = 0;
                    sum2 = 0;
                    DD = x.size;
                    for (d = 0; d < x.size; d++)
                    {
                        xd = xs.x[d];
                        sum1 = sum1 + xd * xd;
                        sum2 = sum2 + Math.Cos(2 * Math.PI * xd);
                    }
                    f = -20 * Math.Exp(-0.2 * Math.Sqrt(sum1 / DD)) - Math.Exp(sum2 / DD) + 20 + Math.Exp(1);
                    break;

                case 6:  // Center-bias test function
                    // on [-100,100]^2
                    for (d = 0; d < x.size; d++) summit.x[d] = shift * center[d];

                    z = Tools.distanceL(x, summit, 2);
                    if (z > radius) f = radius; else f = z;
                    break;

                case 7: // Pressure vessel (penalty method)
                case 1007: // confinement method
                    // Ref New Optim. Tech. in Eng. p 638
                    // D = 4
                    x1 = xs.x[0]; // [1.1,12.5] granularity 0.0625
                    x2 = xs.x[1];// [0.6,12.5] granularity 0.0625
                    x3 = xs.x[2]; // [0,240]
                    x4 = xs.x[3];// [0,240]

                    f = 0.6224 * x1 * x3 * x4 + 1.7781 * x2 * x3 * x3 + 3.1611 * x1 * x1 * x4 + 19.84 * x1 * x1 * x3;

                    ff = Position.Constraint(xs, pb.function, pb.EpsilonConstraint);

                    if (pb.Constraint == 0)// Constraints, by penalty method
                    {
                        if (ff.f[1] > 0) { c = 1 + Math.Pow(10, 10) * ff.f[1]; f = f * c * c; }
                        if (ff.f[2] > 0) { c = 1 + ff.f[2]; f = f * c * c; }
                        if (ff.f[3] > 0) { c = 1 + ff.f[3]; f = f * c * c; }
                    }
                    break;

                case 8: // Coil compression spring  (penalty method)
                    // Ref New Optim. Tech. in Eng. p 644
                case 1008: // confinement method

                    x1 = xs.x[0]; // {1,2, ... 70}
                    x2 = xs.x[1];//[0.6, 3]
                    x3 = xs.x[2];// relaxed form [0.207,0.5]  dx=0.001
                    // In the original problem, it is a list of
                    // acceptable values
                    // {0.207,0.225,0.244,0.263,0.283,0.307,0.331,0.362,0.394,0.4375,0.5}

                    f = Math.PI * Math.PI * x2 * x3 * x3 * (x1 + 2) * 0.25;
                    // Constraints
                    ff = Position.Constraint(xs, pb.function, pb.EpsilonConstraint);
                    if (pb.Constraint == 0)
                    {
                        if (ff.f[1] > 0) { c = 1 + ff.f[1]; f = f * c * c * c; }
                        if (ff.f[2] > 0) { c = 1 + ff.f[1]; f = f * c * c * c; }
                        if (ff.f[3] > 0) { c = 1 + ff.f[3]; f = f * c * c * c; }
                        if (ff.f[4] > 0) { c = 1 + Math.Pow(10, 10) * ff.f[4]; f = f * c * c * c; }
                        if (ff.f[5] > 0) { c = 1 + Math.Pow(10, 10) * ff.f[5]; f = f * c * c * c; }
                    }
                    break;

                case 9: // Gear train
                    x1 = xs.x[0]; // {12,13, ... 60}
                    x2 = xs.x[1];// {12,13, ... 60}
                    x3 = xs.x[2];// {12,13, ... 60}
                    x4 = xs.x[3];// {12,13, ... 60}

                    f = 1.0 / 6.931 - x1 * x2 / (x3 * x4);
                    f = f * f;
                    break;

                    // case 10
                case 10: // Cellular phone
                    // Grid 100 x 100. You may modify it for more or less precision
                    // (which implies, of course, more or less computation time)
                    grid = 100;
                    f = 0;

                    dx1 = (pb.SwarmSize.max[0] - pb.SwarmSize.min[0]) / grid;

                    for (i = 0; i <= grid; i++)
                    {
                        y1 = pb.SwarmSize.min[0] + i * dx1;
                        dx2 = (pb.SwarmSize.max[1] - pb.SwarmSize.min[1]) / grid;
                        for (j = 0; j <= grid; j++)
                        {
                            y2 = pb.SwarmSize.min[1] + j * dx2;
                            z = 0; // Max field
                            for (d = 0; d < xs.size; d = d + 2) // For each station
                            {
                                x1 = xs.x[d];
                                x2 = xs.x[d + 1];

                                z2 = 1.0 / ((x1 - i) * (x1 - y1) + (x2 - j) * (x2 - y2) + 1);
                                if (z2 > z) z = z2;
                            }
                            f = f + z;
                        }
                    }
                    f = 1.0 / f; // In order to have something to minimise
                    break;

                case 12: // Schwefel
                    f = 418.98288727243369 * pb.SwarmSize.D;
                    for (d = 0; d < pb.SwarmSize.D; d++)
                    {
                        xd = xs.x[d];
                        f = f - xd * Math.Sin(Math.Sqrt(Math.Abs(xd)));
                    }
                    break;
                case 13: // Cutting problem
                    sum1 = 0;
                    f = 0;
                    for (d = 0; d < pb.SwarmSize.D; d++) // Waste
                    {
                        sum1 = sum1 + xs.x[d];
                        if (sum1 < Constants.toCut && d < pb.SwarmSize.D - 1) continue;
                        if (sum1 < Constants.toCut && d == pb.SwarmSize.D - 1)
                        {
                            f = f + Constants.toCut - sum1;
                            continue;
                        }
                        f = f + Constants.toCut - sum1 + xs.x[d];
                        sum1 = xs.x[d];
                    }

                    //Constraints
                    for (i = 0; i < pb.SwarmSize.valueNb; i++) // For each value ...
                    {
                        n = 0;
                        for (d = 0; d < pb.SwarmSize.D; d++) // ... count how many times it appears
                        {
                            if (xs.x[d] >= Constants.valueList[i] - Constants.Zero && xs.x[d] <= Constants.valueList[i] + Constants.Zero)
                                n = n + 1;
                            //printf("\n 2732  %f %f %f",valueList[i]-zero,xs.x[d], valueList[i]+zero);
                        }
                        if (n != Constants.pieceNb[i]) // If not exactly the right number of times => penalty
                        {
                            f = f + Constants.toCut; // f+100000
                            //printf("\n 2716, %i, %i, should be %i",i,n,pieceNb[i]);
                        }
                    }
                    //printf("\n2740 f %f",f);
                    break;

                case 14: // Polygon. longest perimeter
                    // Cartesian coordinates
                    xy[0, 0] = 0; xy[0, 1] = 0;
                    xy[1, 0] = xs.x[0]; xy[1, 1] = 0;
                    i = 2;
                    for (d = 1; d < pb.SwarmSize.D; d = d + 2)
                    {
                        xy[i, 0] = xs.x[d + 1] * Math.Cos(xs.x[d]); // rho*Math.Cos(theta)
                        xy[i, 1] = xs.x[d + 1] * Math.Sin(xs.x[d]); // rho*sin(theta)
                        i = i + 1;
                    }

                    // Distances
                    n = i;
                    z2 = 0; // Distance max
                    y = 0; // Sum of the distances
                    for (i = 1; i < n; i++)
                    {
                        for (j = 0; j < i; j++)
                        {
                            zz[i, j] = Math.Sqrt(Math.Pow(xy[i, 0] - xy[j, 0], 2) + Math.Pow(xy[i, 1] - xy[j, 1], 2));
                            y = y + zz[i, j];
                            if (zz[i, j] > z2) z2 = zz[i, j];
                        }
                    }

                    // Perimeter
                    //	f=zz[n-1][0];
                    //	for(i=1;i<n;i++) f=f+zz[i][i-1];

                    // To minimise
                    //f=2+4*sin(pi/12)-f;
                    f = Math.PI - f;

                    // Max sum of the distances y
                    f = n * (n - 1) - y; //to minimise

                    // Constraints -----
                    p = (n - 2) * Math.PI; // penalty
                    //dTheta=(n-2)*pi/(2*n);
                    dTheta = Constants.Zero;
                    // Diameter = 1
                    if (z2 > 1 + Constants.Zero) f = f + p;
                    if (z2 < 1 - Constants.Zero) f = f + p;

                    // Convex
                    for (d = 1; d < pb.SwarmSize.D - 2; d = d + 2) // Increasing theta
                    {
                        //if(xs.x[d]>xs.x[d+2]) f=f+p;
                        if (xs.x[d + 2] < xs.x[d] + dTheta) f = f + p;
                    }

                    // Angle max
                    if (xs.x[pb.SwarmSize.D - 2] > Math.PI) f = f + p;

                    // Sides
                    for (d = 2; d < pb.SwarmSize.D - 2; d = d + 2)
                    {
                        if (xs.x[d] < xs.x[d - 2] && xs.x[d] < xs.x[d + 2]) f = f + p;
                    }

                    //if(xs.x[0]<0.2) f=f+p;
                    /*
                     for(d=2;d<pb.SwarmSize.D;d=d+2) //
                     {
                         if(xs.x[d]<xs.x[0]) f=f+p;
                     }
                     */
                    break;

                case 15: // Constrained g13, Penalty method
                case 1015: // 			Confinement method
                    // D = 5
                    // x1, x2 in [-2.3, 2.3]
                    // x3, x4, x5 [-3.2, 3.2]

                    f = Math.Exp(xs.x[0] * xs.x[1] * xs.x[2] * xs.x[3] * xs.x[4]);
                    ff = Position.Constraint(xs, pb.function, pb.EpsilonConstraint);

                    if (pb.Constraint == 0) // Penalty method
                    {
                        if (ff.f[1] > 0) f = f + ff.f[1];
                        if (ff.f[2] > 0) f = f + ff.f[2];
                        if (ff.f[3] > 0) f = f + ff.f[3];
                    }

                    break;

                case 16: // G3 (constrained)
                    // min =0 on (1/Math.Sqrt(D), ...)
                    f = 1;
                    sum1 = 0;
                    for (d = 0; d < x.size; d++)
                    {
                        xd = xs.x[d];
                        f = f * xd;
                        sum1 = sum1 + xd * xd;
                    }
                    f = Math.Abs(1 - Math.Pow(x.size, x.size / 2.0) * f) + x.size * Math.Abs(sum1 - 1);
                    break;

                case 17: // Lennard-Jones
                    f = Program.lennard_jones(xs);
                    break;

                case 99: // Test
                    x1 = xs.x[0];
                    x2 = xs.x[1];
                    xd = x1 * x1 + x2 * x2;
                    f = xd - Math.Cos(18 * x1) - Math.Cos(18 * x2);
                    f = f + Math.Abs(xd - 0.6); // One constraint (penalty method);

                    break;

                    // 1D Test "deceptive" on [0 1]
                    xd = xs.x[0];
                    if (xd < 0.6) f = xd;
                    else f = 0.6 - (0.5 / 0.4) * (xd - 0.6);
                    break;

                    // 1D test  [-50, 50]
                    xd = xs.x[0];
                    f = xd * (xd + 1) * Math.Cos(xd);
                    break;

                    // KrishnaKumar
                    f = 0;
                    for (d = 0; d < xs.size - 1; d++)
                    {
                        f = f + Math.Sin(xs.x[d] + xs.x[d + 1]) + Math.Sin(2 * xs.x[d] * xs.x[d + 1] / 3);
                    }
                    break;

                    xd = xs.x[0];
                    //if (xd<9) f=10-xd; else f=10*xd-90;
                    if (xd <= 1) f = 10 * xd; else f = 11 - xd;
                    break;

                case 1000: //1-D  Landscape on a file
                    // Find the nearest x
                    xd = xs.x[0];
                    z = Math.Abs(xd - Program.funct.x[0]);
                    f = Program.funct.fx[0];
                    for (d = 1; d < Program.funct.N; d++)
                    {
                        z2 = Math.Abs(xd - Program.funct.x[d]);
                        if (z2 < z)
                        {
                            z = z2;
                            f = Program.funct.fx[d];
                        }
                    }
                    break;

            }

            ff.f[0] = Math.Abs(f - pb.ObjectiveValue);
            return ff;
        }