Пример #1
0
        private GeneticAlgorithm PrepareGeneticAlgorithm(string[][] board)
        {
            double[][] parsedBoard = this.ParseBoardToDouble(board);

            var chromosome = new TicTacToeChromosome(parsedBoard);
            var population = new Population(50, 100, chromosome);
            var fitness    = new TicTacToeFitness
            {
                Minimum = BOARD_SIZE
            };
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new UniformMutation();
            var termination = new OrTermination(new ITermination[]
            {
                new FitnessStagnationTermination(3000),
                new FitnessThresholdTermination(4),
                new FitnessThresholdTermination(3),
                new FitnessThresholdTermination(2)
            });

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

#if DEBUG
            geneticAlgorithm.GenerationRan += (sender, e) =>
            {
                var bestChromosome = geneticAlgorithm.BestChromosome as TicTacToeChromosome;
                Console.WriteLine($"Generation { geneticAlgorithm.GenerationsNumber }: Position ({ bestChromosome.Position.X }, { bestChromosome.Position.Y }) = { bestChromosome.Fitness }");
            };
#endif
            return(geneticAlgorithm);
        }
Пример #2
0
        public void AddTermination_Null_Exception()
        {
            var target = new OrTermination();

            ExceptionAssert.IsThrowing(new ArgumentNullException("termination"), () =>
            {
                target.AddTermination(null);
            });
        }
        public ITermination Or()
        {
            var target = new OrTermination(_falseTermination, _trueTermination);
            var ga     = Substitute.For <IGeneticAlgorithm>();

            target.HasReached(ga);

            return(target);
        }
        public void AddTermination_Null_Exception()
        {
            var target = new OrTermination();
            var actual = Assert.Catch <ArgumentNullException>(() =>
            {
                target.AddTermination(null);
            });

            Assert.AreEqual("termination", actual.ParamName);
        }
Пример #5
0
        public void ToString_NoArgs_State()
        {
            var t1 = new AndTermination();
            var t2 = new OrTermination();
            var t3 = new AndTermination();

            var target = new AndTermination(t1, t2, t3);

            Assert.AreEqual("AndTermination (AndTermination (), OrTermination (), AndTermination ())", target.ToString());
        }
        public void HasReached_LessThan2Terminations_Exception()
        {
            var target = new OrTermination();

            target.AddTermination(Substitute.For <ITermination>());

            Assert.Catch <InvalidOperationException>(() =>
            {
                target.HasReached(Substitute.For <IGeneticAlgorithm>());
            }, "The OrTermination needs at least 2 terminations to perform. Please, add the missing terminations.");
        }
Пример #7
0
        public void HasReached_LessThan2Terminations_Exception()
        {
            var target = new OrTermination();

            target.AddTermination(MockRepository.GenerateMock <ITermination>());

            ExceptionAssert.IsThrowing(new InvalidOperationException("The OrTermination needs at least 2 terminations to perform. Please, add the missing terminations."), () =>
            {
                target.HasReached(MockRepository.GenerateMock <IGeneticAlgorithm>());
            });
        }
Пример #8
0
    private IList <CheckersMove> GetNewMoves()
    {
        int attempts = m_maxMoveAttempts;

        var termination =
            new OrTermination(
                new FitnessStagnationTermination(10),
                new AndTermination(
                    new FitnessThresholdTermination(0.1),
                    new GenerationNumberTermination(GA.GenerationsNumber + 20)
                    )
                );

        GA.Termination = termination;
        Debug.Log("Running GA...");

        if (GA.State == GeneticAlgorithmState.NotStarted)
        {
            GA.Start();
        }
        else
        {
            GA.Resume();
        }


        Debug.Log("Fitness: " + GA.BestChromosome.Fitness);
        Debug.Log("Generations: " + GA.GenerationsNumber);

        if (GA.BestChromosome.Fitness <= 0)
        {
            Debug.LogError("Lower than zero.");
        }

        attempts--;

        if (GA.BestChromosome.Fitness == 0)
        {
            HudController.IsGameOver = true;
        }

        return((GA.BestChromosome as CheckersChromosome).Moves);
    }
        public void HasReached_OnlyOneTerminationsHasReached_True()
        {
            var target = new OrTermination();
            var ga     = Substitute.For <IGeneticAlgorithm>();

            var t1 = Substitute.For <ITermination>();

            t1.HasReached(ga).ReturnsForAnyArgs(false);
            target.AddTermination(t1);

            var t2 = Substitute.For <ITermination>();

            t2.HasReached(ga).ReturnsForAnyArgs(true);
            target.AddTermination(t2);

            var t3 = Substitute.For <ITermination>();

            t3.HasReached(ga).ReturnsForAnyArgs(false);
            target.AddTermination(t3);

            Assert.IsTrue(target.HasReached(ga));
        }
