コード例 #1
0
        public GeneticSharpSolver Setup()
        {
            var chromosome = new FloatingPointChromosome(
                _decisions.Select(d => d.LowerBound).ToArray(),
                _decisions.Select(d => d.UpperBound).ToArray(),
                _decisions.Select(d => d.TotalBits).ToArray(),
                _decisions.Select(d => d.FractionDigits).ToArray());

            var population = new Population(_populationSize, _populationSize + _offspringNumber, chromosome);

            var fitness     = new FuncFitness((c) => { return(_objective(c as FloatingPointChromosome, this)); });
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new GenerationNumberTermination(_maxGenerations);

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

            _ga.Termination = termination;
            if (_generationCallback != null)
            {
                _ga.GenerationRan += (sender, e) => _generationCallback(_ga);
            }

            return(this);
        }
コード例 #2
0
        public static GeneticSharp.Domain.GeneticAlgorithm DefaultGeneticAlgorithm(Func <double[], double> func, Tuple <double, double>[] minmax)
        {
            var population = new Population(20, 40, chromosome.CreateIntChromosone(minmax));

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

                var values = fc.ToFloatingPoints();
                return(func(values));
            });

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

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

            var termination = new FitnessStagnationTermination(100);

            ga.Termination = termination;


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

            return(ga);
        }
コード例 #3
0
        public void Evaluate_Func_CallFunc()
        {
            var target = new FuncFitness((c) =>
            {
                return(c.Fitness.Value + 1);
            });

            Assert.AreEqual(3, target.Evaluate(new ChromosomeStub(2d)));
        }
コード例 #4
0
        public void OptimizeAI()
        {
            if (frequency != turnsSinceLastOptimization)
            {
                turnsSinceLastOptimization++;
                return;
            }

            GenerateScoreData();

            int maxSize = GetMaxSize();
            AiSettingsChromosome intelligenceChromosome = new AiSettingsChromosome(3);
            Population           population             = new Population(maxSize, maxSize, intelligenceChromosome);

            FuncFitness fitness;

            if (HistoryManagr.Instance.savingHistory == true)
            {
                fitness = new FuncFitness((c) => { return(GetHistoryFitness(c)); });
            }
            else
            {
                fitness = new FuncFitness((c) => { return(GetFitness(c)); });
            }

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new DisplacementMutation();
            var termination = new GenerationNumberTermination(2);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            List <IChromosome> savedChromosomes = new List <IChromosome>();

            ga.Termination    = termination;
            ga.GenerationRan += (sender, e) =>
            {
                if (ga.GenerationsNumber == 2)
                {
                    savedChromosomes = (List <IChromosome>)ga.Population.CurrentGeneration.Chromosomes;
                }
            };

            ga.Start();

            turnsSinceLastOptimization = 0;
            settingsScoreData.Clear();
            settingsData.Clear();

            SetGeneratedData(savedChromosomes);
            foreach (PlayerData player in PlayerManager.Instance.players)
            {
                EventSaverManager.Instance.SaveDDAEvolutionAIEvent(player.id);
            }
        }
コード例 #5
0
        public void Start_FloatingPoingChromosome_Evolved()
        {
            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0 },
                new double[] { 1000, 1000, 1000, 1000 },
                new int[] { 10, 10, 10, 10 },
                new int[] { 0, 0, 0, 0 });

            var population = new Population(25, 25, chromosome);

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

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

                // Euclidean distance: https://en.wikipedia.org/wiki/Euclidean_distance
                return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)));
            });

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

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

            ga.Termination = termination;
            ga.Start();

            var bc     = ga.BestChromosome as FloatingPointChromosome;
            var points = bc.ToFloatingPoints();

            Assert.AreEqual(4, points.Length);

            Assert.AreEqual(1414.2135623730951, bc.Fitness);
            Assert.GreaterOrEqual(ga.GenerationsNumber, 100);
        }
