Example #1
0
 public void Elite()
 {
     IChromosome<int>[] a = new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }), new DigitalChromosome().GenerateFromArray(new int[] { 3, 3, 3 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 2, 2, 2 }), new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }), new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) };
     EliteSelection<int> selection = new EliteSelection<int>(2);
     IChromosome<int>[] res = selection.Select(a, x => x.ToArray().Sum(), 6);
     CollectionAssert.AreEqual(new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) }, res.Take(2).ToArray());
 }
        public static void CorretionCentroid()
        {
            //中心点数据
            Stopwatch sw = new Stopwatch();

            sw.Start();
            List <Coordinate> centroidPoints = new List <Coordinate>(80);
            StreamReader      sr             = new StreamReader(@"D:\MagicSong\OneDrive\2017研究生毕业设计\数据\项目用数据\中心点80.txt");

            sr.ReadLine();//读取标题行
            while (!sr.EndOfStream)
            {
                string[] line = sr.ReadLine().Split(',');
                centroidPoints.Add(new Coordinate(double.Parse(line[1]), double.Parse(line[2])));
            }
            sr.Close();
            //Bus数据,并且构造KD树
            KdTree            myKdtree      = new KdTree(2);
            IFeatureSet       busFS         = FeatureSet.Open(@"D:\MagicSong\OneDrive\2017研究生毕业设计\数据\项目用数据\BusStopGauss.shp");
            List <Coordinate> busStopPoints = new List <Coordinate>(busFS.NumRows());

            foreach (var item in busFS.Features)
            {
                var c = item.Coordinates[0];
                busStopPoints.Add(c);
                myKdtree.Insert(new double[] { c.X, c.Y }, item);
            }
            Console.WriteLine("数据读取完毕,开始构造遗传算法");
            IFeatureSet newCentroid = new FeatureSet(FeatureType.Point);

            newCentroid.Name       = "优化过的中心点";
            newCentroid.Projection = ProjectionInfo.FromEpsgCode(GAUSS_EPSG);
            newCentroid.DataTable.Columns.Add("name", typeof(string));
            //遗传算法,构造适应性函数
            MyProblemChromosome.CandiateNumber = 5;
            List <int[]> candinatesForEachControid = new List <int[]>(centroidPoints.Count);

            foreach (var item in centroidPoints)
            {
                object[] nearest = myKdtree.Nearest(new double[] { item.X, item.Y }, MyProblemChromosome.CandiateNumber);
                candinatesForEachControid.Add(nearest.Select((o) =>
                {
                    var f = o as IFeature;
                    return(f.Fid);
                }).ToArray());
            }
            MyProblemFitness    fitness = new MyProblemFitness(centroidPoints, busStopPoints, candinatesForEachControid);
            MyProblemChromosome mpc     = new MyProblemChromosome(centroidPoints.Count);
            //这边可以并行
            MyProblemChromosome globalBest = null;

            Console.WriteLine("遗传算法构造已经完成!");
            sw.Stop();
            Console.WriteLine("一共用时:{0}s", sw.Elapsed.TotalSeconds);
            int GACount = 8;

            Parallel.For(0, GACount, new Action <int>((index) =>
            {
                var selection  = new EliteSelection();
                var crossover  = new TwoPointCrossover();
                var mutation   = new ReverseSequenceMutation();
                var population = new Population(1000, 1200, mpc);
                var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
                ga.Termination = new GenerationNumberTermination(1000);
                Stopwatch sw1  = new Stopwatch();
                sw1.Start();
                Console.WriteLine("遗传算法任务{0}正在运行.......", index);
                ga.Start();
                var best = ga.BestChromosome as MyProblemChromosome;
                if (globalBest == null || globalBest.Fitness < best.Fitness)
                {
                    globalBest = best;
                }
                sw1.Stop();
                Console.WriteLine("第{0}次遗传算法已经完成,耗费时间为:{1}s,最终的fitness为:{2},有效个数为:{3}", index, sw1.Elapsed.TotalSeconds, best.Fitness, best.Significance);
            }));
            Console.WriteLine("Final Choose!");
            Console.WriteLine("最终的fitness为:{0},有效个数为:{1}", globalBest.Fitness, globalBest.Significance);
            for (int i = 0; i < globalBest.Length; i++)
            {
                int        index = candinatesForEachControid[i][(int)globalBest.GetGene(i).Value];
                Coordinate c     = busStopPoints[index];
                var        f     = newCentroid.AddFeature(new Point(c));
                f.DataRow.BeginEdit();
                f.DataRow["name"] = busFS.GetFeature(index).DataRow["name"];
                f.DataRow.EndEdit();
            }
            newCentroid.SaveAs("newCentroid.shp", true);
            Console.ReadKey();
        }
