예제 #1
0
        public int Evaluate(Population population)
        {
            int evaluationCount = 0;

            FitnessEvaluator.OnStartEvaluation();
            bool solutionFound = false;

            Logger.WriteLine(2, "Evaluation: " + population.Size + " individuals");
            foreach (var individual in population.Individuals)
            {
                Logger.WriteLine(4, "tree height: " + individual.SyntaxTree.Height);
                if (!individual.FitnessEvaluated)
                {
                    Logger.WriteLine(2, "Evaluating individual... (" + evaluationCount + ")");
                    Logger.WriteLine(2, individual.SyntaxTree.ToString());
                    var result = FitnessEvaluator.Evaluate(individual, this);
                    individual.FitnessResult = result;
                    individual.Fitness       = result.Fitness;
                    if (!solutionFound)
                    {
                        evaluationCount++;
                    }
                    if (result.Fitness == 0)
                    {
                        // do not count further evaluations as this run is finished.
                        // anyway need to evaluate rest of population for sorting according to fitness.
                        solutionFound = true;
                    }
                }
            }
            FitnessEvaluator.OnEvaluationFinished();
            return(evaluationCount);
        }
예제 #2
0
        public DeploymentModel Run(DeploymentModel initialDeploymentModel)
        {
            var initialChromosome = ChromosomeFactory.Create(initialDeploymentModel);
            var population        = InitialPopulationCreator.CreateInitialPopulation(initialChromosome, MinPopulationSize, MaxPopulationSize);

            while (!TerminationCondition.HasReached(population, CurrentState))
            {
                var parents   = SelectionStrategyStrategy.SelectChromosomes(MinPopulationSize, population).ToArray();
                var offspring = Cross(parents).ToArray();
                offspring  = Mutate(offspring).ToArray();
                population = ReinsertionStrategy.Reinsert(offspring, population);
                foreach (var deployment in population.Deployments)
                {
                    deployment.Fitness = FitnessEvaluator.Evaluate(deployment, Workload);
                }
                CurrentState.UpdateOnGenerationRan(population);
            }
            return(population.BestDeployment.ToDeploymentModel());
        }
예제 #3
0
        public bool Mutate(Individual individual)
        {
            bool triedBackPropagation;
            bool mutated = ResultSemanticsOperator.Operate(DesiredSemantics, individual,
                                                           SubTreePool, MaxTreeDepth, out triedBackPropagation);

            double fitnessChange = 0;

            if (triedBackPropagation && individual.FitnessEvaluated && FitnessEvaluator != null)
            {
                double fitness = FitnessEvaluator.Evaluate(individual, Problem).Fitness;
                fitnessChange = fitness - individual.Fitness;
            }

            Statistics.Instance.AddBackpropagationAttemptMutation(triedBackPropagation, fitnessChange);
            if (!triedBackPropagation && Fallback != null)
            {
                return(Fallback.Mutate(individual));
            }
            return(mutated);
        }
예제 #4
0
        private Individual GenerateChildren(Individual individual1, Individual individual2,
                                            Semantics midpoint, out bool triedBackPropagation)
        {
            var child1 = new Individual(individual1);

            child1.FitnessEvaluated = false;

            var mutated = ResultSemanticsOperator.Operate(midpoint,
                                                          child1, SubTreePool, MaxTreeDepth, out triedBackPropagation);

            double fitnessChange = 0;

            if (mutated && triedBackPropagation && individual1.FitnessEvaluated && FitnessEvaluator != null)
            {
                double fitness = FitnessEvaluator.Evaluate(child1, Problem).Fitness;
                fitnessChange = fitness - individual1.Fitness;
            }
            Statistics.Instance.AddBackpropagationAttemptCrossover(triedBackPropagation, fitnessChange);

            return(mutated ? child1 : individual1);
        }
예제 #5
0
        public override bool Mutate(Individual individual)
        {
            SyntaxTree tree         = (SyntaxTree)individual.SyntaxTree.DeepClone();
            TreeNode   exchangeNode = tree.GetRandomNode();
            Type       nodeType     = exchangeNode.Type;

            TreeNode newNode = SyntaxTreeProvider.GetSyntaxTree(MaxMutationTreeDepth, nodeType);

            if (newNode != null)
            {
                bool replaced = tree.ReplaceTreeNode(exchangeNode, (TreeNode)newNode.DeepClone());
                if (replaced && tree.Height <= MaxTreeDepth)
                {
                    individual.SyntaxTree = tree;
                    if (individual.FitnessEvaluated)                            // only meaningful if fitness of individual is already evaluated
                    // update the node's record
                    {
                        var    recordSubTreePool = SyntaxTreeProvider as RecordBasedSubTreePool;
                        double improvement       = 0;
                        if (FitnessEvaluator != null)
                        {
                            var fitness = FitnessEvaluator.Evaluate(individual, Problem).Fitness;

                            improvement = fitness - individual.Fitness;
                            Statistics.Instance.AddRecordReplaceAttempt(improvement);
                        }
                        if (recordSubTreePool != null)
                        {
                            recordSubTreePool.UpdateRecord(newNode, improvement);
                        }
                    }
                    return(true);
                }
            }
            return(false);
        }