Пример #10
0
        public void HasReached_OnlyOneTerminationsHasReached_True()
        {
            var target = new OrTermination();
            var ga     = MockRepository.GenerateMock <IGeneticAlgorithm>();

            var t1 = MockRepository.GenerateMock <ITermination>();

            t1.Expect(t => t.HasReached(ga)).IgnoreArguments().Return(false);
            target.AddTermination(t1);

            var t2 = MockRepository.GenerateMock <ITermination>();

            t2.Expect(t => t.HasReached(ga)).IgnoreArguments().Return(true);
            target.AddTermination(t2);

            var t3 = MockRepository.GenerateMock <ITermination>();

            t3.Expect(t => t.HasReached(ga)).IgnoreArguments().Return(false);
            target.AddTermination(t3);

            Assert.IsTrue(target.HasReached(ga));
        }
Пример #11
0
        public Test UseAlgorithm(List <int> oblasti, List <double> zastupljenost, int Test_Length)
        {
            Random      r          = new Random(10);
            IDataAccess dataAccess = DataAccess.DataAccess.GetInstance();

            List <Question> qs = new List <Question>();

            for (int i = 0; i < Test_Length; i++)
            {
                qs.Add(dataAccess.GetQuestionById(1 + r.Next(1000)));
            }

            Test adamTest = new Test(qs, Test_Length);

            List <double> zastupljenost_kao_br_pitanja = new List <double>();

            foreach (var vrednost in zastupljenost)
            {
                zastupljenost_kao_br_pitanja.Add(Math.Round(vrednost * Test_Length + 0.01));
            }

            var fitness = new TestFitness(oblasti, zastupljenost_kao_br_pitanja, 0);

            IGenerationStrategy generationStrategy = new PerformanceGenerationStrategy(3);
            var population = new TestPopulation(20, 50, adamTest, oblasti)
            {
                GenerationStrategy = generationStrategy
            };

            ISelection selection = new EliteSelection();

            ICrossover crossover = new TestCrossover(oblasti, zastupljenost_kao_br_pitanja, 8, 4);

            IMutation mutation = new TestMutation(oblasti, zastupljenost_kao_br_pitanja);

            ITermination termination = new OrTermination(new ITermination[] { new TestTermination(100, oblasti),
                                                                              new FitnessThresholdTermination(oblasti.Count),
                                                                              new GenerationNumberTermination(3000) });

            GeneticAlgorithm ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination          = termination,
                CrossoverProbability = 1f,
                MutationProbability  = 0.7f
            };


            double      oldFitness = 0;
            List <Test> tests      = new List <Test>();

            //Callback
            ga.GenerationRan += (sender, arg) =>
            {
                if (ga.BestChromosome.Fitness >= oldFitness)
                {
                    oldFitness = ga.BestChromosome.Fitness.Value;
                    tests.Add(ga.BestChromosome as Test);
                    //Console.WriteLine($"Current fitness: {ga.BestChromosome.Fitness} for generation : {ga.GenerationsNumber}");
                }
            };

            ga.Start();

            if (oldFitness == 0)
            {
                return(null);
            }
            var  lista          = tests.Where(x => !x.HasDuplicate()).OrderByDescending(x => x.Fitness.Value).ToList();
            Test bestChromosome = lista.FirstOrDefault();

            foreach (var q in bestChromosome.questions)
            {
                q.Izabrano = true;
            }

            return(bestChromosome);
        }
Пример #12
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();
        }