Example #3
0
        static void Main(string[] args)
        {
            #region Loading data from File

            string location = Directory.GetCurrentDirectory() + "\\Data\\graf4_kod.txt";

            int[,] data = LoadDataFromFile(location);
            roads       = new List <Road>();
            for (int i = 0; i < data.GetLength(0); i++)
            {
                Road newRoad = new Road(data[i, 0], data[i, 1], data[i, 2]);     // one direction cost
                roads.Add(newRoad);
                Road reverseRoad = new Road(data[i, 1], data[i, 0], data[i, 3]); // read reverse road
                roads.Add(reverseRoad);
            }

            #endregion
            var selection  = new EliteSelection();
            var crossover  = new ThreeParentCrossover();
            var mutation   = new TworsMutation();
            var fitness    = new CPFitness();
            var chromosome = new CPChromosome(3 * roads.Count);
            var population = new Population(200, 400, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.Termination = new GenerationNumberTermination(400);
            Stopwatch timer = new Stopwatch();
            timer.Start();
            Console.WriteLine("GA running...");
            ga.Start();
            Console.WriteLine();
            timer.Stop();
            bool first          = true;
            int  startCityIndex = Convert.ToInt32(ga.BestChromosome.GetGenes()[0].Value, CultureInfo.InvariantCulture);
            int  startCity      = roads[startCityIndex].cityFrom;
            int  totalCost      = 0;
            foreach (Gene gene in ga.BestChromosome.GetGenes())
            {
                int ind = Convert.ToInt32(gene.Value, CultureInfo.InvariantCulture);
                totalCost += roads[ind].cost;
                if (CPFitness.everyRoadIsTraveled(roads) && roads[ind].cityTo == startCity)
                {
                    Console.Write("-" + roads[ind].cityTo.ToString());
                    break;
                }
                else
                {
                    if (first)
                    {
                        Console.Write(roads[ind].cityFrom.ToString() + "-" + roads[ind].cityTo.ToString());
                        first = false;
                    }
                    else
                    {
                        Console.Write("-" + roads[ind].cityTo.ToString());
                    }
                    roads[ind].isTravelled = true;
                    Road returnRoad = roads.Find(e => e.index.Equals(roads[ind].cityTo.ToString() + "-" + roads[ind].cityFrom.ToString()));
                    returnRoad.isTravelled = true;
                }
            }
            TimeSpan ts          = timer.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Console.WriteLine();
            Console.WriteLine("Best solution found has {0} fitness.", ga.BestChromosome.Fitness);
            Console.WriteLine("Best solution has total cost: {0}", totalCost);
            Console.WriteLine("Time running: {0}", elapsedTime);
            Console.ReadKey();
        }
Example #4
0
        public OutputModel Process(InputModel input)
        {
            var toppingCount = Enum.GetValues(typeof(Topping)).Length;
            var sliceMasks   = GeneratePossibleSliceMasks(input.MinToppings * toppingCount, input.MaxCells).ToList();
            var validSlices  = new ConcurrentBag <Slice>();

            Parallel.ForEach(sliceMasks, mask =>
            {
                for (var i = 0; i < input.Rows - mask.Width; i++)
                {
                    for (var j = 0; j < input.Columns - mask.Height; j++)
                    {
                        var slice = new Slice(i, j, i + mask.Width, j + mask.Height);
                        if (IsValidSlice(input, slice))
                        {
                            validSlices.Add(slice);
                        }
                    }
                }
            });

            var orderedSlices = validSlices.ToList();

            var mutationRate  = 1f;
            var crossOverRate = 1f;

            RandomizationProvider.Current = new FastRandomRandomization();

            var fitness     = new PizzaCutterFitness(input, orderedSlices);
            var selection   = new EliteSelection();
            var crossOver   = new EvolutionStrategyCrossOver();
            var mutation    = new FlipBitMutation();
            var reinsertion = new EliteIncludeParentsReinsertion(fitness);
            var currentBest = new PizzaCutterChromosome(orderedSlices.Count, (input.Rows * input.Columns) / (input.MinToppings * toppingCount));

            currentBest.Fitness = fitness.Evaluate(currentBest);
            var population = new Population(10, 20, currentBest);



            var ga = new GeneticAlgorithm(population, fitness, selection, crossOver, mutation)
            {
                Reinsertion          = reinsertion,
                Termination          = new FitnessStagnationTermination(),
                CrossoverProbability = crossOverRate,
                MutationProbability  = mutationRate,
                TaskExecutor         = new SmartThreadPoolTaskExecutor()
                {
                    MinThreads = Environment.ProcessorCount,
                    MaxThreads = Environment.ProcessorCount
                }
            };


            ga.GenerationRan += (sender, args) =>
            {
                if (ga.BestChromosome.Fitness > currentBest.Fitness)
                {
                    currentBest = ga.BestChromosome.Clone() as PizzaCutterChromosome;
                }
            };

            ga.Start();

            var output = new OutputModel()
            {
                Slices = currentBest.GetSlices(orderedSlices).ToList()
            };

            return(output);
        }
Example #5
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            Models.Instance i = new Models.Instance();
            i.Days    = 7;
            i.Doctors = doctors;

            int min = (int)numMin.Value;
            int max = (int)numMax.Value;

            var        chromosome = new Models.Chromosome(21, i, r);
            var        population = new Population(min, max, chromosome);
            var        fitness    = new Models.Fitness();
            IMutation  mutation   = new TworsMutation();
            ISelection selection  = new RouletteWheelSelection();
            ICrossover crossover  = new OnePointCrossover(r.Next(20));

            if (cbxMutation.SelectedItem.ToString() == "Insertion")
            {
                mutation = new InsertionMutation();
            }
            else if (cbxMutation.SelectedItem.ToString() == "Partial Shuffle")
            {
                mutation = new PartialShuffleMutation();
            }
            else if (cbxMutation.SelectedItem.ToString() == "Reverse Sequence")
            {
                mutation = new ReverseSequenceMutation();
            }

            if (cbxSelection.SelectedItem.ToString() == "Elitizam")
            {
                selection = new EliteSelection();
            }

            if (cbxCrossover.SelectedItem.ToString() == "Two-point")
            {
                int p1 = r.Next(19);
                int p2 = r.Next(p1 + 1, 20);
                crossover = new TwoPointCrossover(p1, p2);
            }
            else if (cbxCrossover.SelectedItem.ToString() == "Uniform")
            {
                crossover = new UniformCrossover();
            }

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

            ITermination termination = new FitnessStagnationTermination(50);

            if (cbxTermination.SelectedItem.ToString() == "Generation number")
            {
                termination = new GenerationNumberTermination(200);
            }

            ga.Termination = termination;

            ga.MutationProbability = (float)numProbability.Value;

            ga.Start();

            Gene[] g = ga.BestChromosome.GetGenes();

            dataView.Rows.Clear();
            for (int j = 0; j < 7; j++)
            {
                string[] row = new string[] { ((List <int>)g[j * 3].Value)[0].ToString() + "   " + ((List <int>)g[j * 3].Value)[1].ToString(),
                                              ((List <int>)g[j * 3 + 1].Value)[0].ToString() + "   " + ((List <int>)g[j * 3 + 1].Value)[1].ToString(),
                                              ((List <int>)g[j * 3 + 2].Value)[0].ToString() + "   " + ((List <int>)g[j * 3 + 2].Value)[1].ToString() };

                dataView.Rows.Add(row);
                dataView.Rows[j].HeaderCell.Value = (j + 1).ToString();
            }

            lblFitness.Text = ga.BestChromosome.Fitness.ToString() + "  , generacija broj " + ga.GenerationsNumber.ToString();
        }
