giacomelli / GeneticSharp

GeneticSharp is a fast, extensible, multi-platform and multithreading C# Genetic Algorithm library that simplifies the development of applications using Genetic Algorithms (GAs).
MIT License
1.26k stars 330 forks source link

exception for fitness <=0 #94

Closed FilRav closed 1 year ago

FilRav commented 2 years ago

The chromosome cannot be selected (at least in RouletteWheelSelection), resulting in a population of even only 1 chromosome.

giacomelli commented 1 year ago

There are some scenarios where a chromosome's scores can be lower than 0. If we add this change we can make these scenarios unfeasible.

Can you provide a code sample showing the problem that you faced?

FilRav commented 1 year ago

Having 4 chromosomes with fitness -1, +1, -2, +2 the fitness sum is 0. The instruction https://github.com/giacomelli/GeneticSharp/blob/master/src/GeneticSharp.Domain/Selections/RouletteWheelSelection.cs#L82 will do a divide by 0. In this example with a score = fitness+3 or score = fitness*fitness+1, etc. the sum is not 0 and the problem is solved. Since you cannot have positive and negative values and be sure to have a sum != 0, each value must be strictly positive as well, hence my PR.

giacomelli commented 1 year ago

For this specific case, you should create your own implementation of IFitness or, at least, perform the validation that you want inside your FuncFitness callback usage.

As mentioned before there are some scenarios where a chromosome's scores can be lower than 0, so, this PR cannot be accepted.

FilRav commented 1 year ago

I thought it was better to catch the problem early with improper fitness calculation instead maybe an hour later when the assert fails for an unexpected division by zero (for RouletteWheelSelection case). Thank you anyway.