コード例 #6
0
        public Task <Timetable> RunAsync()
        {
            var adamChromosome = CreateAdamChromosome();

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

            var fitness = new FuncFitness(TimetablerFitnessFunction);

            var selection = new EliteSelection();

            var crossover = new UniformCrossover(0.5f);

            var mutation = new FlipBitMutation();

            var termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(20));

            var geneticAlgorithm = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation)
            {
                Termination = termination
            };

            geneticAlgorithm.GenerationRan += (sender, e) =>
            {
                var bestChromosome = geneticAlgorithm.BestChromosome as FloatingPointChromosome;
                GeneticSolution = ChromosomeToTimetable(bestChromosome);
            };

            GeneticAlgorithm = geneticAlgorithm;

            return(Task.Factory.StartNew(() =>
            {
                geneticAlgorithm.Start();
                return GeneticSolution;
            }));
        }
コード例 #7
0
        public static void Main(string[] args)
        {
            //Inicjujemy zmienne które będą granicznymi wartościami dla naszych punktów x1,x2,y1,y2.
            double maxWidth = 9999;

            double maxHeight = 8765;

            //Tworzymy strukture pojedyńczego chormosomu
            var chromosome = new FloatingPointChromosome(
                new double[] { -1000, -1000, -1000, -1000 },               //Warości początkowe dla x1,x2,y1,y2
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight }, //Wartości maksymalne dla x1,x2,y1,y2
                new int[] { 64, 64, 64, 64 },                              //Liczba bitów użytych do uzyskania wyniku
                new int[] { 0, 0, 0, 0 });

            var population = new Population(10, 50, chromosome);            //Określamy ilość chromosomów
            //(x,y,chromosome) x=minimalna liczba chromosomów, y=maksymalna liczba chormosomów
            //chromosome=odniesienie się do wyżej utworzonego chromosomu



            var fitness = new FuncFitness((c) =>                                //Implementacja funkcji fitness z chormosomem w zmiennej "c"
            {
                var fc = c as FloatingPointChromosome;                          //Rzutowanie powyższego chormosomu na FloatingPointChromosme

                var values = fc.ToFloatingPoints();                             //konwertowanie FloatingPointChromosome do jego fenotypu

                var x1 = values[0];                                             //konwertowanie FloatingPointChromosome do jego fenotypu x1

                var y1 = values[1];                                             //konwertowanie FloatingPointChromosome do jego fenotypu y1

                var x2 = values[2];                                             //konwertowanie FloatingPointChromosome do jego fenotypu x2

                var y2 = values[3];                                             //konwertowanie FloatingPointChromosome do jego fenotypu y2

                return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); //Przekazanie wartości do naszej funkcji
            });

            var selection = new EliteSelection();             //Selekcja odpowiada za wybór chormosomów o największym dystanisie

            var crossover = new UniformCrossover(0.5f);       //Ta sekcja pozwala na krzyżowanie się chromosomów aby generować nowe rozwiązania dla kolejnej generacji
            //Potomstwo przy parametrze 0.5 posiada mniej więcej połowę genów rodziców.

            var mutation = new FlipBitMutation();            //Mutacja uniemożliwa "utknięcie" naszego algorytmu w optimum lokalnym, mutacja Flip-Bit lodowo wybiera
            //gen i odwraca jego wartości, gen o wartości 1 stanie się genem o wartości 0

            var termination = new FitnessStagnationTermination(1000);            //Warunek zakończenia działania algorytmu
            //Jeżeli nasz program wygeneruje w ciągu 1000 pokoleń taką samą wartość funkcji fitness to działanie programu zostanie zakończone.

            //Poniższy fragment odpowiada ze wywołanie zdefiniowanych przez nas wartości komenda ga.Start() spodowuje rozpoczęcie działania funkcji
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;
            //Cały poniższy blok kodu podowuje wyświetlenie kolejnych kroków wyliczania AG na ekranie konsoli
            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}: (X1={1},Y1={2}),(X2={3},Y2={4}) = Największy dystans między punktami {5}",
                        ga.GenerationsNumber,
                        phenotype[0],
                        phenotype[1],
                        phenotype[2],
                        phenotype[3],
                        bestFitness
                        );
                }
            };

            ga.Start();

            Console.ReadKey();
        }