Example #6
0
        /// <summary>
        /// Example:
        ///
        /// http://diegogiacomelli.com.br/function-optimization-with-geneticsharp/
        /// </summary>
        static void Main(string[] args)
        {
            float maxWidth  = 998;
            float maxHeight = 680;

            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0, },
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
                new int[] { 10, 10, 10, 10 },
                new int[] { 0, 0, 0, 0 });

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

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

                var values = fc.ToFloatingPoints();
                var x1     = values[0];
                var y1     = values[1];
                var x2     = values[2];
                var y2     = values[3];

                return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)));
            });

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(100);

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

            ga.Termination = termination;

            Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");

            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,2}: ({1},{2}),({3},{4}) = {5}",
                        ga.GenerationsNumber,
                        phenotype[0],
                        phenotype[1],
                        phenotype[2],
                        phenotype[3],
                        bestFitness
                        );
                }
            };

            ga.Start();

            Console.ReadKey();
        }
Example #7
0
        /// <summary>
        /// Loads presetsProfile into service.
        /// </summary>
        /// <exception cref="T:System.InvalidOperationException">Thrown when an attempt to load presetsProfile twice is made.</exception>
        public void AddGeneticAlgorithm(GADefinition definition, Guid Key)
        {
            var chromosome = new FloatingPointChromosome(
                minValue: new double[] { 0, 0, 0, 0 },
                maxValue: new double[] { _maxWidth, _maxHeight, _maxWidth, _maxHeight },
                totalBits: new int[] { 20, 20, 20, 20 },
                fractionDigits: new int[] { 0, 0, 0, 0 }, geneValues: _geneValues);

            ICrossover gaCrossover = default;

            switch (definition.Crossover)
            {
            case Crossovers.Uniform:
                gaCrossover = new UniformCrossover(mixProbability: 0.5f);
                break;

            case Crossovers.OnePoint:
                gaCrossover = new OnePointCrossover(swapPointIndex: 40);
                break;

            case Crossovers.ThreeParent:
                gaCrossover = new ThreeParentCrossover();
                break;

            default:
                throw new ArgumentOutOfRangeException(paramName: nameof(definition.Crossover),
                                                      actualValue: definition.Crossover, message: "Crossover has wrong value");
            }

            ISelection gaSelection = default;

            switch (definition.Selection)
            {
            case Selections.Elite:
                gaSelection = new EliteSelection();
                break;

            case Selections.Roulette:
                gaSelection = new RouletteWheelSelection();
                break;

            case Selections.Tournament:
                gaSelection = new TournamentSelection(
                    size: decimal.ToInt32(d: decimal.Multiply(definition.Population, new decimal(0.2f))));
                break;

            case Selections.StohasticUniversalSampling:
                gaSelection = new StochasticUniversalSamplingSelection();
                break;

            default:
                throw new ArgumentOutOfRangeException(paramName: nameof(definition.Selection),
                                                      actualValue: definition.Selection, message: "Selection has wrong value");
            }

            var gaMutation = new UniformMutation(true);


            var gaPopulation = new Population(minSize: definition.Population,
                                              maxSize: definition.Population, adamChromosome: chromosome);

            var ga = new GeneticAlgorithm(population: gaPopulation,
                                          fitness: new EuclideanDistanceFitness(), selection: gaSelection,
                                          crossover: gaCrossover, mutation: gaMutation);

            ga.MutationProbability = (float)definition.Mutation;
            ga.GenerationRan      += GeneticAlgorithmOnGenerationRan;
            ga.Termination         =
                new FitnessStagnationTermination(expectedStagnantGenerationsNumber: 5);

            _geneticAlgorithms.Add(key: Key, value: ga);
        }
