Skip to content

Commit

Permalink
Merge pull request #390 from Happy-Algorithms-League/enh/faster-mutate
Browse files Browse the repository at this point in the history
Slightly improve performance of `mutate`
  • Loading branch information
jakobj authored Mar 29, 2024
2 parents dd6b262 + be7bd2e commit 9c3db00
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions cgp/genome.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,15 +750,25 @@ def mutate(self, mutation_rate: float, rng: np.random.RandomState):
selected_gene_indices = self._select_gene_indices_for_mutation(mutation_rate, rng)

for (gene_idx, allele) in zip(selected_gene_indices, np.array(dna)[selected_gene_indices]):
permissible_values = self._permissible_values[gene_idx]

region_idx = self._get_region_idx(gene_idx)
if len(permissible_values) == 0:
raise RuntimeError("should have at least one permissible value")
elif len(permissible_values) == 1:
assert permissible_values[0] == allele
continue # since we have no new choice there's nothing to do here
else:
rng.shuffle(permissible_values)

permissible_values = self._permissible_values[gene_idx]
permissible_alternative_values = permissible_values[permissible_values != allele]
# we have at least two permissible values, we pick the one
# that's different from the current one
if permissible_values[0] != allele:
dna[gene_idx] = permissible_values[0]
else:
dna[gene_idx] = permissible_values[1]

if len(permissible_alternative_values) > 0:
region_idx = self._get_region_idx(gene_idx)

dna[gene_idx] = rng.choice(permissible_alternative_values)
modified_parameter_value: bool
if self._is_function_gene(gene_idx):
region_idx = self._get_region_idx(gene_idx)
Expand Down

0 comments on commit 9c3db00

Please sign in to comment.