コード例 #8
0
        public void Start()
        {
            var w   = new StreamWriter("C:\\Users\\Taylor\\source\\repos\\ComboProject\\ComboProject\\bin\\Debug\\genelog.csv");
            int gen = 1;

            // init chromosomes
            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
                new int[] { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 },
                new int[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 });

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

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

                var genes = fc.ToFloatingPoints();

                string combo = combogen.generateGeneticCombo(genes, 0);

                int damage = ComboSimulator.getComboDamage(combo, movelist);

                w.WriteLine(string.Format("{0},{1},{2},,{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}",
                                          gen.ToString(),
                                          combo,
                                          damage.ToString(),
                                          genes[0],
                                          genes[1],
                                          genes[2],
                                          genes[3],
                                          genes[4],
                                          genes[5],
                                          genes[6],
                                          genes[7],
                                          genes[8],
                                          genes[9]));
                w.Flush();

                return(damage);
            });

            var selection = new EliteSelection();

            var crossover = new UniformCrossover(0.5f);

            var mutation = new ReverseSequenceMutation();

            var termination = new FitnessStagnationTermination(5000);

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

            ga.Termination         = termination;
            ga.MutationProbability = 0.7f;

            Console.WriteLine("Generation: combo = damage");

            var latestFitness = 0.0;

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

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    string combo = combogen.generateGeneticCombo(bestChromosome.ToFloatingPoints(), 0);

                    Console.WriteLine("Generation {0,2}: {1} = {2}",
                                      ga.GenerationsNumber,
                                      combo,
                                      bestFitness
                                      );
                }

                gen++;
            };

            ga.Start();

            Console.ReadKey();
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: cameronwhite08/GeneticAlg
        public static void Main(string[] args)
        {
            //represents a sample in the population
            var chromosome = new FloatingPointChromosome(
                //min values array
                Enumerable.Repeat(0.0, GoalString.Length).ToArray(),
                //max values array
                Enumerable.Repeat(25.0, GoalString.Length).ToArray(),
                //bits nneded array
                Enumerable.Repeat(5, GoalString.Length).ToArray(),
                //decimals required array
                Enumerable.Repeat(0, GoalString.Length).ToArray()
                );

            //create the population
            var population = new Population(4, 8, chromosome);

            //define a fitness function
            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();

                var numCorrect = 0;
                for (int i = 0; i < GoalString.Length; i++)
                {
                    var intVersion = Convert.ToInt32(values[i]);
                    if (intVersion == GoalString[i] - 'a')
                    {
                        numCorrect++;
                    }
                }

                return(Convert.ToInt64(Math.Pow(2, numCorrect)));
            });

            //select the top performers for reproduction
            var selection = new EliteSelection();

            //get half of genetic material from each parent
            var crossover = new UniformCrossover(.5f);

            //our numbers are internally represented as binary strings, randomly flip those bits
            var mutation = new FlipBitMutation();

            //stop mutating when there the goal is met (paried definition with fitness function)
            var termination = new FitnessThresholdTermination(Math.Pow(2, GoalString.Length));

            //put the genetic algorithm together
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            //print out the top performer of the population
            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = Convert.ToInt32(bestChromosome.Fitness.Value);

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

                var ints = phenotype.Select(Convert.ToInt32).ToArray();

                var bestString = ConvertIntArrayToString(ints);

                Console.WriteLine($"Best string: {bestString}");
            };

            ga.TerminationReached += (sender, eventArgs) => { Console.WriteLine("Finished Evolving"); };

            ga.Start();

            Console.ReadKey();
        }
コード例 #10
0
        static void Main(string[] args)
        {
            float maxWidth  = 998f;
            float maxHeight = 680f;

            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)));
            });
            //TODO посмотреть, сколькл хромосом из общего числа выбрано
            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;
                //TODO если фитнес равна нулю, мы ее можем записывать

                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();
        }
コード例 #11
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();
        }