Example #8
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 #9
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Podaj nazwę plkiu z danymi(bez rozszerzenia)");
            string fileName = Console.ReadLine();

            string[]    lines           = File.ReadAllLines(Directory.GetCurrentDirectory() + "\\" + fileName + ".txt");
            int         edgesNumber     = lines.Count();
            List <Edge> edges           = new List <Edge>();
            int         edgeIndex       = 0;
            string      stringSeparator = " ";

            foreach (string l in lines)
            {
                int[] values = l.Split(stringSeparator.ToCharArray(), StringSplitOptions.None).Select(s => int.Parse(s)).ToArray();

                // Krawędź może być przechodzona w obu kierunkach
                edges.Add(new Edge(values[0], values[1], values[2], edgeIndex));

                // Ddodawana jest także w odwróconej wersji
                edges.Add(new Edge(values[1], values[0], values[2], edgeIndex));

                //Krawędź i jej odwrócona wersja mają ten sam indeks(dla łatwiejszego odnajdowania)
                edgeIndex++;
            }

            EliteSelection       selection  = new EliteSelection();
            ThreeParentCrossover crossover  = new ThreeParentCrossover();
            TworsMutation        mutation   = new TworsMutation();
            FitnessFunction      fitness    = new FitnessFunction(edges);
            Chromosome           chromosome = new Chromosome(4 * edgesNumber, edges);
            Population           population = new Population(200, 400, chromosome);

            GeneticAlgorithm ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new GenerationNumberTermination(400)
            };

            Stopwatch timer = new Stopwatch();

            timer.Start();
            Console.WriteLine("START!");
            ga.Start();
            timer.Stop();

            Chromosome bestChromosome   = ga.BestChromosome as Chromosome;
            int        currentEdgeIndex = int.Parse(bestChromosome.GetGene(0).Value.ToString());
            Edge       currentEdge      = edges[currentEdgeIndex];
            int        startVertex      = currentEdge.VertexA;
            int        totalCost        = currentEdge.Cost;
            string     verticesSequence = currentEdge.VertexA + "-" + currentEdge.VertexB;

            Console.WriteLine("Funkcja dopasowania najlepszego rozwiązania wynosi: {0}", bestChromosome.Fitness);
            for (int i = 1; i < bestChromosome.Length; i++)
            {
                currentEdgeIndex    = int.Parse(bestChromosome.GetGene(i).Value.ToString());
                currentEdge         = edges[currentEdgeIndex];
                currentEdge.Visited = true;
                edges.SingleOrDefault(e => e.VertexA == currentEdge.VertexB && e.VertexB == currentEdge.VertexA).Visited = true;
                totalCost        += currentEdge.Cost;
                verticesSequence += "-" + currentEdge.VertexB;

                if (FitnessFunction.AllEdgesVisited(edges))
                {
                    if (currentEdge.VertexB == startVertex)
                    {
                        break;
                    }

                    Edge possibleEdge = edges.SingleOrDefault(e => e.VertexA == currentEdge.VertexB && e.VertexB == startVertex);
                    if (possibleEdge != null)
                    {
                        totalCost        += possibleEdge.Cost;
                        verticesSequence += "-" + possibleEdge.VertexB;
                        break;
                    }
                }
            }

            Console.WriteLine("Ścieżka: {0}", verticesSequence);
            Console.WriteLine("Koszt najlepszego rozwiązania: {0}", totalCost);
            Console.WriteLine("Czas wykonania: {0}", timer.Elapsed.ToString(@"hh\:mm\:ss\:ff"));
            Console.ReadKey();
        }
        public Core.Sudoku SolveGeneticSharp(Core.Sudoku s)
        {
            var         populationSize   = 10000;
            IChromosome sudokuChromosome = new SudokuPermutationsChromosome(s);
            //IChromosome sudokuChromosome = new SudokuCellsChromosome(s);
            var fitnessThreshold = 0;
            //var generationNb = 50;
            var crossoverProbability = 0.75f;
            var mutationProbability  = 0.2f;
            var fitness   = new SudokuFitness(s);
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation();

            IChromosome bestIndividual;
            var         solution = s;
            int         nbErrors = int.MaxValue;


            do
            {
                var population = new Population(populationSize, populationSize, sudokuChromosome);
                var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
                {
                    Termination = new OrTermination(new ITermination[]
                    {
                        new FitnessThresholdTermination(fitnessThreshold),
                        new FitnessStagnationTermination(10),
                        //new GenerationNumberTermination(generationNb)
                        //new TimeEvolvingTermination(TimeSpan.FromSeconds(10)),
                    }),
                    MutationProbability  = mutationProbability,
                    CrossoverProbability = crossoverProbability,
                    OperatorsStrategy    = new TplOperatorsStrategy(),
                };
                ga.GenerationRan += delegate(object sender, EventArgs args)
                {
                    bestIndividual = (ga.Population.BestChromosome);
                    solution       = ((ISudokuChromosome)bestIndividual).GetSudokus()[0];
                    nbErrors       = solution.NbErrors(s);
                    Console.WriteLine($"Generation #{ga.GenerationsNumber}: best individual has {nbErrors} errors");
                };
                ga.Start();

                //bestIndividual = (ga.Population.BestChromosome);
                //solution = ((ISudokuChromosome)bestIndividual).GetSudokus()[0];
                //nbErrors = solution.NbErrors(s);
                if (nbErrors == 0)
                {
                    break;
                }
                else
                {
                    populationSize *= 2;
                    Console.WriteLine($"Genetic search failed with {nbErrors} resulting errors, doubling population to {populationSize}");
                }
            } while (true);



            return(solution);
        }
