Example #1
0
File: Program.cs Project: 7lb/TSP
 public static void display(Population p, int gen)
 {
     Tour best = p.findBest();
     System.Console.WriteLine("Generation {0}\n" +
         "Best fitness:  {1}\n" +
         "Best distance: {2}\n", gen, best.fitness, best.distance);
 }
Example #2
0
 public Resource(ResourceType type, ResourceLevel level)
 {
     Type = type;
     Level = level;
     Population = new Population();
     StorageLevel = 20;
 }
Example #3
0
        static Population AdvanceGeneration(Population population, ISelection selection, ICrossover crossover, IMutation mutation)
        {
            var chromosomes = new List<Chromosome>();
            population = new Population(population.Take((int)(truncationRate * population.Count()))); // TRUNCATION
            chromosomes.AddRange(population.Take((int)(elitismRate * chromosomeCount)));  //ELITE (assuming that the chromosomes in the population are sorted by fitness (the fitter are at the top of the list)

            do
            {
                Chromosome chosen1 = selection.Select(population),
                           chosen2 = selection.Select(population);

                if (random.NextDouble() < crossoverRate)
                {
                    var children = crossover.Crossover(chosen1, chosen2); // CROSSOVER
                    chosen1 = children.Item1;
                    chosen2 = children.Item2;
                }

                if (random.NextDouble() < mutationRate)
                {
                    chosen1 = mutation.Mutate(chosen1); // MUTATION
                }

                if (random.NextDouble() < mutationRate)
                {
                    chosen2 = mutation.Mutate(chosen2); // MUTATION
                }

                chromosomes.Add(chosen1);
                chromosomes.Add(chosen2);
            } while (chromosomes.Count < chromosomeCount);

            return new Population(chromosomes);
        }
Example #4
0
    public void LoadAll(Population pop,float curHouses)
    {
        LoadAllHouses(curHouses);
        LoadAllPeople(pop);
        LoadAllBiomes();

    }
    public override void Select(Population population, SelectionBuffer selection, GeneticAlgorithm.NextStepDelegate callback)
    {
        int size = 0;

        // TODO: Implement settings for how to truncate.
        float cutoff = 0;
        switch (truncationMode) {
        case TruncationMode.AboveMiddle:
            cutoff = population.MinFitness + (population.MaxFitness - population.MinFitness)/2;
            break;
        case TruncationMode.AboveMean:
            cutoff = population.MeanFitness;
            break;
        case TruncationMode.AboveMedian:
            cutoff = population.MedianFitness;
            break;
        }

        for (int i = 0; i < population.Size; i++) {
            if (population[i].Fitness > cutoff) {
                selection[size].CloneFrom(population[i].Genome);
                size++;
            }
        }

        selection.Size = size;
        callback();
    }
        public Population AdvancePopulation(Population population)
        {
            var chromosomes = new List<Chromosome>();
            population = new Population(population.Take((int)(TruncationRate * population.Count()))); // TRUNCATION

            do
            {
                Chromosome chosen1 = selection.Select(population),
                           chosen2 = selection.Select(population);

                if (random.NextDouble() < CrossoverRate)
                {
                    var children = crossover.Crossover(chosen1, chosen2); // CROSSOVER
                    chosen1 = children.Item1;
                    chosen2 = children.Item2;
                }

                if (random.NextDouble() < MutationRate)
                {
                    chosen1 = mutation.Mutate(chosen1); // MUTATION
                }

                if (random.NextDouble() < MutationRate)
                {
                    chosen2 = mutation.Mutate(chosen2); // MUTATION
                }

                chromosomes.Add(chosen1);
                chromosomes.Add(chosen2);
            } while (chromosomes.Count < ChromosomeCount);

            return new Population(chromosomes);
        }
Example #7
0
 public override void FitnessFunction(Population population, GeneticAlgorithm.NextStepDelegate callback)
 {
     this.population = population;
     InitiateNewSimulation();
     simulating = true;
     doneCallback = callback;
 }
Example #8
0
 public PopulationSimulator(int width, int height)
 {
     swarmInBirthOrder = new Species();
     swarmInXOrder = new Species();
     swarmInYOrder = new Species();
     Population = new Population();
 }
        private void RunGA(){
            _teams = LoadTeams();
            _winners = _teams.FindAll(l => l.Winner == true);
            _losers = _teams.FindAll(l => l.Winner == false);

            const double crossoverProbability = 0.85;
            const double mutationProbability = 0.15;
            const int elitismPercentage = 5;

            var population = new Population(1000, 72, true, false, ParentSelectionMethod.TournamentSelection);

            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.DoublePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.Run(TerminateAlgorithm);

        }
	public void InitializePanelWithTrainerData() {
		DebugBot.DebugFunctionCall("TPopUI; InitializePanelWithTrainerData(); ", debugFunctionCalls);
		Trainer trainer = trainerModuleScript.gameController.masterTrainer;
		if(trainer.PlayerList != null) {

			int curPlayer = trainer.CurPlayer;
			//Debug.Log ("InitializePanelWithTrainerData(), " + trainer.PlayerList[curPlayer-1].maxMaxPopulationSize.ToString());
			//sliderMaxPopulationSize.minValue = trainer.PlayerList[curPlayer-1].minMaxPopulationSize;
			//sliderMaxPopulationSize.maxValue = trainer.PlayerList[curPlayer-1].maxMaxPopulationSize;
			//sliderMaxPopulationSize.value = trainer.PlayerList[curPlayer-1].maxPopulationSize;
			if(trainer.PlayerList[curPlayer-1].masterPopulation != null) {  // if the current player has a Population instance:
				populationRef = trainer.PlayerList[curPlayer-1].masterPopulation; // get current population instance
				//Current Population text:
				textCurrentPopulationSize.text = "Current Population Size: " + (populationRef.isFunctional ? populationRef.masterAgentArray.Length.ToString() : "0"); // Update this later!!
				//Current Max Population Size:
				sliderMaxPopulationSize.minValue = minMaxPopulationSize; // set up slider bounds
				sliderMaxPopulationSize.maxValue = maxMaxPopulationSize;
				sliderMaxPopulationSize.value = populationRef.populationMaxSize;
				textMaxPopulationSize.text = populationRef.populationMaxSize.ToString();

			}
			else {  // Population hasn't been created yet:
				//textMaxPopulationSize.text = trainer.PlayerList[curPlayer-1].maxPopulationSize.ToString();
			}
		}

		valuesChanged = false;
		applyPressed = false;

		UpdateUIWithCurrentData();
	}
    public DemoPlayerInputStrategy()
    {
        var population = new Population (6, 6, new DemoPlayerChromosome ());
        var fitness = new DemoPlayerFitness ();
        var selection = new EliteSelection ();
        var crossover = new OnePointCrossover (0);
        var mutation = new UniformMutation (true);

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

        m_ga.MutationProbability = 0.5f;
        m_ga.GenerationRan += (sender, e) => {
            m_bestChromossome = m_ga.BestChromosome as DemoPlayerChromosome;

            if(m_bestChromossome.AvoidAliensProjectilesProbability > 0.9f) {
                HorizontalDirection = 1f;
            }
        };
        m_ga.Start ();

        SHThread.PingPong (.01f, 0, 1, (t) => {
            m_ga.Termination = new GenerationNumberTermination (m_ga.GenerationsNumber + 1);
            m_ga.Resume();

            return true;
        });
    }
Example #12
0
 void Awake()
 {
     if(master == null){
         master = this;
     } else if (master != this){
         Destroy(gameObject);
     }
 }
Example #13
0
 //    string name,
 //    float fullFoodAmt,
 //    float feedIntSec,
 //    float hungryWindow,
 //    float energyProduceVal
 public override Organism Create(Population population)
 {
     return new Organism(population,
                         "fish",
                         1f,
                         3f,
                         3f,
                         5f);
 }
Example #14
0
 //    string name,
 //    float fullFoodAmt,
 //    float feedIntSec,
 //    float hungryWindow,
 //    float energyProduceVal
 public override Organism Create(Population population)
 {
     return new Organism(population,
                         "bacteria",
                         1f,
                         20f,
                         20f,
                         1f);
 }
        public Parametres(Population oldParam)
        {
            InitializeComponent();

            MaxNotes = oldParam.MaxNotes;
            MaxIndividus = oldParam.MaxIndividus;
            Crossover = oldParam.Crossover;
            Mutarate = oldParam.Mutarate;
        }
    public void InitializePanelWithTrainerData() {
		
		Player currentPlayer = trainerModuleScript.gameController.masterTrainer.PlayerList[trainerModuleScript.gameController.masterTrainer.CurPlayer-1];
		populationRef = currentPlayer.masterPopulation;
		
		DebugBot.DebugFunctionCall("LoadPopulationUI; InitializePanelWithTrainerData(); ", debugFunctionCalls);
		
		UpdateUIWithCurrentData();
	}
Example #17
0
 // override this
 public virtual Organism Create(Population population)
 {
     return new Organism(population,
                         "unnamed",
                         0f,
                         0f,
                         0f,
                         0f);
 }
        public void SetUp()
        {
            PopulationGenerator = new Mock<IPopulationGenerator<string>>();
            FitnessEvaluator = new Mock<IFitnessEvaluator<string>>();
            Count = 1;

            PopulationMock = new Mock<Population<string>>(Count, PopulationGenerator.Object, FitnessEvaluator.Object);
            Population = new Population<string>(Count, PopulationGenerator.Object, FitnessEvaluator.Object);
        }
Example #19
0
    public Agent(Population populationIn, int generationIn)
    {
        //	Debug.Log("Agent created " + Time.time);
        componentsList = new ArrayList();
        generation = generationIn;
        population = populationIn;

        CreateRandomComponents();
    }
Example #20
0
 private void Scale(Population population)
 {
     foreach (var chromosome in population.Chromosomes)
     {
         double value = chromosome.Value + (population.AvgFitness - c * _sigma);
         if (value < 0) value = 0;
         chromosome.Value = value;
     }
 }
Example #21
0
    public virtual void FitnessFunctionSimple(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            PhenomeDescription pd = population[i];
            pd.Fitness = CalculateFitness(pd.Genome);
        }

        CalculateMinMaxTotal(population);
        callback();
    }
Example #22
0
    public override void FitnessFunction(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            PhenomeDescription pd = population[i];
            pd.Fitness = CalculateFitness(pd.Genome as BaseGenomeBinary);
        }

        CalculateMinMaxTotal(population);
        callback();
    }
Example #23
0
        protected internal override void InitializeNewRun()
        {
            base.InitializeNewRun();

            rule = (GARule)LearningConnections.ItemArray[0].Rule;
            population = new Population(rule.PopulationSize);
            bestSel = new GaussianSelectionAlgorithm(rule.BestSelectStdDev);
            worstSel = new GaussianSelectionAlgorithm(rule.WorstSelectStdDev, SelectionDirection.FromBottom);
            nextStep = null;
        }
Example #24
0
        private void CalculateSigma(Population population)
        {
            double avg = population.AvgFitness;

            double sum = 0;
            foreach(var chromosome in population.Chromosomes)
                sum += Math.Pow(chromosome.Value - avg ,2);

            _sigma = Math.Sqrt(sum / population.Count);
        }
        public static void Write(XmlNode parentNode, Population p, IActivationFunction activationFn)
        {
            XmlElement xmlPopulation = XmlUtilities.AddElement(parentNode, "population");
            XmlUtilities.AddAttribute(xmlPopulation, "activation-fn-id", activationFn.FunctionId);

            foreach(IGenome genome in p.GenomeList)
            {
                genome.Write(xmlPopulation);
            }
        }
