Hide Comments
Hide Comments

Comments (0)

Occurs when the    EvaluateFitness method is called. Use the OnEvaluateFitness event to define your fitness function for the genetic algorithm. Defining your fitness function is another highly important part of defining a genetic algorithm. The fitness function returns a floating point value that specifies the correctness of the individual solution. The fitness function needs to be able to allow the genetic component to decide which solution is better than another. The genetic component will seek to either maximize the solution (e.g., keep evolving for individuals whose fitness are greater than other individuals in the population) or to minimize the solution (e.g., find the individuals whose fitness are less than other individuals). Note you can specify which direction to evolve towards with the    FitnessMethod property.

Use the OnEvaluateFitness event to calculate each TRSIndividual's fitness level. Without an OnEvaluateFitness event handler all individuals in the population will have a default Fitness of 0. Every generation, when the Evolve method is called, the OnEvaluateFitness event will occur Population.Count number of times.

Namespace: RSGeneticBase



  property OnEvaluateFitness: TRSFitnessEvent read FOnEvaluateFitness write FOnEvaluateFitness;


Type: TRSFitnessEvent


For the 8-queens problem, the fitness function calculates the number of non-attacking pairs of queens. A completely solved solution would be 28 non-attacking pairs of queens.

To define your fitness function, you need to define an OnEvaluateFitness event handler:


procedure TForm1.RSGeneticAlgorithm1EvaluateFitness(Sender: TObject;
   const Item: TRSGAIndividual; var Fitness: TGAFitness);
    i: Integer;
    j: Integer;
    Queen: Integer;
    newQueen: Integer;
    d1, d2: Integer;
      // fitness function for 8 queens problem is the number of non-attacking
      // pairs of queens (perfect is 28)
      Fitness := 0;
      with Sender as TRSGeneticAlgorithm do
      for i := 0 to Genes.Count - 2 do
           Queen := Genes[i].AsInteger[Item.Index];
           if Queen >= NUM_QUEENS then Fitness := Fitness - 1;
           d1 := Queen + 1;
           d2 := Queen - 1;
           for j := i + 1 to Genes.Count - 1 do
                NewQueen := Genes[j].AsInteger[Item.Index];
                if NewQueen >= NUM_QUEENS then Fitness := Fitness - 1;
                if (NewQueen <> Queen) and (NewQueen <> d1) and (NewQueen <> d2) then
                   Fitness := Fitness + 1;

expandingSee Also

Comments (0)