コード例 #12
0
        private void Iniciar_Click(object sender, RoutedEventArgs e)
        {
            Bitmap bmpDest = new Bitmap(bmpObj.Width, bmpObj.Height);

            Int32[] solucion = new Int32[bmpObj.Width * bmpObj.Height];
            int     i        = 0;

            for (int y = 0; y < bmpObj.Height; y++)
            {
                for (int x = 0; x < bmpObj.Width; x++)
                {
                    System.Drawing.Color color = bmpObj.GetPixel(x, y);
                    solucion[i] = color.ToArgb();
                    i++;
                    //bmpDest.SetPixel(x, y, System.Drawing.Color.FromArgb(acolor));
                }
            }

            int tam = bmpObj.Width * bmpObj.Height;

            double[] minArray = new double[tam];
            double[] maxArray = new double[tam];
            int[]    bits     = new int[tam];
            int[]    b2       = new int[tam];
            for (int j = 0; j < tam; j++)
            {
                minArray[j] = -16777216;
                maxArray[j] = -1;
                bits[j]     = 64;
                b2[j]       = 0;
            }
            var chromosome = new FloatingPointChromosome(
                minArray,
                maxArray,
                bits,
                b2
                );

            var fitness = new FuncFitness((c) =>
            {
                var fc          = c as FloatingPointChromosome;
                double[] values = fc.ToFloatingPoints();
                //Int32[] valuesAux = new Int32[values.Length];
                //for (int b = 0; b < values.Length; b++) {
                //   valuesAux[b] = Convert.ToInt32(values[b]);
                //}
                double acum;
                acum = 0;
                for (int j = 0; j < values.Length; j++)
                {
                    byte[] bA  = BitConverter.GetBytes(Convert.ToInt32(values[j]));
                    byte[] bA2 = BitConverter.GetBytes(solucion[j]);
                    int ac     = 0;
                    for (int b = 0; b < 4; b++)
                    {
                        ac += Math.Abs(bA[b] - bA2[b]);
                    }
                    acum += ac;
                }
                if (acum == 0)
                {
                    return(Int32.MaxValue);
                }
                else
                {
                    return(1 / acum);
                }
            }
                                          );

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

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.7f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(1000);

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

            ga.Termination = termination;



            var latestFitness = 0.0;

            ga.MutationProbability = 0.3f;
            ga.GenerationRan      += (a, b) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

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

                    Dispatcher.BeginInvoke((Action)(() =>
                    {
                        int pos = 0;
                        for (int y = 0; y < bmpObj.Height; y++)
                        {
                            for (int x = 0; x < bmpObj.Width; x++)
                            {
                                var aas = phenotype[pos];
                                bmpDest.SetPixel(x, y, System.Drawing.Color.FromArgb(Convert.ToInt32(phenotype[pos])));
                                pos++;
                            }
                        }
                        BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                            bmpDest.GetHbitmap(),
                            IntPtr.Zero,
                            System.Windows.Int32Rect.Empty,
                            BitmapSizeOptions.FromWidthAndHeight(bmpDest.Width, bmpDest.Height));
                        ImageBrush ib = new ImageBrush(bs);
                        Destino.Source = bs;


                        //Resta
                        Bitmap resta = new Bitmap(bmpObj.Width, bmpObj.Height);
                        pos = 0;
                        for (int y = 0; y < bmpObj.Height; y++)
                        {
                            for (int x = 0; x < bmpObj.Width; x++)
                            {
                                if (phenotype[pos] - solucion[pos] != 0)
                                {
                                    resta.SetPixel(x, y,
                                                   System.Drawing.Color.FromArgb(-16777216)
                                                   );
                                }

                                pos++;
                            }
                        }
                        BitmapSource bs2 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                            resta.GetHbitmap(),
                            IntPtr.Zero,
                            System.Windows.Int32Rect.Empty,
                            BitmapSizeOptions.FromWidthAndHeight(bmpDest.Width, bmpDest.Height));
                        RestaM.Source = bs2;
                    }));
                }
            };

            Task.Run(() => {
                ga.Start();
            });
        }
コード例 #13
0
        public void TestMethod1()
        {
            float maxWidth  = 998f;
            float maxHeight = 680f;

            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();

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

            ga.Start();
        }