Example #26
0
 public static SaveSpecies GetPopulationAsSaveSpecies(Population population)
 {
     SaveSpecies saveSpecies = new SaveSpecies();
     saveSpecies.CreadtedDt = DateTime.Now;
     foreach (Species species in population)
     {
         saveSpecies.SavedSpecies.Add(GetSavedGenomes(species));
     }
     return saveSpecies;
 }
Example #27
0
        public void GeneratePopulationSectors(ulong size) {

            //!@ ToDo: parse types from assembly
            Type[] feature_types = new Type[] {
                typeof(Male),
                typeof(Female),

                typeof(Asian),
                typeof(Indian),

                typeof(Jobless),
                typeof(Retired),
                typeof(Disable),
                typeof(Artist),
                typeof(Engeneer),

                typeof(Child),
                typeof(Teenager),
                typeof(Adult),
                typeof(Senior)
            };

            Sections = new Population[] {
                new Population(123, typeof(Male), typeof(Asian), typeof(Engeneer), typeof(Adult)),
                new Population(321, typeof(Female), typeof(Asian), typeof(Engeneer), typeof(Adult)),
                new Population(0, typeof(Pregnant), typeof(Asian), typeof(Engeneer), typeof(Adult)),
                new Population(0, typeof(Male), typeof(Asian), typeof(Jobless), typeof(Child)),
                new Population(0, typeof(Female), typeof(Asian), typeof(Jobless), typeof(Child))
            };
            Sections[1].Sex.AddTarget(Sections[2] as ISectionSize<ulong>, Feature.Targets.Pregnant);
            Sections[2].Sex.AddTarget(Sections[1] as ISectionSize<ulong>, Feature.Targets.Female);
            Sections[2].Sex.AddTarget(Sections[4] as ISectionSize<ulong>, Feature.Targets.FemaleChild);
            Sections[2].Sex.AddTarget(Sections[3] as ISectionSize<ulong>, Feature.Targets.MaleChild);

            //!@ test
            //var population = new List<Population>();
            //for (int i = 0; i < 2; i++) {
            //    for (int j = 2; j < 4; j++) {
            //        for (int k = 4; k < 9; k++) {
            //            for (int t = 9; t < 13; t++) {
            //                population.Add(
            //                    new Population(
            //                        1,
            //                        Activator.CreateInstance(feature_types[i]) as Gender,
            //                        Activator.CreateInstance(feature_types[j]) as Nationality,
            //                        Activator.CreateInstance(feature_types[k]) as EmpStatus,
            //                        Activator.CreateInstance(feature_types[t]) as AgeGroup)
            //                    );
            //            }
            //        }
            //    }
            //}

            //Sections = population.ToArray();   
        }
    public void evolveNextGeneration()
    {
        // save data before evolving
        this.saveTxtFile ();

        this.pop = Algorithm.evolvePopulation(this.pop);
        this.championFitness = this.pop.getGenome (0).fitness;
        this.generationCount++;
        this.index = 0;
        testNextGenome ();
    }
	public void InitializePanelWithTrainerData() {

		Player currentPlayer = trainerModuleScript.gameController.masterTrainer.PlayerList[trainerModuleScript.gameController.masterTrainer.CurPlayer-1];
		populationRef = currentPlayer.masterPopulation;
				
		DebugBot.DebugFunctionCall("TNewPopUI; InitializePanelWithTrainerData(); ", debugFunctionCalls);
		sliderPopulationSize.minValue = minMaxPopulationSize;
		sliderPopulationSize.maxValue = maxMaxPopulationSize;

		UpdateUIWithCurrentData();
	}
Example #30
0
        private string createIndividualName(Population population, int individualId, IndividualExtractionOptions options)
        {
            var proposedName = options.GenerateIndividualName(population.Name, individualId);

            return(_containerTask.CreateUniqueName(_buildingBlockRepository.All <Individual>(), proposedName, canUseBaseName: true));
        }