예제 #6
0
        /// <summary>
        /// Executes one iteration of EA
        /// </summary>
        /// <param name="pop">population for this iteration</param>
        public void Evolve(Population pop)
        {
            if (fitness == null)
            {
                throw new Exception("No fitness function defined");
            }

            generationNo++;

            // informative output
            if ((!Settings.parallel) && Settings.showGap >= 5 && (generationNo + 1) % (Settings.showGap / 5) == 0)
            {
                Console.Write("|");
            }

            fitness.Evaluate(pop, false);

            Population parents = pop;

            Population matingPool = new Population();

            // mating pool creation - if n selectors, each will select 1 / n of the pool
            if (matingSelectors.Count() > 0)
            {
                int mateSel  = matingSelectors.Count;
                int toSelect = parents.GetPopulationSize() / mateSel;
                for (int i = 0; i < matingSelectors.Count; i++)
                {
                    Population sel = new Population();
                    matingSelectors[i].Select(toSelect, parents, sel);
                    matingPool.AddAll((Population)sel.Clone());
                }

                int missing = parents.GetPopulationSize() - matingPool.GetPopulationSize();
                if (missing > 0)
                {
                    Population sel = new Population();
                    matingSelectors[matingSelectors.Count - 1].Select(toSelect, parents, sel);
                    matingPool.AddAll((Population)sel.Clone());
                }
            }
            else
            {
                matingPool = (Population)parents.Clone();
                matingPool.Shuffle();
            }

            // operators are executed in the order of specification
            Population offspring = null;

            foreach (Operator o in operators)
            {
                offspring = new Population();
                o.Operate(matingPool, offspring);
                matingPool = offspring;
            }

            // update of operator properties (if desired)
            foreach (Operator o in operators)
            {
                o.Update();
            }

            fitness.Evaluate(offspring, false);

            // selection process
            Population selected = new Population();

            Population combined = replacement.Replace(parents, offspring);

            if (environmentalSelectors.Count < 1)
            {
                selected = (Population)combined.Clone();
                fitness.Evaluate(combined, false);
            }
            else
            {
                List <Individual> sortedOld = parents.GetSortedIndividuals();
                for (int i = 0; i < eliteSize * parents.GetPopulationSize(); i++)
                {
                    selected.Add(sortedOld[i]);
                }

                fitness.Evaluate(combined, false);

                int envSel   = environmentalSelectors.Count;
                int toSelect = (parents.GetPopulationSize() - selected.GetPopulationSize()) / envSel;
                for (int i = 0; i < environmentalSelectors.Count; i++)
                {
                    Population sel = new Population();
                    environmentalSelectors[i].Select(toSelect, combined, sel);
                    selected.AddAll((Population)sel.Clone());
                }

                int missing = parents.GetPopulationSize() - selected.GetPopulationSize();
                if (missing > 0)
                {
                    Population sel = new Population();
                    environmentalSelectors[environmentalSelectors.Count - 1].Select(toSelect, combined, sel);
                    selected.AddAll((Population)sel.Clone());
                }
            }
            pop.Clear();
            pop.AddAll(selected);

            fitness.Evaluate(pop, true);
        }
예제 #7
0
    /// <summary>
    /// Moves a piece to another place on the board
    /// </summary>
    /// <param name="oldBoard"> the board before the piece is moved </param>
    /// <param name="pieceToMove"> the piece to be moved on the board </param>
    /// <param name="squareToMoveTo"> yhe square to move the piece to </param>
    public Move(char[] oldBoard, int pieceToMove, int squareToMoveTo)
    {
        from = pieceToMove;
        to   = squareToMoveTo;

        newBoard = new char[oldBoard.Length];


        for (int i = 0; i < newBoard.Length; i++)
        {
            if (i == squareToMoveTo)
            {
                //moves piece to new place
                newBoard[i] = oldBoard[pieceToMove];
            }
            else
            {
                //Just copy it over
                newBoard[i] = oldBoard[i];
            }
        }

        //Enpassant check
        if (to == BoardManager.Instance.enPassentIndex && char.ToUpper(oldBoard[from]) == 'P')
        {
            if (from > to && to + 8 < newBoard.Length)
            {
                //Moving downward
                newBoard[to + 8] = '\0';
                enpassentIndex   = to + 8;
            }
            else if (to - 8 >= 0)
            {
                //Moving upward
                newBoard[to - 8] = '\0';
                enpassentIndex   = to - 8;
            }
        }

        //Promotion Check
        if ((char.ToUpper(movedPiece) == 'P') && (to > 55 || to < 8))
        {
            //Promoted
            if (TurnManager.Instance.IsPlayerTurn())
            {
                //Prompt player for which piece they want
            }
            else
            {
                //Choose queen, as statistcally it is the best choice
                newBoard[to]  = (GameManager.Instance.playerTeam == PieceScript.Team.White) ? 'q' : 'Q';
                promotionType = PieceScript.Type.Queen;
            }
        }

        //Remove old piece
        newBoard[pieceToMove] = '\0';


        //Set Self Fitness
        self_fitness = FitnessEvaluator.Evaluate(newBoard);

        pathFitness = self_fitness;
    }