Example #11
0
        public GeneticOptimizer(GeneticOptimizerConfiguration configuration, Func <double[], double> objectiveFunction, Action <string> generationRanCallback = null)
        {
            //store configuration
            _configuration         = configuration;
            _generationRanCallback = generationRanCallback;

            //set min/max/precision of input variables
            var minValues      = new double[_configuration.Variables.Count];
            var maxValues      = new double[_configuration.Variables.Count];
            var fractionDigits = new int[_configuration.Variables.Count];

            for (int index = 0; index < _configuration.Variables.Count; index++)
            {
                minValues[index]      = _configuration.Variables[index].MinimumValue;
                maxValues[index]      = _configuration.Variables[index].MaximumValue;
                fractionDigits[index] = _configuration.Variables[index].NumberDigitsPrecision;
            }

            //total bits
            var totalBits = new int[] { 64 };

            //chromosome
            var chromosome = new FloatingPointChromosome(minValues, maxValues, totalBits, fractionDigits);

            //population
            var population = new Population(MinimumNumberPopulation, MaximumNumberPopulation, chromosome);

            //set fitness function
            var fitnessFunction = new FuncFitness(c =>
            {
                var fc     = c as FloatingPointChromosome;
                var inputs = fc.ToFloatingPoints();
                var result = objectiveFunction(inputs);

                //add to results
                if (!Double.IsNaN(result))
                {
                    var list = inputs.ToList();
                    list.Add(result);

                    _result.IterationArray.Add(string.Join(",", list));
                }

                return(result);
            });

            //other variables
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessThresholdTermination();

            _algorithm = new GeneticAlgorithm(population, fitnessFunction, selection, crossover, mutation)
            {
                Termination = termination,
            };

            //task parallelism
            var taskExecutor = new ParallelTaskExecutor();

            taskExecutor.MinThreads = 1;
            taskExecutor.MaxThreads = _configuration.NumberThreadsToUse;
            _algorithm.TaskExecutor = taskExecutor;

            //if (_configuration.NumberThreadsToUse > 1)
            //{
            //    var taskExecutor = new ParallelTaskExecutor();
            //    taskExecutor.MinThreads = 1;
            //    taskExecutor.MaxThreads = _configuration.NumberThreadsToUse;
            //    _algorithm.TaskExecutor = taskExecutor;
            //}

            //register generation ran callback
            _algorithm.GenerationRan += AlgorithmOnGenerationRan;
        }