Example #31
0
        static void Main(string[] args)
        {
            #region Excel Input
            FileInfo      InputFile       = new FileInfo(@"D:\InputPLASH.xlsx");
            List <double> InputPrecipUp   = new List <double>();
            List <double> InputPrecipDown = new List <double>();
            List <double> InputQObs       = new List <double>();
            List <double> InputEvap       = new List <double>();
            using (ExcelPackage package = new ExcelPackage(InputFile))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int            ColCount  = worksheet.Dimension.End.Column;
                int            RowCount  = worksheet.Dimension.End.Row;
                for (int row = 2; row <= RowCount; row++)
                {
                    InputPrecipUp.Add(Convert.ToDouble(worksheet.Cells[row, 2].Value));
                    InputPrecipDown.Add(Convert.ToDouble(worksheet.Cells[row, 3].Value));
                    InputQObs.Add(Convert.ToDouble(worksheet.Cells[row, 4].Value));
                    InputEvap.Add(Convert.ToDouble(worksheet.Cells[row, 5].Value));

                    //Console.WriteLine("PrecipUp: {0}, PrecipDown: {1}, Evap: {2}, QObos: {3}", Math.Round(InputPrecipUp[row - 2],3), Math.Round(InputPrecipDown[row - 2], 3), Math.Round(InputQObs[row - 2],3), Math.Round(InputEvap[row - 2],3));
                }
            }


            #endregion Excel Input


            #region PLASH Simulation

            #region Genetic Algorithm
            int    SimulationLength = InputPrecipUp.Count;
            double Timestep         = 24;

            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 2, 24, 0, //Param Upstream
                               0, 0, 0, 120, 6,
                               0, 0, 0, 0,

                               0, 0, 0, 0,     //Initial Upstream

                               0, 0, 2, 24, 0, //Param Downstream
                               0, 0, 0, 120, 6,
                               0, 0, 0, 0,

                               0, 0, 0, 0, //Initial Downstream

                               12, 0.01    //Param Muskingum
                },
                new double[] {
                10, 10, 10, 240, 300,
                0.5, 0.5, 10, 3600, 120,
                3, 500, 1, 1,

                10, 10, 10, 10,

                10, 10, 10, 240, 300,
                0.5, 0.5, 10, 3600, 120,
                20, 200, 1, 1,

                10, 10, 10, 10,

                180, 0.5
            },
                new int[] { 64, 64, 64, 64, 64,
                            64, 64, 64, 64, 64,
                            64, 64, 64, 64,

                            64, 64, 64, 64,

                            64, 64, 64, 64, 64,
                            64, 64, 64, 64, 64,
                            64, 64, 64, 64,

                            64, 64, 64, 64,

                            64, 64 },
                new int[] { 3, 3, 3, 3, 3,
                            3, 3, 3, 3, 3,
                            3, 3, 3, 3,

                            3, 3, 3, 3,

                            3, 3, 3, 3, 3,
                            3, 3, 3, 3, 3,
                            3, 3, 3, 3,

                            3, 3, 3, 3,

                            3, 3 });

            var population = new Population(50, 100, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();
                if (values[12] < values[13] || values[30] < values[31])
                {
                    return(double.NegativeInfinity);
                }
                DateTime[] TimeSeries = new DateTime[SimulationLength];
                TimeSeries[0]         = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                for (int i = 1; i < TimeSeries.Length; i++)
                {
                    TimeSeries[i] = TimeSeries[0].AddHours(Timestep * i);
                }

                PLASHInput InputUp = new PLASHInput
                {
                    DTE_Arr_TimeSeries   = TimeSeries,
                    FLT_Arr_PrecipSeries = InputPrecipUp.ToArray(),
                    FLT_Arr_EPSeries     = InputEvap.ToArray(),
                    FLT_Arr_QtObsSeries  = InputQObs.ToArray(),
                    FLT_Arr_QtUpstream   = new double[SimulationLength]
                };

                PLASHParameters ParamUp = new PLASHParameters
                {
                    FLT_AD       = 861.42252,
                    FLT_AI       = 0.02,
                    FLT_AP       = 0.95,
                    FLT_TimeStep = 24,

                    FLT_DI   = values[0],
                    FLT_IP   = values[1],
                    FLT_DP   = values[2],
                    FLT_KSup = values[3],
                    FLT_CS   = values[4],
                    FLT_CC   = values[5],
                    FLT_CR   = values[6],
                    FLT_PP   = values[7],
                    FLT_KSub = values[8],
                    FLT_KCan = values[9],
                    FLT_CH   = values[10],
                    FLT_FS   = values[11],
                    FLT_PS   = values[12],
                    FLT_UI   = values[13]
                };

                PLASHInitialConditions Res0Up = new PLASHInitialConditions()
                {
                    RImp0 = values[14],
                    RInt0 = values[15],
                    RSup0 = values[16],
                    RCan0 = values[17]
                };

                PLASHReservoir ReservoirUp = new PLASHReservoir();

                PLASHOutput OutputUp = new PLASHOutput();

                PLASH.Run(InputUp, ParamUp, Res0Up, ReservoirUp, OutputUp);


                Muskingum Musk = new Muskingum()
                {
                    FLT_K             = values[36],
                    FLT_X             = values[37],
                    FLT_Timestep      = Timestep,
                    FLT_Arr_InputFlow = OutputUp.FLT_Arr_Qt_Calc
                };


                PLASHInput InputDown = new PLASHInput()
                {
                    DTE_Arr_TimeSeries   = TimeSeries,
                    FLT_Arr_PrecipSeries = InputPrecipDown.ToArray(),
                    FLT_Arr_EPSeries     = InputEvap.ToArray(),
                    FLT_Arr_QtObsSeries  = InputQObs.ToArray(),
                    FLT_Arr_QtUpstream   = Muskingum.ProcessDamping(Musk)
                };

                PLASHParameters ParamDown = new PLASHParameters
                {
                    FLT_AD       = 727.8917, //Watershed Area (km2)
                    FLT_AI       = 0.02,     //Impervious Area Fraction (km2/km2)
                    FLT_AP       = 0.95,     //Pervious Area Fraction (km2/km2)
                    FLT_TimeStep = 24,


                    FLT_DI   = values[18], //Maximum Impervious Detention (mm)
                    FLT_IP   = values[19], //Maximum Interception (mm)
                    FLT_DP   = values[20], //Maximum Pervious Detention (mm)
                    FLT_KSup = values[21], //Surface Reservoir Decay (h)
                    FLT_CS   = values[22], //Soil Saturation Capacity (mm)
                    FLT_CC   = values[23], //Field Capacity (%)
                    FLT_CR   = values[24], //Recharge Capacity (%)
                    FLT_PP   = values[25], //Deep Percolation (mm/h)
                    FLT_KSub = values[26], //Aquifer Reservoir Decay (d)
                    FLT_KCan = values[27], //Channel Reservoir Decay (h)
                    FLT_CH   = values[28], //Hydraulic Conductivity (mm/h)
                    FLT_FS   = values[29], //Soil Capilarity Factor (mm)
                    FLT_PS   = values[30], //Soil Porosity (cm3/cm3)
                    FLT_UI   = values[31]  //Initial Moisture (cm3/cm3)
                };

                PLASHInitialConditions Res0Down = new PLASHInitialConditions()
                {
                    RImp0 = values[32],
                    RInt0 = values[33],
                    RSup0 = values[34],
                    RCan0 = values[35]
                };

                PLASHReservoir ReservoirDown = new PLASHReservoir();

                PLASHOutput OutputDown = new PLASHOutput();

                PLASH.Run(InputDown, ParamDown, Res0Down, ReservoirDown, OutputDown);

                if (ReservoirDown.FLT_Arr_ESSup.Sum() < 30 || ReservoirUp.FLT_Arr_ESSup.Sum() < 30)
                {
                    return(double.NegativeInfinity);
                }

                //double objectiveNashSut = 1;

                //double MeanSimulatedFlow = OutputDown.FLT_Arr_Qt_Calc.Average();

                //double NashSutUpper = 0;
                //double NashSutLower = 0;


                //for(int i = 0; i < OutputDown.FLT_Arr_Qt_Calc.Length; i++)
                //{
                //    NashSutUpper += Math.Pow(OutputDown.FLT_Arr_Qt_Calc[i] - InputDown.FLT_Arr_QtObsSeries[i], 2);
                //    NashSutLower += Math.Pow(InputDown.FLT_Arr_QtObsSeries[i] - MeanSimulatedFlow, 2);
                //}

                //objectiveNashSut -= (NashSutUpper / NashSutLower);

                double objectiveSquareSum = 0;
                for (int i = 0; i < OutputDown.FLT_Arr_Qt_Calc.Length; i++)
                {
                    objectiveSquareSum += Math.Pow(OutputDown.FLT_Arr_Qt_Calc[i] - InputDown.FLT_Arr_QtObsSeries[i], 2);
                }

                //double objectiveAbsSum = 0;
                //for(int i = 0; i < OutputDown.FLT_Arr_Qt_Calc.Length; i++)
                //{
                //    objectiveAbsSum +=  Math.Abs(OutputDown.FLT_Arr_Qt_Calc[i] - InputDown.FLT_Arr_QtObsSeries[i]);
                //}

                //return objectiveAbsSum * -1;

                return(objectiveSquareSum * -1);

                //return objectiveNashSut;
            });

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.3f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(250);

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

            ga.Termination = termination;

            //Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");
            Console.WriteLine("Genetic algorithm tests");
            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.ToFloatingPoints();

                    Console.WriteLine("Generation {0}: {1}",

                                      ga.GenerationsNumber,
                                      bestFitness);

                    //Console.WriteLine(
                    //    "Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                    //    ga.GenerationsNumber,
                    //    phenotype[0],
                    //    phenotype[1],
                    //    phenotype[2],
                    //    phenotype[3],
                    //    bestFitness
                    //);
                }
            };

            ga.Start();

            Console.WriteLine("GA Over!");

            #endregion Genetic Algorithm
            var bestChrom = ga.BestChromosome as FloatingPointChromosome;
            var bestVal   = bestChrom.ToFloatingPoints();


            PLASHInput InputUpstream = new PLASHInput()
            {
                DTE_Arr_TimeSeries   = new DateTime[SimulationLength],
                FLT_Arr_PrecipSeries = InputPrecipUp.ToArray(),
                FLT_Arr_EPSeries     = InputEvap.ToArray(),
                FLT_Arr_QtObsSeries  = InputQObs.ToArray(),
                FLT_Arr_QtUpstream   = new double[SimulationLength]
            };

            PLASHParameters ParametersUpstream = new PLASHParameters()
            {
                FLT_AD       = 861.42252, //Watershed Area (km2)
                FLT_AI       = 0.02,      //Impervious Area Fraction (km2/km2)
                FLT_AP       = 0.95,      //Pervious Area Fraction (km2/km2)
                FLT_TimeStep = 24,

                //Parameters
                FLT_DI   = bestVal[0],      //Maximum Impervious Detention (mm)
                FLT_IP   = bestVal[1],      //Maximum Interception (mm)
                FLT_DP   = bestVal[2],      //Maximum Pervious Detention (mm)
                FLT_KSup = bestVal[3],      //Surface Reservoir Decay (h)
                FLT_CS   = bestVal[4],      //Soil Saturation Capacity (mm)
                FLT_CC   = bestVal[5],      //Field Capacity (%)
                FLT_CR   = bestVal[6],      //Recharge Capacity (%)
                FLT_PP   = bestVal[7],      //Deep Percolation (mm/h)
                FLT_KSub = bestVal[8],      //Aquifer Reservoir Decay (d)
                FLT_KCan = bestVal[9],      //Channel Reservoir Decay (h)
                FLT_CH   = bestVal[10],     //Hydraulic Conductivity (mm/h)
                FLT_FS   = bestVal[11],     //Soil Capilarity Factor (mm)
                FLT_PS   = bestVal[12],     //Soil Porosity (cm3/cm3)
                FLT_UI   = bestVal[13]      //Initial Moisture (cm3/cm3)
            };

            InputUpstream.DTE_Arr_TimeSeries[0] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            for (int i = 1; i < InputUpstream.DTE_Arr_TimeSeries.Length; i++)
            {
                InputUpstream.DTE_Arr_TimeSeries[i] = InputUpstream.DTE_Arr_TimeSeries[0].AddHours(ParametersUpstream.FLT_TimeStep * i);
            }

            PLASHReservoir ReservoirUpstream = new PLASHReservoir();

            PLASHInitialConditions InitialUpstream = new PLASHInitialConditions()
            {
                RImp0 = bestVal[14],
                RInt0 = bestVal[15],
                RSup0 = bestVal[16],
                RCan0 = bestVal[17]
            };

            PLASHOutput OutputUpstream = new PLASHOutput();

            PLASH.Run(InputUpstream, ParametersUpstream, InitialUpstream, ReservoirUpstream, OutputUpstream);


            PLASHInput InputDownstream = new PLASHInput()
            {
                DTE_Arr_TimeSeries   = new DateTime[SimulationLength],
                FLT_Arr_PrecipSeries = InputPrecipDown.ToArray(),
                FLT_Arr_EPSeries     = InputEvap.ToArray(),
                FLT_Arr_QtObsSeries  = InputQObs.ToArray()
            };

            PLASHParameters ParametersDownstream = new PLASHParameters()
            {
                FLT_AD       = 727.8917, //Watershed Area (km2)
                FLT_AI       = 0.02,     //Impervious Area Fraction (km2/km2)
                FLT_AP       = 0.95,     //Pervious Area Fraction (km2/km2)
                FLT_TimeStep = 24,

                //Parameters
                FLT_DI   = bestVal[18],      //Maximum Impervious Detention (mm)
                FLT_IP   = bestVal[19],      //Maximum Interception (mm)
                FLT_DP   = bestVal[20],      //Maximum Pervious Detention (mm)
                FLT_KSup = bestVal[21],      //Surface Reservoir Decay (h)
                FLT_CS   = bestVal[22],      //Soil Saturation Capacity (mm)
                FLT_CC   = bestVal[23],      //Field Capacity (%)
                FLT_CR   = bestVal[24],      //Recharge Capacity (%)
                FLT_PP   = bestVal[25],      //Deep Percolation (mm/h)
                FLT_KSub = bestVal[26],      //Aquifer Reservoir Decay (d)
                FLT_KCan = bestVal[27],      //Channel Reservoir Decay (h)
                FLT_CH   = bestVal[28],      //Hydraulic Conductivity (mm/h)
                FLT_FS   = bestVal[29],      //Soil Capilarity Factor (mm)
                FLT_PS   = bestVal[30],      //Soil Porosity (cm3/cm3)
                FLT_UI   = bestVal[31]       //Initial Moisture (cm3/cm3)
            };


            InputDownstream.DTE_Arr_TimeSeries[0] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            for (int i = 1; i < InputDownstream.DTE_Arr_TimeSeries.Length; i++)
            {
                InputDownstream.DTE_Arr_TimeSeries[i] = InputDownstream.DTE_Arr_TimeSeries[0].AddHours(ParametersDownstream.FLT_TimeStep * i);
            }

            PLASHReservoir ReservoirDownstream = new PLASHReservoir();

            PLASHInitialConditions InitialDownstream = new PLASHInitialConditions()
            {
                RImp0 = bestVal[32],
                RInt0 = bestVal[33],
                RSup0 = bestVal[34],
                RCan0 = bestVal[35]
            };

            PLASHOutput OutputDownstream = new PLASHOutput();

            Muskingum DampenedUpstream = new Muskingum()
            {
                FLT_K             = bestVal[36],
                FLT_X             = bestVal[37],
                FLT_Timestep      = 24,
                FLT_Arr_InputFlow = OutputUpstream.FLT_Arr_Qt_Calc
            };

            DampenedUpstream.FLT_Arr_OutputFlow = Muskingum.ProcessDamping(DampenedUpstream);

            InputDownstream.FLT_Arr_QtUpstream = DampenedUpstream.FLT_Arr_OutputFlow;

            PLASH.Run(InputDownstream, ParametersDownstream, InitialDownstream, ReservoirDownstream, OutputDownstream);


            Console.ReadKey();



            //Console.WriteLine("");
            //Console.ReadKey();

            #endregion PLASH Simulation

            #region Buwo Simulation

            List <Buildup_Washoff> UsesUpstream   = Buildup_Washoff.BuwoUpstreamList(Timestep, ReservoirUpstream.FLT_Arr_ESSup);
            List <Buildup_Washoff> UsesDownstream = Buildup_Washoff.BuwoDownstreamList(Timestep, ReservoirDownstream.FLT_Arr_ESSup);

            foreach (Buildup_Washoff Use in UsesUpstream)
            {
                Buildup_Washoff.fncBuildupWashoffProcess(Use);
            }

            Buildup_Washoff BuwoUpstream = Buildup_Washoff.AggregateUses(UsesUpstream, 863.178D);

            foreach (Buildup_Washoff Use in UsesDownstream)
            {
                Buildup_Washoff.fncBuildupWashoffProcess(Use);
            }

            Buildup_Washoff BuwoDownstream = Buildup_Washoff.AggregateUses(UsesDownstream, 729.018D);



            Buildup_Washoff Aggregate = Buildup_Washoff.Transport(BuwoUpstream, BuwoDownstream);


            #endregion Buwo Simulation



            //#region Excel Output
            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add("Param_PLASHUp");
                excel.Workbook.Worksheets.Add("Param_PLASHDown");
                excel.Workbook.Worksheets.Add("PLASHReservoirUp");
                excel.Workbook.Worksheets.Add("PLASHReservoirDown");
                excel.Workbook.Worksheets.Add("PLASHInitialUp");
                excel.Workbook.Worksheets.Add("PLASHInitialDown");
                excel.Workbook.Worksheets.Add("Results_PLASHUp");
                excel.Workbook.Worksheets.Add("Results_PLASHDown");
                excel.Workbook.Worksheets.Add("Param_Muskingum");
                excel.Workbook.Worksheets.Add("Results_Muskingum");
                excel.Workbook.Worksheets.Add("Results_BuWo");

                #region Parameters

                var HeaderRowPLASHParam = new List <string[]>()
                {
                    new string[]
                    {
                        "DI", "IP", "DP", "KSup", "CS", "CC", "CR", "PP", "Ksub", "KCan", "CH", "FS", "PS", "UI"
                    }
                };

                string headerRangePLASHParam = "A1:" + Char.ConvertFromUtf32(HeaderRowPLASHParam[0].Length + 64) + 1;

                var worksheet = excel.Workbook.Worksheets["Param_PLASHUp"];

                worksheet.Cells[headerRangePLASHParam].LoadFromArrays(HeaderRowPLASHParam);

                List <object[]> cellDataPLASHParamUP = new List <object[]>();

                cellDataPLASHParamUP.Add(new object[]
                {
                    ParametersUpstream.FLT_DI, ParametersUpstream.FLT_IP, ParametersUpstream.FLT_DP, ParametersUpstream.FLT_KSup, ParametersUpstream.FLT_CS,
                    ParametersUpstream.FLT_CC, ParametersUpstream.FLT_CR, ParametersUpstream.FLT_PP, ParametersUpstream.FLT_KSub, ParametersUpstream.FLT_KCan,
                    ParametersUpstream.FLT_CH, ParametersUpstream.FLT_FS, ParametersUpstream.FLT_PS, ParametersUpstream.FLT_UI
                });

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHParamUP);

                worksheet = excel.Workbook.Worksheets["Param_PLASHDown"];

                worksheet.Cells[headerRangePLASHParam].LoadFromArrays(HeaderRowPLASHParam);

                List <object[]> cellDataPLASHParamDown = new List <object[]>();

                cellDataPLASHParamDown.Add(new object[]
                {
                    ParametersDownstream.FLT_DI, ParametersDownstream.FLT_IP, ParametersDownstream.FLT_DP, ParametersDownstream.FLT_KSup, ParametersDownstream.FLT_CS,
                    ParametersDownstream.FLT_CC, ParametersDownstream.FLT_CR, ParametersDownstream.FLT_PP, ParametersDownstream.FLT_KSub, ParametersDownstream.FLT_KCan,
                    ParametersDownstream.FLT_CH, ParametersDownstream.FLT_FS, ParametersDownstream.FLT_PS, ParametersDownstream.FLT_UI
                });

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHParamDown);

                #endregion Parameters

                #region Reservoir
                var HeaderRowPLASHreservoir = new List <string[]>()
                {
                    new string[]
                    {
                        "ImpRes", "ImpEvap", "ImpFlow",
                        "IntRes", "IntEvap", "IntFlow",
                        "SurfRes", "SurfEvap", "SurfFlow",
                        "Inf", "InfCum", "IAE", "TP", "IAEAdim", "TPAdim",
                        "SoilRes", "SoilEvap", "SoilUpFlow", "SoilDownFlow",
                        "AquiRes", "AquiPerc", "AquiFlow",
                        "ChanRes", "ChanEvap", "ChanUpFlow", "ChanDownFlow"
                    }
                };

                string HeaderRangePLASHReservoir = "A1:" + Char.ConvertFromUtf32(HeaderRowPLASHreservoir[0].Length + 64) + 1;

                worksheet = excel.Workbook.Worksheets["PLASHReservoirUp"];

                worksheet.Cells[HeaderRangePLASHReservoir].LoadFromArrays(HeaderRowPLASHreservoir);

                List <object[]> cellDataPLASHResUp = new List <object[]>();

                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataPLASHResUp.Add(new object[]
                    {
                        ReservoirUpstream.FLT_Arr_RImp[i], ReservoirUpstream.FLT_Arr_ERImp[i], ReservoirUpstream.FLT_Arr_ESImp[i],
                        ReservoirUpstream.FLT_Arr_RInt[i], ReservoirUpstream.FLT_Arr_ERInt[i], ReservoirUpstream.FLT_Arr_ESInt[i],
                        ReservoirUpstream.FLT_Arr_RSup[i], ReservoirUpstream.FLT_Arr_ERSup[i], ReservoirUpstream.FLT_Arr_ESSup[i],
                        ReservoirUpstream.FLT_Arr_Infiltration[i], ReservoirUpstream.FLT_Arr_Infiltration_Cumulative[i], ReservoirUpstream.FLT_Arr_IAE[i], ReservoirUpstream.FLT_Arr_TP[i], ReservoirUpstream.FLT_Arr_IAEAdim[i], ReservoirUpstream.FLT_Arr_TPAdim[i],
                        ReservoirUpstream.FLT_Arr_RSol[i], ReservoirUpstream.FLT_Arr_ERSol[i], ReservoirUpstream.FLT_Arr_EESol[i], ReservoirUpstream.FLT_Arr_ESSol[i],
                        ReservoirUpstream.FLT_Arr_RSub[i], ReservoirUpstream.FLT_Arr_PPSub[i], ReservoirUpstream.FLT_Arr_EESub[i],
                        ReservoirUpstream.FLT_Arr_RCan[i], ReservoirUpstream.FLT_Arr_ERCan[i], ReservoirUpstream.FLT_Arr_EECan[i], ReservoirUpstream.FLT_ARR_ESCan[i]
                    });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHResUp);


                worksheet = excel.Workbook.Worksheets["PLASHReservoirDown"];

                worksheet.Cells[HeaderRangePLASHReservoir].LoadFromArrays(HeaderRowPLASHreservoir);

                List <object[]> cellDataPLASHResDown = new List <object[]>();

                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataPLASHResDown.Add(new object[]
                    {
                        ReservoirDownstream.FLT_Arr_RImp[i], ReservoirDownstream.FLT_Arr_ERImp[i], ReservoirDownstream.FLT_Arr_ESImp[i],
                        ReservoirDownstream.FLT_Arr_RInt[i], ReservoirDownstream.FLT_Arr_ERInt[i], ReservoirDownstream.FLT_Arr_ESInt[i],
                        ReservoirDownstream.FLT_Arr_RSup[i], ReservoirDownstream.FLT_Arr_ERSup[i], ReservoirDownstream.FLT_Arr_ESSup[i],
                        ReservoirDownstream.FLT_Arr_Infiltration[i], ReservoirDownstream.FLT_Arr_Infiltration_Cumulative[i], ReservoirDownstream.FLT_Arr_IAE[i], ReservoirDownstream.FLT_Arr_TP[i], ReservoirDownstream.FLT_Arr_IAEAdim[i], ReservoirDownstream.FLT_Arr_TPAdim[i],
                        ReservoirDownstream.FLT_Arr_RSol[i], ReservoirDownstream.FLT_Arr_ERSol[i], ReservoirDownstream.FLT_Arr_EESol[i], ReservoirDownstream.FLT_Arr_ESSol[i],
                        ReservoirDownstream.FLT_Arr_RSub[i], ReservoirDownstream.FLT_Arr_PPSub[i], ReservoirDownstream.FLT_Arr_EESub[i],
                        ReservoirDownstream.FLT_Arr_RCan[i], ReservoirDownstream.FLT_Arr_ERCan[i], ReservoirDownstream.FLT_Arr_EECan[i], ReservoirDownstream.FLT_ARR_ESCan[i]
                    });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHResDown);

                #endregion Reservoir

                #region Initial Conditions
                var HeaderRowPLASHInitial = new List <string[]>()
                {
                    new string[] { "RImp0", "RInt0", "RSup0", "RCan0" }
                };

                string headerRangePLASHInitial = "A1:" + Char.ConvertFromUtf32(HeaderRowPLASHInitial[0].Length + 64) + 1;

                worksheet = excel.Workbook.Worksheets["PLASHInitialUp"];

                worksheet.Cells[headerRangePLASHInitial].LoadFromArrays(HeaderRowPLASHInitial);

                List <object[]> cellDataPLASHInitialUp = new List <object[]>();

                cellDataPLASHInitialUp.Add(new object[] { InitialUpstream.RImp0, InitialUpstream.RInt0, InitialUpstream.RSup0, InitialUpstream.RCan0 });

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHInitialUp);


                worksheet = excel.Workbook.Worksheets["PLASHInitialDown"];

                worksheet.Cells[headerRangePLASHInitial].LoadFromArrays(HeaderRowPLASHInitial);

                List <object[]> cellDataPLASHInitialDown = new List <object[]>();

                cellDataPLASHInitialDown.Add(new object[] { InitialDownstream.RImp0, InitialDownstream.RInt0, InitialDownstream.RSup0, InitialDownstream.RCan0 });

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHInitialDown);

                #endregion Initial Conditions

                #region Results

                //PLASH Upstream
                var HeaderRowPLASH = new List <string[]>()
                {
                    new string[] { "Precipitation", "Evapotranspiration", "Observed Flow",
                                   "Impervious Reservoir", "Interception Reservoir", "Surface Reservoir", "Soil Reservoir", "Aquifer Reservoir", "Channel Reservoir",
                                   "Calculated Basic Flow", "Calculated Surface Flow", "Calculated Total Flow" },
                };

                string headerRangePLASH = "A1:" + Char.ConvertFromUtf32(HeaderRowPLASH[0].Length + 64) + 1;

                worksheet = excel.Workbook.Worksheets["Results_PLASHUp"];

                worksheet.Cells[headerRangePLASH].LoadFromArrays(HeaderRowPLASH);

                List <object[]> cellDataPLASHUp = new List <object[]>();

                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataPLASHUp.Add(new object[] { InputUpstream.FLT_Arr_PrecipSeries[i], InputUpstream.FLT_Arr_EPSeries[i], InputUpstream.FLT_Arr_QtObsSeries[i],
                                                       ReservoirUpstream.FLT_Arr_RImp[i], ReservoirUpstream.FLT_Arr_RInt[i], ReservoirUpstream.FLT_Arr_RSup[i], ReservoirUpstream.FLT_Arr_RSol[i], ReservoirUpstream.FLT_Arr_RSub[i], ReservoirUpstream.FLT_Arr_RCan[i],
                                                       OutputUpstream.FLT_Arr_QBas_Calc[i], OutputUpstream.FLT_Arr_QSup_Calc[i], OutputUpstream.FLT_Arr_Qt_Calc[i] });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHUp);

                //PLASH Downstream

                worksheet = excel.Workbook.Worksheets["Results_PLASHDown"];

                worksheet.Cells[headerRangePLASH].LoadFromArrays(HeaderRowPLASH);

                List <object[]> cellDataPLASHDown = new List <object[]>();


                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataPLASHDown.Add(new object[] { InputDownstream.FLT_Arr_PrecipSeries[i], InputDownstream.FLT_Arr_EPSeries[i], InputDownstream.FLT_Arr_QtObsSeries[i],
                                                         ReservoirDownstream.FLT_Arr_RImp[i], ReservoirDownstream.FLT_Arr_RInt[i], ReservoirDownstream.FLT_Arr_RSup[i], ReservoirDownstream.FLT_Arr_RSol[i], ReservoirDownstream.FLT_Arr_RSub[i], ReservoirDownstream.FLT_Arr_RCan[i],
                                                         OutputDownstream.FLT_Arr_QBas_Calc[i], OutputDownstream.FLT_Arr_QSup_Calc[i], OutputDownstream.FLT_Arr_Qt_Calc[i] });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataPLASHDown);

                #endregion Results


                #region Muskingum Parameters
                //Muskingum

                var HeaderRowMuskingumParam = new List <string[]>()
                {
                    new string[] { "K", "X" },
                };

                string headerRangeMuskingumParam = "A1:" + Char.ConvertFromUtf32(HeaderRowMuskingumParam[0].Length + 64) + 1;


                worksheet = excel.Workbook.Worksheets["Param_Muskingum"];

                worksheet.Cells[headerRangeMuskingumParam].LoadFromArrays(HeaderRowMuskingumParam);

                List <object[]> cellDataMuskingumParam = new List <object[]>();

                cellDataMuskingumParam.Add(new object[] { DampenedUpstream.FLT_K, DampenedUpstream.FLT_X });


                worksheet.Cells[2, 1].LoadFromArrays(cellDataMuskingumParam);

                #endregion Muskingum Parameters

                #region Muskingum
                var HeaderRowMuskingum = new List <string[]>()
                {
                    new string[] { "Upstream Flow", "Downstream Flow" },
                };

                string headerRangeMuskingum = "A1:" + Char.ConvertFromUtf32(HeaderRowMuskingum[0].Length + 64) + 1;


                worksheet = excel.Workbook.Worksheets["Results_Muskingum"];

                worksheet.Cells[headerRangeMuskingum].LoadFromArrays(HeaderRowMuskingum);

                List <object[]> cellDataMuskingum = new List <object[]>();


                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataMuskingum.Add(new object[] { DampenedUpstream.FLT_Arr_InputFlow[i], DampenedUpstream.FLT_Arr_OutputFlow[i] });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataMuskingum);

                #endregion Muskingum

                #region BuWo
                //Buwo

                var HeaderRow2 = new List <string[]>()
                {
                    new string[] { "Precipitation", "Surface Flow", "Buildup", "Effective Washoff" },
                };

                string headerRange2 = "A1:" + Char.ConvertFromUtf32(HeaderRow2[0].Length + 64) + 1;

                worksheet = excel.Workbook.Worksheets["Results_BuWo"];

                worksheet.Cells[headerRange2].LoadFromArrays(HeaderRow2);

                List <object[]> cellDataBuwo = new List <object[]>();

                for (int i = 0; i < SimulationLength; i++)
                {
                    cellDataBuwo.Add(new object[] { InputUpstream.FLT_Arr_PrecipSeries[i], ReservoirDownstream.FLT_Arr_ESSup[i], Aggregate.FLT_Arr_Buildup[i], Aggregate.FLT_Arr_EffectiveWashoff[i] });
                }

                worksheet.Cells[2, 1].LoadFromArrays(cellDataBuwo);

                #endregion BuWo

                FileInfo excelFile = new FileInfo(@"D:\dataGA.xlsx");
                excel.SaveAs(excelFile);
            }

            ////Console.WriteLine("Excel processed");

            //#endregion Excel Output

            //Console.ReadKey();
        }