コード例 #14
0
        public static void BuildTestGA()
        {
            //Create chromosome length = 20
            BinaryChromosome chrom = new BinaryChromosome(20);

            //Create population = [2,100]
            var population = new Population(2, 100, chrom);

            //Console.WriteLine(chrom.Length);
            //Console.WriteLine(chrom.ToString());

            //create Fitness Function (функция приспособления)
            var fitness = new FuncFitness(
                (c) =>
            {
                var fc        = c as BinaryChromosome;
                double result = 0.0;
                foreach (Gene gene in fc.GetGenes())
                {
                    result += Convert.ToDouble(gene.Value.ToString());
                }
                return(result);
            }
                );


            //create selection
            //var selection = new EliteSelection();
            var selection = new TournamentSelection();
            //var selection = new RouletteWheelSelection();
            //var selection = new StochasticUniversalSamplingSelection();

            //create crossover
            var crossover = new UniformCrossover(0.5f);
            //var crossover = new CutAndSpliceCrossover(); //только с EliteSelection()
            //var crossover = new OnePointCrossover();
            //var crossover = new TwoPointCrossover();
            //var crossover = new CycleCrossover(); // new OrderBasedCrossover(); new OrderedCrossover(); new PositionBasedCrossover(); new PartiallyMappedCrossover(); //может использоваться только с упорядоченными хромосомами. Указанная хромосома имеет повторяющиеся гены
            //var crossover = new ThreeParentCrossover(); //ОДНУ Итерацию выполняет

            //create mutation
            var mutation = new FlipBitMutation();
            //var mutation = new UniformMutation(); //1 перегрузка принимает индексы генов для мутации, 2-я все гены мутируют
            //var mutation = new TworsMutation(); //Слабая
            //var mutation = new ReverseSequenceMutation(); //Слабая


            //create termination (Количество итераций)
            var termination = new GenerationNumberTermination(100);
            //var termination = new FitnessStagnationTermination(50);
            // var termination = new FitnessThresholdTermination(50); //Постоянно зацикливается
            //TimeSpan time = new TimeSpan(0, 0, 10); //10 секунд
            //var termination = new TimeEvolvingTermination(time);

            //Сам генетический алгоритм
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            Console.WriteLine("Generation:  = distance");

            var latestFitness = 0.0;

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

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

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

                    Console.WriteLine("Generation {0,2}. Best Fitness = {1}", ga.GenerationsNumber, bestFitness);
                    Console.Write("Chromosome: ");

                    foreach (Gene g in phenotype)
                    {
                        Console.Write(g.Value.ToString() + "");
                    }
                    Console.WriteLine();
                }
            };

            ga.Start();
        }
コード例 #15
0
        public static wynikGA Genetic(int counter, Item[] dane, double back_volume)
        {
            double[] minValue       = new double[counter];
            double[] maxValue       = new double[counter];
            int[]    totalBits      = new int[counter];
            int[]    fractionDigits = new int[counter];


            for (int i = 0; i < counter; i++)
            {
                minValue[i]       = 0;
                maxValue[i]       = 1;
                totalBits[i]      = 16;
                fractionDigits[i] = 4;
            }

            var selection  = new TournamentSelection(50, true);
            var crossover  = new TwoPointCrossover();
            var mutation   = new FlipBitMutation();
            var chromosome = new FloatingPointChromosome(minValue, maxValue, totalBits, fractionDigits);
            // var fitobj = new MyProblemFitness(dane, chromosome, back_volume);
            //var fitness = fitobj.Evaluate;
            var population = new Population(500, 500, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;
                //var _items = dane;
                //var _bvol = back_volume;

                /* 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));
                 *
                 */

                //chromosome.ReplaceGenes(0, chromosome.GetGenes());
                double[] proc_wag          = fc.ToFloatingPoints();
                double suma_spakowanych    = 0;
                double wartosc_spakowanych = 0;
                for (int i = 0; i < proc_wag.Length; i++)
                {
                    suma_spakowanych    += dane[i].item_volume * proc_wag[i];
                    wartosc_spakowanych += dane[i].item_value * proc_wag[i];
                }

                if (suma_spakowanych <= back_volume)
                {
                    double temp = (wartosc_spakowanych * (suma_spakowanych / back_volume));
                    if (temp < 0)
                    {
                        if (Experiments.doOutput)
                        {
                            System.Console.WriteLine("LOL ");
                        }
                    }
                }


                return((suma_spakowanych <= back_volume) ? (wartosc_spakowanych * (suma_spakowanych / back_volume)) : (-suma_spakowanych));
            });



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

            ga.Termination = new GenerationNumberTermination(100);

            if (Experiments.doOutput)
            {
                System.Console.WriteLine("GA running...");
            }
            ga.MutationProbability  = 0.05f;
            ga.CrossoverProbability = 0.20f;
            //ga.Selection.
            ga.Start();

            // FITNESS  if (Experiments.doOutput) System.Console.WriteLine("Best solution found has fitness = " + ga.BestChromosome.Fitness);
            wynikGA w = new wynikGA();

            w.ga = ga;
            w.ch = chromosome;
            w.ch.ReplaceGenes(0, ga.BestChromosome.GetGenes());

            return(w);
        }
