Skip to content

Commit

Permalink
Reduce time of single point crossover
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmedfgad committed Mar 28, 2024
1 parent a846a26 commit 4eba80b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
2 changes: 1 addition & 1 deletion pygad/utils/__init__.py
Expand Up @@ -3,4 +3,4 @@
from pygad.utils import mutation
from pygad.utils import nsga2

__version__ = "1.1.1"
__version__ = "1.2.1"
12 changes: 7 additions & 5 deletions pygad/utils/crossover.py
Expand Up @@ -25,10 +25,12 @@ def single_point_crossover(self, parents, offspring_size):
else:
offspring = numpy.empty(offspring_size, dtype=object)

# Randomly generate all the K points at which crossover takes place between each two parents. The point does not have to be always at the center of the solutions.
crossover_points = numpy.random.randint(low=0,
high=parents.shape[1],
size=offspring_size[0])
for k in range(offspring_size[0]):
# The point at which crossover takes place between two parents. Usually, it is at the center.
crossover_point = numpy.random.randint(low=0, high=parents.shape[1], size=1)[0]

# Check if the crossover_probability parameter is used.
if not (self.crossover_probability is None):
probs = numpy.random.random(size=parents.shape[0])
indices = numpy.where(probs <= self.crossover_probability)[0]
Expand All @@ -51,9 +53,9 @@ def single_point_crossover(self, parents, offspring_size):
parent2_idx = (k+1) % parents.shape[0]

# The new offspring has its first half of its genes from the first parent.
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, 0:crossover_points[k]] = parents[parent1_idx, 0:crossover_points[k]]
# The new offspring has its second half of its genes from the second parent.
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
offspring[k, crossover_points[k]:] = parents[parent2_idx, crossover_points[k]:]

if self.allow_duplicate_genes == False:
if self.gene_space is None:
Expand Down

0 comments on commit 4eba80b

Please sign in to comment.