Example #32
0
 protected override IList <GeneticEntity> GetEliteGeneticEntitiesCore(Population population)
 {
     GetEliteGeneticEntitiesCoreCalled = true;
     return(base.GetEliteGeneticEntitiesCore(null));
 }
 private void AssignID(Population pop)
 {
     pop.setID(openID.Pop());
     pops.Add(pop);
 }
 public static bool Terminate(Population population, int currentGeneration, long currentEvaluation)
 {
     return(currentGeneration > 200);
 }
Example #35
0
        public static void Box(Settings settings, Population pop, Random rand, double popLeft, double popWidth, Color color, Position position, BoxFormat boxFormat, HorizontalAlignment errorAlignment = HorizontalAlignment.Right)
        {
            // adjust edges to accomodate special positions
            if (position == Position.Hide)
            {
                return;
            }
            if (position == Position.Left || position == Position.Right)
            {
                popWidth /= 2;
            }
            if (position == Position.Right)
            {
                popLeft += popWidth;
            }

            double errorMaxPx, errorMinPx;
            double yPxTop, yPxBase;
            double yPx;

            if (boxFormat == BoxFormat.StdevStderrMean)
            {
                errorMaxPx = settings.GetPixelY(pop.mean + pop.stDev);
                errorMinPx = settings.GetPixelY(pop.mean - pop.stDev);
                yPxTop     = settings.GetPixelY(pop.mean + pop.stdErr);
                yPxBase    = settings.GetPixelY(pop.mean - pop.stdErr);
                yPx        = settings.GetPixelY(pop.mean);
            }
            else if (boxFormat == BoxFormat.OutlierQuartileMedian)
            {
                errorMaxPx = settings.GetPixelY(pop.maxNonOutlier);
                errorMinPx = settings.GetPixelY(pop.minNonOutlier);
                yPxTop     = settings.GetPixelY(pop.Q3);
                yPxBase    = settings.GetPixelY(pop.Q1);
                yPx        = settings.GetPixelY(pop.median);
            }
            else
            {
                throw new NotImplementedException();
            }

            // make cap width a fraction of available space
            double capWidthFrac = .38;
            double capWidth     = popWidth * capWidthFrac;

            // contract edges slightly to encourage padding between elements
            double edgePaddingFrac = 0.2;

            popLeft  += popWidth * edgePaddingFrac;
            popWidth -= (popWidth * edgePaddingFrac) * 2;
            double leftPx  = settings.GetPixelX(popLeft);
            double rightPx = settings.GetPixelX(popLeft + popWidth);

            Pen   pen   = new Pen(Color.Black, 1);
            Brush brush = new SolidBrush(color);

            // draw the box
            RectangleF rect = new RectangleF((float)leftPx, (float)yPxTop, (float)(rightPx - leftPx), (float)(yPxBase - yPxTop));

            settings.gfxData.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
            settings.gfxData.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);

            // draw the line in the center
            settings.gfxData.DrawLine(pen, rect.X, (float)yPx, rect.X + rect.Width, (float)yPx);

            // determine location of errorbars and caps
            double capPx1, capPx2, errorPxX;

            switch (errorAlignment)
            {
            case HorizontalAlignment.Center:
                double centerX = popLeft + popWidth / 2;
                errorPxX = settings.GetPixelX(centerX);
                capPx1   = settings.GetPixelX(centerX - capWidth / 2);
                capPx2   = settings.GetPixelX(centerX + capWidth / 2);
                break;

            case HorizontalAlignment.Right:
                errorPxX = settings.GetPixelX(popLeft + popWidth);
                capPx1   = settings.GetPixelX(popLeft + popWidth - capWidth / 2);
                capPx2   = settings.GetPixelX(popLeft + popWidth);
                break;

            case HorizontalAlignment.Left:
                errorPxX = settings.GetPixelX(popLeft);
                capPx1   = settings.GetPixelX(popLeft);
                capPx2   = settings.GetPixelX(popLeft + capWidth / 2);
                break;

            default:
                throw new NotImplementedException();
            }

            // draw errorbars and caps
            settings.gfxData.DrawLine(pen, (float)errorPxX, (float)errorMinPx, (float)errorPxX, rect.Y + rect.Height);
            settings.gfxData.DrawLine(pen, (float)errorPxX, (float)errorMaxPx, (float)errorPxX, rect.Y);
            settings.gfxData.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx);
            settings.gfxData.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx);
        }