コード例 #16
0
ファイル: GA.cs プロジェクト: wangpei421/GeneticSharp
        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;
        }
コード例 #17
0
        static void Main(string[] args)
        {
            TestData.GetData(out var servers, out var services);

            var chromosome = new MyChromosome(servers, services);

            var populationSize = 9;
            var population     = new Population(populationSize, populationSize, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var mc = (MyChromosome)c;

                var genes   = mc.GetGenes();
                var servers = genes.Select(x => (Server)x.Value).ToList();

                var freeServersTerm     = servers.Count(x => x.IsFree) * 2.5;
                var negativeHddFreeTerm = servers.Where(x => x.HddFree < 0).Select(x => x.HddFree * 3).Sum();
                var positiveHddFreeTerm = servers.Where(x => x.HddFree > 0).Select(x => x.HddFree * 0.2).Sum();
                var negativeRamFreeTerm = servers.Where(x => x.RamFree < 0).Select(x => x.RamFree * 3).Sum();
                var positiveRamFreeTerm = servers.Where(x => x.RamFree > 0).Select(x => x.RamFree * 0.2).Sum();
                var negativeCpuFreeTerm = servers.Where(x => x.CpuFree < 0).Select(x => x.CpuFree * 3).Sum();
                var positiveCpuFreeTerm = servers.Where(x => x.CpuFree > 0).Select(x => x.CpuFree * 0.2).Sum();

                var fitness = freeServersTerm + negativeHddFreeTerm + positiveHddFreeTerm + negativeRamFreeTerm +
                              positiveRamFreeTerm + negativeCpuFreeTerm + positiveCpuFreeTerm;

                //по каждому серверу нужно вычислить коэффициент заполненности
                var serversFill = new List <double>();
                foreach (var server in servers)
                {
                    var serverFill = ((server.HddFull - server.HddFree) / server.HddFull) * 0.2 +
                                     ((server.RamFull - server.RamFree) / server.RamFull) * 0.4 +
                                     ((server.CpuFull - server.CpuFree) / server.CpuFull) * 0.4;
                    serversFill.Add(serverFill);
                }
                serversFill = serversFill.OrderByDescending(x => x).ToList();
                //отладочная строка
                //var serversFill = new List<double> { 0.9d, 0.9d, 0.6d, 0.2d,0 };
                //среднее значение заполненности серверов
                var averageFill = serversFill.Sum() / servers.Count();
                //рассчитаем дисперсию у serversFill
                var dispersion = serversFill.Select(eachFill => (eachFill - averageFill) * (eachFill - averageFill)).Sum() / servers.Count;

                return((dispersion * 3) + fitness);
            });

            var selection = new EliteSelection();
            //сделал свой кроссовер, похожий на UniformCrossover
            var crossover = new MyCrossover();
            //строка для отладки кроссовера
            //crossover.Cross(new List<IChromosome> {chromosome.CreateNew(), chromosome.CreateNew()});

            var mutation = new MyMutation();
            //mutation.Mutate(chromosome, Single.Epsilon);

            var termination = new FitnessStagnationTermination(100);

            var ga = new GeneticSharp.Domain.GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation)
            {
                Termination         = termination,
                MutationProbability = 0.3f
            };

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var ga = (GeneticSharp.Domain.GeneticAlgorithm)sender;
                Console.Write("Номер итерации: " + ga.GenerationsNumber + "  " + "Время работы: " + ga.TimeEvolving);
                Console.WriteLine();

                var bestChromosome = ga.BestChromosome as MyChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.GetGenes()
                                    .Select(x => (Server)x.Value).ToList();

                    Console.Write("Фитнес: " + bestFitness);
                    Console.WriteLine();

                    foreach (var server in phenotype)
                    {
                        Console.Write("Сервер: " + server.Name +
                                      ", HddFull: " + server.HddFull +
                                      ", RamFull: " + server.RamFull +
                                      ", HddFree: " + server.HddFree +
                                      ", RamFree: " + server.RamFree +
                                      ", CpuFree: " + server.CpuFree +
                                      ", сервисы: ");
                        Console.Write(" Заполненность Hdd: " + Math.Round(100 - (server.HddFree / server.HddFull * 100)) + "%");
                        Console.Write(" Заполненность Ram: " + Math.Round(100 - (server.RamFree / server.RamFull * 100)) + "%");
                        Console.Write(" Заполненность Cpu: " + Math.Round(100 - server.CpuFree) + "%");
                        foreach (var service in server.Services)
                        {
                            Console.Write(service.Name + ", ");
                        }
                        Console.WriteLine();
                        Console.WriteLine();

                        //получить хромосомы на этой итерации и смотреть, равны ли они.
                        //Хромосомы равны, если равны их фитнесы.
                        //Если равны, алгоритм преждевременно сходится (вырождается популяция)
                        var chromosomesFitnessCollection = ga.Population.CurrentGeneration.Chromosomes;
                    }
                }
            };

            ga.Start();
        }