Example #12
0
        public IHttpActionResult Generuj(DateTime poczatek, DateTime koniec, int naGodzine)
        {
            User = System.Web.HttpContext.Current.User;
            int user;

            int.TryParse(((ClaimsIdentity)User.Identity).Claims.First(c => c.Type == "Id").Value, out user);

            ((ClaimsIdentity)User.Identity).Claims.First(c => c.Type == "Admin");
            if (((ClaimsIdentity)User.Identity).Claims.First(c => c.Type == "Admin").Value == "false")
            {
                return(Content(HttpStatusCode.Forbidden, "Brak uprawnień do wykonania zadania!"));
            }

            Models.Grafik grafik = null;

            try
            {
                if (TRWA_GENEROWANIE)
                {
                    return(Content(HttpStatusCode.Conflict, "Trwa Generowanie"));
                }
                TRWA_GENEROWANIE = true;

                Models.DataBaseEntities db = new Models.DataBaseEntities();

                List <Models.Pracownik>  pracownicy = db.Pracownik.Where(p => p.GodzinWUmowie > 0 && p.StanowiskoPracownika.Count() > 0).ToList();
                List <Models.Stanowisko> stanowiska = db.Stanowisko.Where(s => s.StanowiskoPracownika.Count() > 0).ToList();

                // 1 bit dla czy w pracy
                // pozostale numer stanowiska
                int dlugoscKodonu = (int)Math.Round(Math.Log(stanowiska.Count(), 2), 0, MidpointRounding.AwayFromZero);

                int    iloscPrzedzialow = (int)Math.Round(koniec.Subtract(poczatek).TotalHours *naGodzine, 0, MidpointRounding.AwayFromZero) * naGodzine;
                double przedzial        = 60 / naGodzine;

                List <double> genMin     = new List <double>();
                List <double> genMax     = new List <double>();
                List <int>    genBits    = new List <int>();
                List <int>    genDecimal = new List <int>();

                for (int i = 0; i < iloscPrzedzialow * pracownicy.Count(); i++)
                {
                    genMin.Add(0);
                    genMin.Add(0);
                    genMax.Add(1);
                    genMax.Add(stanowiska.Count() - 1);
                    genBits.Add(1);
                    genBits.Add(dlugoscKodonu);
                    genDecimal.Add(0);
                    genDecimal.Add(0);
                }

                var selection = new EliteSelection();
                //var selection = new TournamentSelection(100, true);
                var crossover = new UniformCrossover(0.5f);
                //var crossover = new ThreeParentCrossover();
                //var mutation = new ReverseSequenceMutation();
                var mutation = new FlipBitMutation();
                //var mutation = new UniformMutation(false);
                var fitness = new OcenaGrafiku(pracownicy, stanowiska, naGodzine, poczatek, koniec);

                var termination = new GeneticSharp.Domain.Terminations.OrTermination(
                    new FitnessStagnationTermination(1000), new FitnessThresholdTermination(0), new TimeEvolvingTermination(new TimeSpan(0, 5, 0)));

                var chromosome = new FloatingPointChromosome(genMin.ToArray(), genMax.ToArray(), genBits.ToArray(), genDecimal.ToArray());
                var population = new Population(1000, 10000, chromosome);


                var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
                ga.Termination         = termination;
                ga.MutationProbability = 0.20f;

                ga.Start();

                var    wynik = (ga.BestChromosome as FloatingPointChromosome).ToFloatingPoints();
                double?x     = (ga.BestChromosome as FloatingPointChromosome).Fitness;

                DateTime czas = poczatek;

                grafik          = new Models.Grafik();
                grafik.Poczatek = poczatek;
                grafik.Koniec   = koniec;

                db.Grafik.Add(grafik);

                int j = 0;
                while (czas < koniec)
                {
                    Models.Czas cz = new Models.Czas();

                    foreach (Models.Pracownik pr in pracownicy)
                    {
                        if (wynik[j] == 1)
                        {
                            Models.PracownikNaStanowisku pns = new Models.PracownikNaStanowisku();
                            pns.Pracownik  = pr;
                            pns.Stanowisko = stanowiska[(int)wynik[j + 1] % stanowiska.Count()];
                            pns.Czas       = cz;

                            db.PracownikNaStanowisku.Add(pns);
                        }
                        j += 2;
                    }
                    if (cz.PracownikNaStanowisku.Count() > 0)
                    {
                        cz.Grafik   = grafik;
                        cz.Poczatek = czas;
                        cz.Koniec   = czas.AddMinutes(przedzial);
                        db.Czas.Add(cz);
                    }
                    czas = czas.AddMinutes(przedzial);
                }

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, ex.ToString()));
            }
            TRWA_GENEROWANIE = false;

            return(Ok(grafik.Id));
        }
Example #13
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("GeneticSharp - ConsoleApp");
            Console.ResetColor();
            Console.WriteLine("Select the sample:");
            Console.WriteLine("1) TSP (Travelling Salesman Problem)");
            Console.WriteLine("2) Ghostwriter");
            var sampleNumber = Console.ReadLine();
            ISampleController sampleController = null;

            switch (sampleNumber)
            {
            case "1":
                sampleController = new TspSampleController(20);
                break;

            case "2":
                sampleController = new GhostwriterSampleController();
                break;

            default:
                return;
            }

            var selection  = new EliteSelection();
            var crossover  = new UniformCrossover();
            var mutation   = new UniformMutation(true);
            var fitness    = sampleController.CreateFitness();
            var population = new Population(50, 70, sampleController.CreateChromosome());

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

            ga.MutationProbability = 0.4f;
            ga.Termination         = new FitnessStagnationTermination(100);

            ga.TaskExecutor = new SmartThreadPoolTaskExecutor()
            {
                MinThreads = 25,
                MaxThreads = 50
            };

            ga.GenerationRan += delegate
            {
                Console.CursorLeft = 0;
                Console.CursorTop  = 5;

                var bestChromosome = ga.Population.BestChromosome;
                Console.WriteLine("Generations: {0}", ga.Population.GenerationsNumber);
                Console.WriteLine("Fitness: {0:n4}", bestChromosome.Fitness);
                Console.WriteLine("Time: {0}", ga.TimeEvolving);
                sampleController.Draw(bestChromosome);
            };

            try
            {
                ga.Start();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine();
                Console.WriteLine("Error: {0}", ex.Message);
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine();
            Console.WriteLine("Evolved.");
            Console.ResetColor();
            Console.ReadKey();
        }