Example #36
0
 /// <summary>
 /// Selects the chromosomes which will be reinserted.
 /// </summary>
 /// <returns>The chromosomes to be reinserted in next generation..</returns>
 /// <param name="population">The population.</param>
 /// <param name="offspring">The offspring.</param>
 /// <param name="parents">The parents.</param>
 protected override IList <IChromosome> PerformSelectChromosomes(Population population, IList <IChromosome> offspring, IList <IChromosome> parents)
 {
     return(offspring);
 }
Example #37
0
        /// <summary>
        /// Start the solver with an initial population.
        /// </summary>
        /// <param name="initial"></param>
        public Individual <GenomeType, ProblemType, WeightType> Start(Population <GenomeType, ProblemType, WeightType> initial)
        {
            WeightType fitness = default(WeightType);

            Population <GenomeType, ProblemType, WeightType> population = new Population <GenomeType, ProblemType, WeightType>(initial, true);

            OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.SolversSolver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                            "Generating population...");

            // use parallelism to generate population.
#if !WINDOWS_PHONE
            if (_parallel)
            {
                System.Threading.Tasks.Parallel.For(population.Count, _settings.PopulationSize, delegate(int i)
                {
                    // generate new.
                    IGenerationOperation <GenomeType, ProblemType, WeightType> generation_operation = this.CreateGenerationOperation();
                    Individual <GenomeType, ProblemType, WeightType> new_individual =
                        generation_operation.Generate(this);

                    // add to population.
                    lock (population)
                    {
                        population.Add(new_individual);
                    }

                    // report population generation.
                    OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.SolversSolver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                    "Generating population{0}/{1}...", population.Count, _settings.PopulationSize);
                    this.ReportNew(string.Format("Generating population..."), population.Count, _settings.PopulationSize);
                });
            }
#endif

            while (population.Count < _settings.PopulationSize)
            {
                // generate new.
                IGenerationOperation <GenomeType, ProblemType, WeightType> generation_operation = this.CreateGenerationOperation();
                Individual <GenomeType, ProblemType, WeightType>           new_individual       =
                    generation_operation.Generate(this);

                // add to population.
                population.Add(new_individual);

                // report population generation.
                OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.SolversSolver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                "Generating population {0}/{1}...", population.Count, _settings.PopulationSize);
                this.ReportNew(string.Format("Generating population..."), population.Count, _settings.PopulationSize);
            }

            OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.SolversSolver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                            "Done!");

            // sort the initial population.
            population.Sort(this, _fitness_calculator);

            //Tools.Core.Output.OutputTextStreamHost.WriteLine("Average {0}",
            //    _fitness_calculator.AverageFitness(_problem, population));

            int stagnation = 0;

            // start next generation or stop.
            WeightType new_fitness =
                population[0].Fitness;

            // is there improvement?
            if (new_fitness.CompareTo(fitness) > 0)
            { // a new fitness is found!
                // raise a new event here.
                this.RaiseNewFittest(population[0]);


                // set new fitness.
                fitness = new_fitness;
                fittest = population[0];

                // reset the stagnation count.
                stagnation = 0;

                OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                "New Fittest {0}", fittest.ToString());
            }

            // start getting genetic!
            int generation_count = 0;
            while (generation_count < _settings.MaxGeneration &&
                   stagnation < _settings.StagnationCount)
            {
                // check if the solving has been cancelled.
                if (this.Cancelled)
                {
                    this.ReportNew(string.Format("Solver cancelled at generation {0}!", generation_count), 1, 1);
                    return(null);
                }
                if (this.Stopped)
                {
                    this.ReportNew(string.Format("Solver stopped at generation {0}!", generation_count), 1, 1);
                    return(fittest);
                }

                // calculate the next generation.
                population =
                    this.NextGeneration(population);

                // get the population fitness.
                population.Sort(this, _fitness_calculator);
                OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                "{0}->{1}", population[0].Fitness, population[population.Count - 1].Fitness);

                // start next generation or stop.
                new_fitness =
                    population[0].Fitness;

                // is there improvement?
                if (new_fitness.CompareTo(fitness) < 0)
                { // a new fitness is found!
                    // raise a new event here.
                    this.RaiseNewFittest(population[0]);

                    // set new fitness.
                    fitness = new_fitness;
                    fittest = population[0];

                    OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                    "New Fittest {0}-{1} {2}", generation_count, stagnation, fittest.ToString());

                    // reset the stagnation count.
                    stagnation = 0;

                    // report the new fittest.
                    this.ReportNew(string.Format("New Fittest {0}",
                                                 fittest.ToString()), 0, 1);
                }
                else
                {
                    // increase the stagnation count.
                    stagnation++;
                }

                // raise the generation count.
                generation_count++;

                // raise a new generation event.
                this.RaiseNewGeneration(generation_count, stagnation, population);

                // report the new generation.
                this.ReportNew(string.Format("Generation {0}-{1} {2}",
                                             generation_count,
                                             stagnation,
                                             fittest.ToString()), stagnation, _settings.StagnationCount);
                if (stagnation != 0 && stagnation % 1 == 0)
                {
                    OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                                    "Generation {0}-{1} {2}", generation_count, stagnation, fittest.ToString());
                }
            }

            OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                            "Result [{0}]:", fitness, fittest.ToString());

            // report the new generation.
            this.ReportNew(string.Format("Evolution finished @ generation {0}: {1}",
                                         generation_count,
                                         fittest.ToString()), generation_count, _settings.StagnationCount);
            OsmSharp.Logging.Log.TraceEvent("OsmSharp.Math.AI.Genetic.Solvers.Solver<GenomeType, ProblemType, WeightType>", System.Diagnostics.TraceEventType.Information,
                                            "Evolution finished @ generation {0}: {1}", generation_count, fittest.ToString());

            return(fittest);
        }
Example #38
0
 private string BuildSeriesId(Population population, County county)
 {
     return(County_Codes[county.CountyName].ToString());
 }
Example #39
0
 public void ExtractIndividualsFrom(Population population, IndividualExtractionOptions individualExtractionOptions)
 {
     _executionContext.AddToHistory(ExtractIndividualsFromPopulationCommand(population, individualExtractionOptions));
 }
Example #40
0
 public void ExtractIndividualsFrom(Population population, IEnumerable <int> individualIds)
 {
     ExtractIndividualsFrom(population, new IndividualExtractionOptions {
         IndividualIds = individualIds
     });
 }