コード例 #18
0
        static void Main(string[] args)
        {
            string cadena;        //cadena leida por el usuario
            int    tam_cadena;    //tamaño de la cadena introducida
            string cadenana = ""; //cadena resultante generada por el algoritmo

            Console.WriteLine("Introduzca la cadena");
            cadena     = Console.ReadLine();
            cadena     = cadena.Trim();             //se eliminan espacios de la cadena introducida
            cadena     = cadena.ToLower();          //se pasa a minusculas todas las letras
            tam_cadena = cadena.Length;             //se obtiene le tamaño de la caden
            double[] min  = new double[tam_cadena]; //se generan
            double[] max  = new double[tam_cadena]; //rangos minimos y maximos para que trabaje el AG
            int[]    arr  = new int[tam_cadena];    //se generan los arreglos
            int[]    arr2 = new int[tam_cadena];    // de numero de digits , bits

            for (int i = 0; i < tam_cadena; i++)    //se debe de llenar una posicion del arreglo por cada gen(cada caracter de la cadena )
            {
                min[i]  = 97;                       //minimo -> a
                max[i]  = 122;                      //maximo -> z
                arr[i]  = 64;
                arr2[i] = 3;
            }
            var cromosoma = new FloatingPointChromosome(min, max, arr, arr2); //se instancia la nueva cromosoma

            var aptitud = new FuncFitness((c) => {                            //se define la funcion de aptitud
                var fc         = c as FloatingPointChromosome;
                var x          = fc.ToFloatingPoints();
                string cad_obt = "";
                double porcentaje;
                for (int i = 0; i < tam_cadena; i++)        //para cada gen
                {
                    cad_obt += (char)Convert.ToInt32(x[i]); //se debe de concatenar a la cadena obtenida, convirtiendo de float a int y despues
                }
                //casteando a caracter
                double dist = Math.Exp(-LevenshteinDistance(cadena, cad_obt, out porcentaje)); //se realiza el calculo
                return(1f / 1f + dist);                                                        //de la aptitud
            });
            var poblacion   = new Population(100, 1000, cromosoma);                            //se crea la poblacon con minimo 100 individuos y maximo 1000
            var cruza       = new UniformCrossover(0.3f);                                      //se define como se realizara la cruza
            var mutacion    = new FlipBitMutation();                                           //como se realizara la mutacion
            var seleccion   = new RouletteWheelSelection();                                    //se elige el metodo de seleccion a utilizar
            var terminacion = new FitnessStagnationTermination(1000);                          //se determina el parametro de termino para el algoritmo genetico
            //var ga = new GeneticSharp
            var ga = new GeneticAlgorithm(poblacion, aptitud, seleccion, cruza, mutacion);     //se crea el algoritmo genetico

            ga.Termination = terminacion;                                                      //se asigna la condicion de termino a el AG

            var latestFitness = 0.0;                                                           //variable para guardar fitness anterior

            ga.GenerationRan += (sender, e) =>                                                 //funcion para estar verificando como es que evoluciona el AG
            {
                var bestchromosome = ga.BestChromosome as FloatingPointChromosome;             //se obtiene la cromosoma
                var bestFitness    = bestchromosome.Fitness.Value;                             //se obtiene el fitness de la cromosoma

                if (bestFitness != latestFitness)                                              //se comprueba que el fitness actual sea distinto al anterior
                {
                    latestFitness = bestFitness;                                               //el anterior fitness se vuelve el mejor ahora, para asi comprobar que le fitness mejora
                    // var phenotype = bestchromosome.ToFloatingPoints();//se obtienen los valores que reprsenta la cromosoma

                    Console.WriteLine("Generation {0}", ga.GenerationsNumber); //se imprime el numero de generacion
                    // Console.WriteLine("X = {0}", bestchromosome.ToFloatingPoint());
                    var x = bestchromosome.ToFloatingPoints();                 //se obtienen los valores que reprsenta la cromosoma
                    cadenana = "";
                    for (int i = 0; i < tam_cadena; i++)                       //se obtiene el valor
                    {
                        cadenana += (char)Convert.ToInt32(x[i]);               // que representa el fenotipo en terminos de caracteres para
                    }
                    //formar la cadena resultante

                    //  Console.WriteLine("F(x) =  {0}", (char)((int)bestFitness));
                    Console.WriteLine("Palabra Obtenida " + cadenana);//imprime la mejor aproximacion hasta ahora
                }
            };
            ga.Start();                                                                             //se Inicia el AG
            Console.WriteLine("\nEjecucion Terminada \n");
            Console.WriteLine("La Mejor Aproximacion a la solucion encontrada es :\n " + cadenana); //se imprime la mejor solucion encontrada
            Console.ReadLine();                                                                     //esto es para hacer un pausa y se pueda ver el resultado tranquilamente
        }