Example #14
0
        /**
         *
         * Genetic Algorithm with Revit API
         *
         * This sample is using GeneticSharp Library (github.com/giacomelli/GeneticSharp)
         * The MIT License (MIT)
         * Copyright (c) 2013 Diego Giacomelli
         */
        public void GridObjectPlacement(DesignAutomationData data)
        {
            m_doc = data.RevitDoc;
            m_app = data.RevitApp;

            InputData inputParameters = JsonConvert.DeserializeObject <InputData>(File.ReadAllText("params.json"));

            // Family Symbol
            Document familyProjectDoc = m_app.OpenDocumentFile("family.rvt");

            string    tempFamilyName      = Path.GetFileNameWithoutExtension(inputParameters.FamilyFileName) + ".rfa";
            ModelPath tempFamilyModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(tempFamilyName);

            FamilySymbol tempFamilySymbol = null;

            FilteredElementCollector familyInstanceCollector
                = new FilteredElementCollector(familyProjectDoc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_Furniture)
                  .OfClass(typeof(FamilyInstance));

            foreach (Element familyInstanceElem in familyInstanceCollector)
            {
                FamilyInstance fi = familyInstanceElem as FamilyInstance;

                Element superComponent = fi.SuperComponent;

                if (superComponent == null)
                {
                    tempFamilySymbol = fi.Symbol;

                    Family family = tempFamilySymbol.Family;

                    Document familyDoc = familyProjectDoc.EditFamily(family);

                    Family loadedFamily = familyDoc.LoadFamily(m_doc);

                    ISet <ElementId> familySymbolIds = loadedFamily.GetFamilySymbolIds();

                    foreach (ElementId familySymbolId in familySymbolIds)
                    {
                        FamilySymbol familySymbol = m_doc.GetElement(familySymbolId) as FamilySymbol;

                        m_familySymbol = familySymbol;
                    }

                    break;
                }
            }

            if (!m_familySymbol.IsActive)
            {
                using (Transaction tx = new Transaction(m_doc))
                {
                    tx.Start("Transaction Activate Family Symbol");
                    m_familySymbol.Activate();
                    tx.Commit();
                }
            }

            // Room
            m_room = m_doc.GetElement(inputParameters.RoomUniqueId) as Room;

            // Level
            m_level = m_doc.GetElement(m_room.LevelId) as Level;

            // View
            ElementId viewId = m_level.FindAssociatedPlanViewId();

            if (viewId != null)
            {
                m_view = m_doc.GetElement(viewId) as View;
            }

            // Selected Placement Method
            m_selectedPlacementMethod = int.Parse(inputParameters.GridTypeId);

            // Construct Chromosomes with 3 params, m_objectDistanceX, m_objectDistanceY, m_selectedPlacementMethod
            var chromosome = new FloatingPointChromosome(
                new double[] { double.Parse(inputParameters.DistanceXMinParam), double.Parse(inputParameters.DistanceYMinParam), double.Parse(inputParameters.DistanceWallMinParam) },
                new double[] { double.Parse(inputParameters.DistanceXMaxParam), double.Parse(inputParameters.DistanceYMaxParam), double.Parse(inputParameters.DistanceWallMaxParam) },
                new int[] { 32, 32, 32 },
                new int[] { 2, 2, 2 });

            // Population Settings
            //
            // The population size needs to be 'large enough'.
            // The question of when a population is large enough is difficult to answer.
            // Generally, it depends on the project, the number of genes, and the gene value range.
            // A good rule of thumb is to set the population size to at least 3x the number of inputs.
            // If the results don't start to converge to an answer, you may need to increase the population size.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-02_initialization-phase
            var population = new Population(8, 12, chromosome);

            // Fitness Function Settings
            //
            // Call CreateObjectPlacementPointList() and get count of points.
            // This sample maximize a number of objects to place in a room.
            //
            // A fitness function is used to evaluate how close (or far off) a given design solution is from meeting the designer�fs goals.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-03_evaluation-phase
            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();

                m_objectDistanceX = values[0];
                m_objectDistanceY = values[1];
                m_minimumDistanceFromObjectToWall = values[2];

                List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                return(objectPlacementPointList.Count);
            });

            var selection = new EliteSelection();
            var crossover = new UniformCrossover(0.5f);
            var mutation  = new FlipBitMutation();

            // Termination Condition Settings
            //
            // To finish the process in half an hour, this sample sets 2 conditions.
            var termination = new OrTermination(
                new GenerationNumberTermination(20),
                new TimeEvolvingTermination(TimeSpan.FromMinutes(10)));

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

            ga.Termination = termination;

            Console.WriteLine("Generation: objectDistanceX, objectDistanceY, minimumDistanceFromObjectToWall = objectCount");

            var latestFitness = 0.0;

            // Callback Function of Generation Result
            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

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

                    m_objectDistanceX = phenotype[0];
                    m_objectDistanceY = phenotype[1];
                    m_minimumDistanceFromObjectToWall = phenotype[2];

                    Console.WriteLine(
                        "Generation {0,2}: objectDistanceX: {1}, objectDistanceY: {2}, minimumDistanceFromObjectToWall: {3} = objectCount: {4}",
                        ga.GenerationsNumber,
                        m_objectDistanceX,
                        m_objectDistanceY,
                        m_minimumDistanceFromObjectToWall,
                        bestFitness
                        );

                    List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                    using (Transaction tx = new Transaction(m_doc))
                    {
                        tx.Start("Transaction Create Family Instance");

                        m_view.SetCategoryHidden(new ElementId(BuiltInCategory.OST_Furniture), false);

                        foreach (XYZ point in objectPlacementPointList)
                        {
                            FamilyInstance fi = m_doc.Create.NewFamilyInstance(point, m_familySymbol, m_level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                            m_doc.Regenerate();

                            BoundingBoxXYZ fiBB = fi.get_BoundingBox(m_view);

                            double xDiff = fiBB.Max.X - fiBB.Min.X;
                            double yDiff = fiBB.Max.Y - fiBB.Min.Y;

                            if (m_objectDistanceX / m_objectDistanceY >= 1.2 && yDiff / xDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                            else if (m_objectDistanceY / m_objectDistanceX >= 1.2 && xDiff / yDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                        }

                        DWGExportOptions dwgOptions = new DWGExportOptions();

                        ICollection <ElementId> views = new List <ElementId>();
                        views.Add(m_view.Id);

                        m_doc.Export(Directory.GetCurrentDirectory() + "\\exportedDwgs", m_level.Name + "_" + m_room.Name + "_Gen " + ga.GenerationsNumber + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"), views, dwgOptions);

                        tx.RollBack();
                    }
                }
            };

            ga.Start();
        }
Example #15
0
File: Form1.cs Project: bjutlgr/ga1
        private void Go_Click(object sender, EventArgs e)
        {
            //initialize var
            int cLength = Convert.ToInt32(chromoLength.Text);
            EliteSelection<int> sel2 = new EliteSelection<int>(0);
            RouletteSelection<int> sel1 = new RouletteSelection<int>();
            GreedyCrossover cros = new GreedyCrossover(-1, -1, matrix);
            GoldenMutation<int> mut = new GoldenMutation<int>(cLength);
            pop = new Population<int>(mut, cros, sel1, sel2, x => 1 / cros.CalcFitness(x),
                Convert.ToDouble(mProb.Text), Convert.ToDouble(cProb.Text));
            maxF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1];
            avgF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1];
            double min = 100500; // Hi to Max ))
            string bestChromo = null;

            //experiments
            for (int i = 0; i < Convert.ToInt32(expCount.Text); ++i)
            {
                //initial chromosomes
                Trace.WriteLine("experiment #" + (i + 1).ToString());
                Trace.Indent();
                ChromosomesFromArray();
                maxF[i, 0] = Math.Round(1 / pop.GetMaxFitness());
                avgF[i, 0] = 1 / pop.GetPopulationFitness();
                Trace.WriteLine("initial best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString());
                Trace.WriteLine("initial avg fitness = " + (1 / pop.GetPopulationFitness()).ToString());
                Trace.WriteLine("initia;best fitness chromo = " + pop.GetMaxChromo());

                // iterations
                for (int j = 0; j < Convert.ToInt32(iterCount.Text); ++j)
                {
                    Trace.WriteLine("iteration #" + (j + 1).ToString());
                    Trace.Indent();
                    pop.Iteration();
                    maxF[i, j + 1] = Math.Round(1 / pop.GetMaxFitness());
                    avgF[i, j + 1] = 1 / pop.GetPopulationFitness();
                    Trace.WriteLine(" best fitness  = " + Math.Round((1 / pop.GetMaxFitness())).ToString());
                    Trace.WriteLine("avg fitness = " + (1 / pop.GetPopulationFitness()).ToString());
                    Trace.WriteLine("best fitness chromo = " + pop.GetMaxChromo());
                    Trace.Unindent();
                }
                if (Math.Round(1 / pop.GetMaxFitness()) < min)
                {
                    min = Math.Round(1 / pop.GetMaxFitness());
                    bestChromo = pop.GetMaxChromo();
                }
                Trace.Unindent();
            }
            answer.Text = "Best Path: " + bestChromo + "Path Length" + min.ToString();
        }