Example #41
0
 protected override IList <GeneticEntity> GetEliteGeneticEntitiesCore(Population population)
 {
     this.GetElitistGeneticEntitiesCallCount++;
     return(base.GetEliteGeneticEntitiesCore(population));
 }
Example #42
0
 public void SetPopulation(Population population, int requestedChromosomes)
 {
     this.population = population.GetBestChromosomes((int)Math.Ceiling(population.Count() * percentage));
 }
Example #43
0
 private static void OnLifecycleFinishedEvent(Population currentPopulation)
 {
     Console.WriteLine($"Highest fitness: {currentPopulation.MaxFitness}");
 }
Example #44
0
 /// <summary>
 /// This method is will be called once per generation (after the MutationProbability method for that generation), so you can use it to remember old data.
 /// </summary>
 public void AddGeneration(Population population)
 {
     previousConvergence = GetConvergence(population.GetEvaluations());
 }
Example #45
0
{ public bool isDuplicateKey(Population pop)
  {
      return(pop.Name == this.Name && pop != this);
  }
 ///<summary>
 ///Remove a population from the RPM
 ///</summary>
 public void RemovePopulation(Population pop)
 {
     pops.Remove(pop);
     openID.Push(pop.getID()); //free ID
 }
        private Engine wireEngine(MainSettings mainSettings, MainAppData data, RobotKiller killer, RobotBreeder breeder, Population population)
        {
            EngineSettings    engineSettings    = getEngineSettings(mainSettings);
            TimePointExecutor timePointExecutor = wireTimePointExecutor(mainSettings);

            return(EngineFactory.getDefaultEngine(engineSettings, data, timePointExecutor, killer, breeder, population));
        }
Example #48
0
 /// <summary>
 /// Selects the krill with the best fitness function value
 /// </summary>
 public Krill GetBestKrill()
 {
     return(Population.Where(x => x.Fitness == MaximumFitness).First());
 }
Example #49
0
    // Update is called once per frame
    void FixedUpdate()
    {
        var gas       = 1;
        var steer     = 1;
        var moveDist  = gas * Speed * Time.deltaTime;
        var turnAngle = steer * TurnSpeed * Time.deltaTime * gas;

        int i;

        count++;

        //StartCoroutine(MyMethod());
        i = 0;
        int j = 0;

        //pop.incGenes();
        foreach (GameObject x in carList)
        {
            if (x != null)
            {
                Car carCont = x.GetComponent <Car>();
                if (carCont.roadNumber != 0)
                {
                    j = pop.getChromozom()[i].getLastPos();
                    //Hareketleri yaptır.
                    //hareketleri yaptırırken
                    //Debug.Log("Chromosome:"+ i);
                    int temp = j;
                    while (j < pop.getChromozom()[i].getGenes().Count&& j - temp < Global.CHROMOSOME_SIZE)
                    {
                        //Debug.Log("gene:"+ pop.getChromozom()[i].getGenes()[j]);


                        if (pop.getChromozom()[i].getGenes()[j] == 0)
                        {
                            //float step = Speed * Time.deltaTime;
                            //x.transform.position += Vector3.MoveTowards(transform.position, x.transform.position, step);
                            x.transform.Translate(Vector3.forward * moveDist);
                            //Rigidbody rb = x.GetComponent<Rigidbody>();
                            //rb.MovePosition(Vector3.forward * moveDist);
                            // x.transform.position = x.transform.position + Vector3.forward * 1;
                            // x.transform.position += x.transform.forward * Time.deltaTime * 1;
                        }
                        else if (pop.getChromozom()[i].getGenes()[j] == 1)
                        {
                            x.transform.Rotate(new Vector3(0, 2, 0));
                        }
                        else if (pop.getChromozom()[i].getGenes()[j] == 2)
                        {
                            x.transform.Rotate(new Vector3(0, -2, 0));
                        }
                        j++;
                    }

                    if (j == pop.getChromozom()[i].getGenes().Count)
                    {
                        Debug.Log("Increasing...");
                        pop.incGenes();
                    }
                    pop.getChromozom()[i].setLastPos(j);
                    //  if (pop.getChromozom()[i].getFitness() < carCont.roadNumber)
                    pop.getChromozom()[i].setFitness(carCont.roadNumber);
                    //Debug.Log("roadNum:" + pop.getChromozom()[i].getFitness());
                }
            }
            i++;
        }

        int null_count = 0;

        foreach (GameObject x in carList)
        {
            if (x == null)
            {
                null_count++;
            }
        }
        if (null_count == carList.Count)
        {
            carList.Clear();

            for (i = 0; i < Global.POPULATION_SIZE; i++)
            {
                GameObject obj = Instantiate(Car, Car.transform.position, Car.transform.rotation) as GameObject;

                carList.Add(obj);
                pop.getChromozom()[i].setLastPos(0);
            }
            Debug.Log("Evolving...");
            Debug.Log("Genes: " + pop.getChromozom()[0].getGenes().Count);
            pop.getChromozom().Sort((a, b) => a.getFitness().CompareTo(b.getFitness()));//fitnesa göre sort etmeyi ayarla
            pop.getChromozom().Reverse();
            //List<int> once = pop.getChromozom()[3].getGenes().ToList<int>();
            pop = Global.generic.evolve(pop);
            //List<int> sonra = pop.getChromozom()[3].getGenes().ToList<int>();
            //Debug.Log("0 Degisti. : " + isEqual(once,sonra));
            generation_number++;
            Debug.Log("Generation: " + generation_number);
        }


        //carList.Clear();



        //Debug.Log("---- Fitness ----");
        //Debug.Log(pop.getChromozom()[0].getFitness());
        //Debug.Log(pop.getChromozom()[0].getGenes()[0]);
        //Debug.Log(pop.getChromozom()[1].getFitness());
        //Debug.Log(pop.getChromozom()[2].getFitness());
        //Debug.Log(pop.getChromozom()[3].getFitness());
        //Debug.Log(pop.getChromozom()[4].getFitness());
        //Debug.Log(pop.getChromozom()[5].getFitness());
        //Debug.Log(pop.getChromozom()[6].getFitness());
        //Debug.Log(pop.getChromozom()[7].getFitness());
        //Debug.Log(pop.getChromozom()[8].getFitness());
        //Debug.Log(pop.getChromozom()[9].getFitness());
        //Debug.Log(pop.getChromozom()[0].getLastPos());
        //Debug.Log(pop.getChromozom()[1].getLastPos());
        //Debug.Log(pop.getChromozom()[2].getLastPos());
        //Debug.Log(pop.getChromozom()[3].getLastPos());
        //Debug.Log(pop.getChromozom()[4].getLastPos());
    }
Example #50
0
        public static void Main(string[] args)
        {
            string plaintextFilename = "text_sample.txt";
            string logFilename       = "log.txt";
            string key = "cipherkey";

            int   populationSize       = 100;
            int   offspring            = 10;
            float mutationProbability  = 0.25f;
            float crossoverProbability = 0.85f;
            int   maxGenerations       = 500;

            using (StreamWriter w = File.AppendText($"../../../logs/{logFilename}"))
            {
                //read in plaintext
                string plaintext = File.ReadAllText($"../../../statistics/text/{plaintextFilename}").ToLower();

                //init cipher and encipher plaintext
                ICipher cipher = new VigenereCipher(plaintext);
                cipher.Encipher(key);
                Console.WriteLine(cipher.CipherText);

                //init genetic alorithm operators
                //use tournament selection to minimize the likelyhood of staying in a lokal optima
                var selection = new TournamentSelection(5);
                //crossover the solution candidates by choosing a interval of the key and swap the interval
                var crossover = new TwoPointCrossover();
                //mutate the solution candidates with the own implemented mutation operator
                var mutation = new CipherMutation();
                //evaluate the fitness of the solution candidates with the own implemented fitness function
                var fitness = new CipherFitness(cipher);
                //initalize the solution candidates with the own implemented solution candidate implementation
                var chromosome = new CipherChromosome(key.Length);
                //initialize a population
                var population = new Population(populationSize, populationSize + offspring, chromosome);

                //initialize the genetic algorithm with the above initialized operators
                var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

                //set mutation and crossover probabilities
                ga.MutationProbability  = mutationProbability;
                ga.CrossoverProbability = crossoverProbability;

                //specify the algorithm termination with max generations or a fitness threshold
                ga.Termination = new OrTermination(new GenerationNumberTermination(maxGenerations), new FitnessThresholdTermination(0.99));

                var latestFitness = 0.0;

                //hang into the GenerationRan event which gets called by the library after each generation ran.
                ga.GenerationRan += (sender, e) =>
                {
                    //select the best solution candidate in the current generation
                    var bestChromosome = ga.BestChromosome as CipherChromosome;
                    //if fitness in current generation is better than fitness in previous generations
                    if (bestChromosome.Fitness != latestFitness)
                    {
                        latestFitness = bestChromosome.Fitness.Value;
                        string genText = String.Format("Generation {0}: Best solution found is Key:{1} with {2} fitness.", ga.GenerationsNumber, bestChromosome.ToString(), bestChromosome.Fitness);
                        Console.WriteLine(genText);
                        w.WriteLine(genText);
                    }
                };
                string gaText = $"------Plaintextfile:{plaintextFilename}, Key:{key}------\n------Genetic Algorithm Settings: Populationsize:{populationSize}, Mutation:{mutationProbability}, Crossover:{crossoverProbability}------";
                Console.WriteLine(gaText);
                w.WriteLine(gaText);

                //start ga
                ga.Start();

                var    finalSolution = ga.BestChromosome as CipherChromosome;
                string doneText      = $"GA done in {ga.GenerationsNumber} generations.\n Best solution found is Key:{finalSolution.ToString()} (L={finalSolution.ToString().Length}) with {finalSolution.Fitness} fitness. ";

                string decipheredText = cipher.Decipher(finalSolution.ToString());
                Console.WriteLine(doneText + "\n" + decipheredText);
                w.WriteLine(doneText + "\n" + decipheredText);
            }
        }
Example #51
0
 public Population evolve(Population pop)
 {
     pop = mutate_population(crossover_population(pop));
     //pop.getChromozom()[3].getGenes().Add(1);
     return(pop);
 }
Example #52
0
    public void NewGeneration()
    {
        if (Population.Count <= 0)
        {
            return;
        }

        CalculateFitness();

        List <DNA <T> > newPopulation = new List <DNA <T> >();

        Population.Sort
        (
            (DNA <T> a, DNA <T> b) =>
        {
            return(a.Fitness > b.Fitness ? -1 : 1);
        }
        );
        if (Generation != 1)
        {
            string test          = tests[method];
            string baseDirUni    = "M:\\aiproject\\";
            string baseDirLaptop = "C:\\Users\\Sirius\\Desktop\\aiproject\\";
            string baseDir       = baseDirUni;
            string printString;
            string fitnessString;
            string thrustString;
            string judgementString;
            string fuelString;

            {
                fitnessString   = ((float)((int)(Population[0].Fitness * 100)) / 100).ToString();
                thrustString    = ((float)((int)(Population[0].Genes[0] * 100)) / 100).ToString();
                judgementString = ((float)((int)(Population[0].Genes[1] * 100)) / 100).ToString();
                fuelString      = ((float)((int)(Population[0].Genes[2] * 100)) / 100).ToString();

                printString  = ("Worst:  Fitness=" + fitnessString);
                printString += ("    Peak Thrust=" + thrustString);
                printString += ("   Judgement Height=" + judgementString);
                printString += ("  Starting Fuel=" + fuelString);
                UnityEngine.Debug.Log(printString);
                WriteToFile(fitnessString, thrustString, judgementString, fuelString, baseDir + test + "\\worst.csv");
            }

            {
                float medianFitness = (Population[(Population.Count / 2) - 1].Fitness + Population[(Population.Count / 2) - 0].Fitness) / 2;
                float medianGene0   = (Population[(Population.Count / 2) - 1].Genes[0] + Population[(Population.Count / 2) - 0].Genes[0]) / 2;
                float medianGene1   = (Population[(Population.Count / 2) - 1].Genes[1] + Population[(Population.Count / 2) - 0].Genes[1]) / 2;
                float medianGene2   = (Population[(Population.Count / 2) - 1].Genes[2] + Population[(Population.Count / 2) - 0].Genes[2]) / 2;
                fitnessString   = ((float)((int)(medianFitness * 100)) / 100).ToString();
                thrustString    = ((float)((int)(medianGene0 * 100)) / 100).ToString();
                judgementString = ((float)((int)(medianGene1 * 100)) / 100).ToString();
                fuelString      = ((float)((int)(medianGene2 * 100)) / 100).ToString();

                printString  = ("Median:  Fitness=" + fitnessString);
                printString += ("    Peak Thrust=" + thrustString);
                printString += ("   Judgement Height=" + judgementString);
                printString += ("  Starting Fuel=" + fuelString);
                UnityEngine.Debug.Log(printString);
                WriteToFile(fitnessString, thrustString, judgementString, fuelString, baseDir + test + "\\median.csv");
            }

            {
                fitnessString   = ((float)((int)(Population[Population.Count - 2].Fitness * 100)) / 100).ToString();
                thrustString    = ((float)((int)(Population[Population.Count - 2].Genes[0] * 100)) / 100).ToString();
                judgementString = ((float)((int)(Population[Population.Count - 2].Genes[1] * 100)) / 100).ToString();
                fuelString      = ((float)((int)(Population[Population.Count - 2].Genes[2] * 100)) / 100).ToString();

                printString  = ("Second:  Fitness=" + fitnessString);
                printString += ("    Peak Thrust=" + thrustString);
                printString += ("   Judgement Height=" + judgementString);
                printString += ("  Starting Fuel=" + fuelString);
                UnityEngine.Debug.Log(printString);
                WriteToFile(fitnessString, thrustString, judgementString, fuelString, baseDir + test + "\\second.csv");
            }

            {
                fitnessString   = ((float)((int)(Population[Population.Count - 1].Fitness * 100)) / 100).ToString();
                thrustString    = ((float)((int)(Population[Population.Count - 1].Genes[0] * 100)) / 100).ToString();
                judgementString = ((float)((int)(Population[Population.Count - 1].Genes[1] * 100)) / 100).ToString();
                fuelString      = ((float)((int)(Population[Population.Count - 1].Genes[2] * 100)) / 100).ToString();

                printString  = ("First:  Fitness=" + fitnessString);
                printString += ("    Peak Thrust=" + thrustString);
                printString += ("   Judgement Height=" + judgementString);
                printString += ("  Starting Fuel=" + fuelString);
                UnityEngine.Debug.Log(printString);
                WriteToFile(fitnessString, thrustString, judgementString, fuelString, baseDir + test + "\\first.csv");
            }
        }
        for (int i = 0; i < Population.Count; i++)
        {
            //string printString;
            //printString = ("Fitness=" + ((float)((int)(Population[i].Fitness * 100)) / 100).ToString());
            //printString += ("    Peak Thrust=" + ((float)((int)(Population[i].Genes[0] * 100)) / 100).ToString());
            //printString += ("   Judgement Height=" + ((float)((int)(Population[i].Genes[1] * 100)) / 100));
            //printString += ("  Starting Fuel=" + ((float)((int)(Population[i].Genes[2] * 100)) / 100));
            //UnityEngine.Debug.Log(printString);
            //DNA<T> parent1 = ChooseParent();
            //DNA<T> parent2 = ChooseParent();

            DNA <T> parent1;
            DNA <T> parent2;
            if (method == METHOD.TWOBEST)
            {
                parent1 = Population[Population.Count - 1];
                parent2 = Population[Population.Count - 2];
            }
            else if (method == METHOD.ABOVEMEDIANONLY)
            {
                //int index = Population.Count - 1;
                //index -= i / 2;
                //parent1 = Population[index];
                parent1 = ChooseParent(method);
                parent2 = ChooseParent(method);
            }
            else if (method == METHOD.ROULETTEWHEEL)
            {
                parent1 = ChooseParent(method);
                parent2 = ChooseParent(method);
            }
            else if (method == METHOD.ABOVEMEDIANSANDBEST)
            {
                parent1 = Population[Population.Count - 1];
                parent2 = ChooseParent(method);
            }
            else
            {
                parent1 = Population[Population.Count - 1];
                parent2 = Population[Population.Count - 2];
            }

            DNA <T> child = parent1.Crossover(parent2);

            child.Mutate(MutationRate, MutationVariance);

            newPopulation.Add(child);
        }

        Population = newPopulation;

        Generation++;
    }
Example #53
0
        public PieChartViewModel()
        {
            this.Expenditure = new List <CompanyExpense>();
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Seeds", Amount = 7658d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Fertilizers", Amount = 7090d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Insurance", Amount = 3577d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Labor", Amount = 1473d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Warehousing", Amount = 820d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Taxes", Amount = 571d
            });
            Expenditure.Add(new CompanyExpense()
            {
                Expense = "Truck", Amount = 462d
            });

            CompanyDetails = new List <CompanyDetail>();
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Rolls Royce", CompanyTurnover = 750000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Benz", CompanyTurnover = 500000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Audi", CompanyTurnover = 450000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "BMW", CompanyTurnover = 700000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Mahindra", CompanyTurnover = 350000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Jaguar", CompanyTurnover = 650000
            });
            CompanyDetails.Add(new CompanyDetail()
            {
                CompanyName = "Hero Honda", CompanyTurnover = 250000
            });

            Metric = new List <Metrics>();
            Metric.Add(new Metrics()
            {
                ResponseTime = 43, Utilization = 32
            });
            Metric.Add(new Metrics()
            {
                ResponseTime = 20, Utilization = 34
            });
            Metric.Add(new Metrics()
            {
                ResponseTime = 67, Utilization = 41
            });
            Metric.Add(new Metrics()
            {
                ResponseTime = 52, Utilization = 42
            });
            Metric.Add(new Metrics()
            {
                ResponseTime = 71, Utilization = 48
            });
            Metric.Add(new Metrics()
            {
                ResponseTime = 30, Utilization = 45
            });

            this.Population = new List <Populations>();
            Population.Add(new Populations()
            {
                Continent = "Asia", Countries = "China", States = "Taiwan", PopulationinContinents = 50.02, PopulationinCountries = 26.02, PopulationinStates = 18.02
            });
            Population.Add(new Populations()
            {
                Continent = "Africa", Countries = "India", States = "Shandong", PopulationinContinents = 20.81, PopulationinCountries = 24, PopulationinStates = 8
            });
            Population.Add(new Populations()
            {
                Continent = "Europe", Countries = "Nigeria", States = "UP", PopulationinContinents = 15.37, PopulationinCountries = 12.81, PopulationinStates = 14.5
            });
            Population.Add(new Populations()
            {
                Countries = "Ethiopia", States = "Maharashtra", PopulationinCountries = 8, PopulationinStates = 9.5
            });
            Population.Add(new Populations()
            {
                Countries = "Germany", States = "Kano", PopulationinCountries = 8.37, PopulationinStates = 7.81
            });
            Population.Add(new Populations()
            {
                Countries = "Turkey", States = "Lagos", PopulationinCountries = 7, PopulationinStates = 5
            });
            Population.Add(new Populations()
            {
                States = "Oromia", PopulationinStates = 5
            });
            Population.Add(new Populations()
            {
                States = "Amhara", PopulationinStates = 3
            });
            Population.Add(new Populations()
            {
                States = "Hessen", PopulationinStates = 5.37
            });
            Population.Add(new Populations()
            {
                States = "Bayern", PopulationinStates = 3
            });
            Population.Add(new Populations()
            {
                States = "Istanbul", PopulationinStates = 4.5
            });
            Population.Add(new Populations()
            {
                States = "Ankara", PopulationinStates = 2.5
            });

            AdornmentsFac   = new ResourceFactory();
            AdornmentInfo   = new ChartAdornmentInfo();
            AdornmentInfo1  = new ChartAdornmentInfo();
            AdornmentInfo2  = new ChartAdornmentInfo();
            AdornmentInfo3  = new ChartAdornmentInfo();
            AdornmentInfo4  = new ChartAdornmentInfo();
            AdornmentInfo5  = new ChartAdornmentInfo();
            AdornmentInfo6  = new ChartAdornmentInfo();
            AdornmentInfo7  = new ChartAdornmentInfo();
            AdornmentInfo8  = new ChartAdornmentInfo();
            AdornmentInfo9  = new ChartAdornmentInfo();
            AdornmentInfo10 = new ChartAdornmentInfo();
            AdornmentInfo11 = new ChartAdornmentInfo();

            AdornmentInfo.HorizontalAlignment = HorizontalAlignment.Center;
            AdornmentInfo.VerticalAlignment   = VerticalAlignment.Center;
            AdornmentInfo.ShowConnectorLine   = true;
            AdornmentInfo.UseSeriesPalette    = true;
            AdornmentInfo.ConnectorHeight     = 30;
            AdornmentInfo.ShowLabel           = true;
            AdornmentInfo.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo.LabelTemplate       = AdornmentsFac.labelTemplate8;

            AdornmentInfo1.ShowLabel           = true;
            AdornmentInfo1.FontSize            = 10;
            AdornmentInfo1.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo1.LabelTemplate       = AdornmentsFac.labelTemplate21;

            AdornmentInfo2.ShowLabel           = true;
            AdornmentInfo2.FontSize            = 10;
            AdornmentInfo2.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo2.LabelTemplate       = AdornmentsFac.labelTemplate22;

            AdornmentInfo3.ShowLabel           = true;
            AdornmentInfo3.FontSize            = 10;
            AdornmentInfo3.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo3.LabelTemplate       = AdornmentsFac.labelTemplate23;

            AdornmentInfo4.ShowLabel           = true;
            AdornmentInfo4.SegmentLabelContent = LabelContent.Percentage;
            AdornmentInfo4.SegmentLabelFormat  = "##.#";
            AdornmentInfo4.AdornmentsPosition  = AdornmentsPosition.Bottom;
            AdornmentInfo4.HorizontalAlignment = HorizontalAlignment.Center;
            AdornmentInfo4.ConnectorHeight     = 30;
            AdornmentInfo4.VerticalAlignment   = VerticalAlignment.Center;
            AdornmentInfo4.ShowConnectorLine   = true;
            AdornmentInfo4.UseSeriesPalette    = true;

            AdornmentInfo5.ShowLabel        = true;
            AdornmentInfo5.UseSeriesPalette = true;

            AdornmentInfo6.ShowLabel           = true;
            AdornmentInfo6.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo6.AdornmentsPosition  = AdornmentsPosition.Bottom;
            AdornmentInfo6.LabelTemplate       = AdornmentsFac.labelTemplate21;

            AdornmentInfo7.ShowLabel           = true;
            AdornmentInfo7.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo7.AdornmentsPosition  = AdornmentsPosition.Bottom;
            AdornmentInfo7.LabelTemplate       = AdornmentsFac.labelTemplate22;

            AdornmentInfo8.ShowLabel           = true;
            AdornmentInfo8.SegmentLabelContent = LabelContent.LabelContentPath;
            AdornmentInfo8.AdornmentsPosition  = AdornmentsPosition.Bottom;
            AdornmentInfo8.LabelTemplate       = AdornmentsFac.labelTemplate23;

            AdornmentInfo9.ShowLabel         = true;
            AdornmentInfo9.ShowConnectorLine = true;
            AdornmentInfo9.UseSeriesPalette  = true;
            AdornmentInfo9.ConnectorHeight   = 17;

            AdornmentInfo10.ShowLabel = true;
            AdornmentInfo11.ShowLabel = true;
        }
