Skip to content

Commit

Permalink
Slightly improve performance of mutate
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobj committed Mar 29, 2024
1 parent 6ec03be commit 50f967a
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 50f967a

Please sign in to comment.