コード例 #19
0
        static void Main(string[] args)
        {
            float largMax = 998f; //largura maxima ou maxWidht do retângulo
            float altMax  = 680f; //altura maxima ou maxHeight do retângulo


            var cromossomo = new FloatingPointChromosome //Criando um cromossomo de distância euclidiana
                             (
                new double[] { 0, 0, 0, 0 },
                new double[] { largMax, altMax, largMax, altMax },
                new int[] { 10, 10, 10, 10 },
                new int[] { 0, 0, 0, 0 }
                             );

            var population = new Population(50, 100, cromossomo); // população, de no minimo 50 e no maximo 100, criada usando o cromossomo

            var fitness = new FuncFitness((c) =>                  // criando uma função fitness
            {
                var fc = c as FloatingPointChromosome;

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

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

            var peneira = new EliteSelection();                                                   // seletor "peneira" do tipo ELITE ou seja só os melhores passarão >>>> Besides this, you can use the already implemented classic selections: Elite, Roulete Wheel, Stochastic Universal Sampling and Tournament.

            var crossover = new UniformCrossover(0.5f);                                           // aqui ocorre a união dos cromossomos para gerar novas possibilidades de soluções da proxima geração

            var mutacao = new FlipBitMutation();                                                  // classe de mutação

            var terminator = new FitnessStagnationTermination(100);                               // essa parte passa uma "régua" no cromossomo e para de executar quando ele gera o melhor cromossomo 100 vezes.

            var creator = new GeneticAlgorithm(population, fitness, peneira, crossover, mutacao); // instaciei o algoritmo genetico>>>>

            creator.Termination = terminator;                                                     // parametros de terminação passados atraves do terminator

            //creator.Start();// mando ele iniciar o algoritmo daqui pra baixo da pra apagar que vai funcionar

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

            var latestFitness = 0.0;

            creator.GenerationRan += (sender, e) =>
            {
                var bestChromosome = creator.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}",
                        creator.GenerationsNumber,
                        phenotype[0],
                        phenotype[1],
                        phenotype[2],
                        phenotype[3],
                        bestFitness
                        );
                }
            };

            creator.Start();

            Console.ReadKey();
        }
コード例 #20
0
        public void functionOptimizationWithGeneticsharp()
        {
            /* example from
             * http://diegogiacomelli.com.br/function-optimization-with-geneticsharp/
             */
            float maxWidth  = 998f;
            float maxHeight = 680f;

            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0 },
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
                new int[] { 12, 12, 12, 12 },
                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 RouletteWheelSelection();
            var crossover   = new ThreeParentCrossover();
            var mutation    = new PartialShuffleMutation();
            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();
                    var s         = string.Format("Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                                                  ga.GenerationsNumber,
                                                  phenotype[0],
                                                  phenotype[1],
                                                  phenotype[2],
                                                  phenotype[3],
                                                  bestFitness);
                    Console.WriteLine(
                        s
                        );
                }
            };

            ga.Start();
        }
コード例 #21
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();
        }