Example #54
0
 protected override IList <GeneticEntity> GetEliteGeneticEntitiesCore(Population population)
 {
     throw new Exception();
 }
Example #55
0
 /// <summary>
 /// Finishes a phase for the strategy.
 /// </summary>
 /// <param name="basePopulation">Population on which this phase was based.</param>
 /// <returns>The <see cref="Population"/> for the next strategy to work with.</returns>
 public Population FinishPhase(Population basePopulation)
 {
     return(this._population);
 }
Example #56
0
        /// <inheritdoc />
        public void Iteration()
        {
            if (!_initialized)
            {
                PreIteration();
            }

            if (Population.Species.Count == 0)
            {
                throw new EncogError("Population is empty, there are no species.");
            }

            IterationNumber++;

            // Clear new population to just best genome.
            _newPopulation.Clear();
            _newPopulation.Add(BestGenome);
            _oldBestGenome = BestGenome;


            // execute species in parallel
            IList <EAWorker> threadList = new List <EAWorker>();

            foreach (ISpecies species in Population.Species)
            {
                int numToSpawn = species.OffspringCount;

                // Add elite genomes directly
                if (species.Members.Count > 5)
                {
                    var idealEliteCount = (int)(species.Members.Count * EliteRate);
                    int eliteCount      = Math.Min(numToSpawn, idealEliteCount);
                    for (int i = 0; i < eliteCount; i++)
                    {
                        IGenome eliteGenome = species.Members[i];
                        if (_oldBestGenome != eliteGenome)
                        {
                            numToSpawn--;
                            if (!AddChild(eliteGenome))
                            {
                                break;
                            }
                        }
                    }
                }

                // now add one task for each offspring that each species is allowed
                while (numToSpawn-- > 0)
                {
                    var worker = new EAWorker(this, species);
                    threadList.Add(worker);
                }
            }

            // run all threads and wait for them to finish
            Parallel.ForEach(threadList, currentTask => currentTask.PerformTask());

            // validate, if requested
            if (ValidationMode)
            {
                if (_oldBestGenome != null &&
                    !_newPopulation.Contains(_oldBestGenome))
                {
                    throw new EncogError(
                              "The top genome died, this should never happen!!");
                }

                if (BestGenome != null &&
                    _oldBestGenome != null &&
                    BestComparer.IsBetterThan(_oldBestGenome,
                                              BestGenome))
                {
                    throw new EncogError(
                              "The best genome's score got worse, this should never happen!! Went from "
                              + _oldBestGenome.Score + " to "
                              + BestGenome.Score);
                }
            }

            _speciation.PerformSpeciation(_newPopulation);

            // purge invalid genomes
            Population.PurgeInvalidGenomes();

            PostIteration();
        }