Example #16
0
        private void StartEvolution()
        {
            SetupSourceColorMatrix();
            if (currentDrawing == null)
            {
                currentDrawing = GetNewInitializedDrawing();
            }
            lastSelected = 0;

            var selection = new EliteSelection();
//      var selection = new CustomSelection(20);
            var crossover = new OrderedCrossover();
//      var crossover = new CycleCrossover();
//      var crossover = new CutAndSpliceCrossover();
//      var crossover = new OnePointCrossover(2);
            var mutation = new CustomMutation();
//      var mutation = new UniformMutation(true);
            var fitness    = new DrawingFitness(sourceColors);
            var chromosome = new PolygonChromosome();
            var population = new Population(10, 100, chromosome);

            _ga             = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            _ga.Termination = new TimeEvolvingTermination(TimeSpan.FromHours(4));
//
            _ga.GenerationRan += (sender, args) =>
            {
                generation++;
                var best    = _ga.Population.CurrentGeneration.Chromosomes.OrderBy(c => c.Fitness).First() as PolygonChromosome;
                var drawing = new DnaDrawing(best);
                if (best.Fitness.Value <= errorLevel)
                {
                    errorLevel = best.Fitness.Value;
                    lock (currentDrawing)
                    {
                        currentDrawing = drawing;
                    }
                    selected++;
                }
            };
            _ga.Stopped += (sender, args) =>
            {
                Stop();
            };
            _ga.Start();


//            while (isRunning)
//            {
//                DnaDrawing newDrawing;
//                lock (currentDrawing)
//                {
//                    newDrawing = currentDrawing.Clone();
//                }
//                newDrawing.Mutate();
//
//                if (newDrawing.IsDirty)
//                {
//                    generation++;
//
//                    double newErrorLevel = FitnessCalculator.GetDrawingFitness(
//                      newDrawing,
//                      sourceColors);
//
//                    if (newErrorLevel <= errorLevel)
//                    {
//                        selected++;
//                        lock (currentDrawing)
//                        {
//                            currentDrawing = newDrawing;
//                        }
//                        errorLevel = newErrorLevel;
//                    }
//                }
//                //else, discard new drawing
//            }
        }
Example #17
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();
        }