Example #57
0
        /// <summary>
        /// Calculates/generates a next generation based on the given one.
        /// </summary>
        /// <param name="population"></param>
        /// <returns></returns>
        private Population <GenomeType, ProblemType, WeightType> NextGeneration(Population <GenomeType, ProblemType, WeightType> population)
        {
            Population <GenomeType, ProblemType, WeightType> next_population =
                new Population <GenomeType, ProblemType, WeightType>(true);

            // do elitims selection.
            int elitism_count = (int)(population.Count * (_settings.ElitismPercentage / 100f));

            next_population.AddRange(
                population.GetRange(
                    0,
                    elitism_count));

            // do selection/cross-over.
            //Tools.Core.Output.OutputTextStreamHost.Write(" C:");
            int cross_over_count = (int)(population.Count *
                                         (_settings.CrossOverPercentage / 100f)) + elitism_count;

            while (next_population.Count < cross_over_count &&
                   next_population.Count < population.Count)
            {
                // select two individuals.
                Individual <GenomeType, ProblemType, WeightType> individual1 = _selector.Select(
                    this,
                    population,
                    null);
                Individual <GenomeType, ProblemType, WeightType> individual2 = _selector.Select(
                    this,
                    population,
                    new HashSet <Individual <GenomeType, ProblemType, WeightType> >(
                        new Individual <GenomeType, ProblemType, WeightType>[] { individual1 }));

                // cross-over.
                Individual <GenomeType, ProblemType, WeightType> new_individual =
                    _cross_over_operation.CrossOver(
                        this,
                        individual1,
                        individual2);

                new_individual.CalculateFitness(_problem, _fitness_calculator);
                if (_accept_only_better_on_cross_over)
                {
                    if (new_individual.Fitness.CompareTo(individual1.Fitness) < 0 &&
                        new_individual.Fitness.CompareTo(individual2.Fitness) < 0)
                    {
                        // add to the new population.
                        next_population.Add(new_individual);
                    }
                    else
                    {
                        //next_population.Add(individual1);
                        if (individual2.Fitness.CompareTo(individual1.Fitness) < 0)
                        {
                            // add to the new population.
                            next_population.Add(individual2);
                        }
                        else
                        {
                            next_population.Add(individual1);
                        }
                    }
                }
                else
                {
                    // add to the new population.
                    next_population.Add(new_individual);
                }

                //this.ReportNew("Crossing over population!", next_population.Count, population.Count);
                //Tools.Core.Output.OutputTextStreamHost.Write(".");
            }

            // do mutation to generate the rest of the population.
            int mutation_count =
                (int)(population.Count * (_settings.MutationPercentage / 100f)) + cross_over_count;
            int mutation_count_max_tries = mutation_count * 2; // try mutation 10 times more.
            int mutation_idx_absolute    = 0;

            //Tools.Core.Output.OutputTextStreamHost.Write(" m:");
            while (next_population.Count < mutation_count &&
                   next_population.Count < population.Count)
            {
                // get random individual.
                int individual_to_mutate_idx = this.Random.Next(population.Count);
                Individual <GenomeType, ProblemType, WeightType> individual_to_mutate =
                    population[individual_to_mutate_idx];

                // mutate.
                Individual <GenomeType, ProblemType, WeightType> mutation = _mutation_operation.Mutate(
                    this,
                    individual_to_mutate);
                //if (!mutation.Equals(individual_to_mutate))
                //{ // do not add indentical ones.
                // add to population.
                if (_accept_only_better_on_mutation)
                {
                    mutation.CalculateFitness(_problem, _fitness_calculator);
                    if (mutation.Fitness.CompareTo(individual_to_mutate.Fitness) < 0)
                    {
                        next_population.Add(mutation);
                    }
                }
                else
                {
                    next_population.Add(mutation);
                }

                //    //Tools.Core.Output.OutputTextStreamHost.Write(".");
                //    this.ReportNew("Mutating population!", next_population.Count, population.Count);
                //}

                // increase the absolute count.
                mutation_idx_absolute++;
                if (mutation_idx_absolute > mutation_count_max_tries)
                { // stop trying to mutate not new individuals could be found.
                    break;
                }
            }


            while (next_population.Count < population.Count)
            {
                // get random individual.
                int individual_to_mutate_idx = this.Random.Next(population.Count);
                Individual <GenomeType, ProblemType, WeightType> individual =
                    population[individual_to_mutate_idx];

                // place in the new population.
                next_population.Add(individual);

                this.ReportNew("Filling population!", next_population.Count, population.Count);
            }

            return(next_population);
        }
Example #58
0
 public void ExtractIndividualsFrom(Population population, params int[] individualIds)
 {
     ExtractIndividualsFrom(population, individualIds.ToList());
 }
Example #59
0
        public void Solve(Maze maze)
        {
            const int   NumberOfGenes = 5000;
            const float MutationRate  = 0.02f;
            const float CrossOverRate = 0.6f;
            var         selection     = new EliteSelection();
            var         crossover     = new UniformCrossover();
            var         mutation      = new UniformMutation(true);
            var         chromosome    = new MazeSolverChromosome(NumberOfGenes);
            var         reinsertion   = new ElitistReinsertion();
            var         population    = new Population(50, 100, chromosome);
            var         fitness       = new MazeWalkerFitness(maze);
            IChromosome best          = chromosome;

            best.Fitness = fitness.Evaluate(best);

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

            ga.MutationProbability = MutationRate;
            ga.Reinsertion         = reinsertion;
            ga.Termination         = new OrTermination(
                new FitnessStagnationTermination(this.stagnationThreshold),
                new TimeEvolvingTermination(TimeSpan.FromSeconds(this.maxRunTimeInSeconds)));
            ga.CrossoverProbability = CrossOverRate;
            ga.TaskExecutor         = new SmartThreadPoolTaskExecutor()
            {
                MinThreads = Environment.ProcessorCount,
                MaxThreads = Environment.ProcessorCount
            };
            ga.GenerationRan += (sender, eventargs) =>
            {
                if (this.generateUpdateImages)
                {
                    if (ga.GenerationsNumber == 1 || ga.GenerationsNumber % this.updateImageFrequency == 0)
                    {
                        var winnerSteps = FillMazeStepsWalked(maze, ga.BestChromosome);
                        ImageDraw(winnerSteps, $"gen{ga.GenerationsNumber}.png");
                    }
                }
                if (ga.GenerationsNumber % 10 == 0)
                {
                    Console.WriteLine(
                        $"{ga.GenerationsNumber} generations completed. Best fitness: {ga.BestChromosome.Fitness}.  Best so far: {best.Fitness}. Time evolving: {ga.TimeEvolving.TotalMinutes} min.");
                }

                if (ga.BestChromosome.Fitness > best.Fitness)
                {
                    best = ga.BestChromosome.Clone();

                    // ga.Population.CurrentGeneration.Chromosomes.Add(best);
                }
            };
            ga.TerminationReached += (sender, eventargs) =>
            {
                Console.WriteLine($"Termination Reached");
                var winnerSteps = FillMazeStepsWalked(maze, best);
                ImageDraw(winnerSteps, "best.png");

                var serializer = new XmlSerializer(typeof(string[]));
                using (var sw = new StreamWriter("bestchromosome.xml"))
                {
                    serializer.Serialize(sw, best.GetGenes().Select(g => g.Value as string).ToArray());
                }

                if (this.animate)
                {
                    File.Delete("output.gif");
                    this.gif.Save("output.gif");
                }
            };

            if (this.generateUpdateImages)
            {
                this.ImageDraw(maze, "gen0.png");
            }

            ga.Start();
        }
Example #60
-1
 private void LoadAllPeople(Population pop)
 {
     float errorCounter = 0;
     float totalError = 0;
     bool recklessPlacement = false;
     
     for (int i = 0; i < pop.currentPopulation; ++i)
     {
         Vector2 creationSpot = new Vector2(Random.Range(-Globals.mapRadiusX, Globals.mapRadiusX), Random.Range(-Globals.mapRadiusY, Globals.mapRadiusY));
         RaycastHit2D[] allHit = Physics2D.RaycastAll(creationSpot, -Vector2.up,0);
         if (allHit.Length == 0 || recklessPlacement)
         {
             GameObject go = Instantiate(Resources.Load("Villager"), creationSpot, Quaternion.identity) as GameObject;
             go.GetComponent<Villager>().Initialize(pop.averagePercentLifePoints, pop.averageHappiness, pop.averageHealthiness);
         } else {
             errorCounter++;
             totalError++;
             if (errorCounter > 10) //too much wait, that vilagers toast, next one
             {
                 errorCounter = 0;
                 ++i;
             }
             if (totalError > 40)  //too much thrashing, just place them ontop other objects and hope unity forces them out
             {
                 recklessPlacement = true;
             }                
         }            
     }        
 }