Skip to content

Commit

Permalink
Merge pull request #153 from jakobj/maint/simplify-individual
Browse files Browse the repository at this point in the history
Simplify Individual: move mutate() to Genome
  • Loading branch information
mschmidt87 committed Jun 17, 2020
2 parents 61108a3 + 642f19d commit 00b9389
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 50 deletions.
10 changes: 6 additions & 4 deletions cgp/cartesian_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,20 @@
except ModuleNotFoundError:
torch_available = False

from typing import Callable, DefaultDict, Dict, List, Optional, Set
from typing import Callable, DefaultDict, Dict, List, Optional, Set, TYPE_CHECKING

from .node import Node, InputNode, OutputNode, Parameter
from .genome import Genome

if TYPE_CHECKING:
from .genome import Genome


class CartesianGraph:
"""Class representing a particular Cartesian graph defined by a
Genome.
"""

def __init__(self, genome: Genome) -> None:
def __init__(self, genome: "Genome") -> None:
"""Init function.
Parameters
Expand Down Expand Up @@ -95,7 +97,7 @@ def empty_node_str() -> str:

return s

def parse_genome(self, genome: Genome) -> None:
def parse_genome(self, genome: "Genome") -> None:
if genome.dna is None:
raise RuntimeError("dna not initialized")

Expand Down
20 changes: 11 additions & 9 deletions cgp/genome.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from typing import DefaultDict, Generator, List, Optional, Tuple, Type

from .cartesian_graph import CartesianGraph
from .node import Node
from .primitives import Primitives

Expand Down Expand Up @@ -355,25 +356,26 @@ def _is_active_input_gene(self, gene_idx: int) -> bool:
else:
assert False # should never be reached

def mutate(self, n_mutations: int, active_regions: List[int], rng: np.random.RandomState):
def mutate(self, mutation_rate: float, rng: np.random.RandomState):
"""Mutate the genome.
Parameters
----------
n_mutations : int
Number of entries in the genome to be mutated.
active_regions: List[int]
Regions in the genome that are currently used in the
computational graph. Used to check whether mutations are
silent or require reevaluation of fitness.
mutation_rate : float
Proportion of genes to be mutated, between 0 and 1.
rng : numpy.random.RandomState
Random number generator instance to use for crossover.
Returns
----------
True if only inactive regions of the genome were mutated, False otherwise.
bool
True if only inactive regions of the genome were mutated, False otherwise.
"""
assert isinstance(n_mutations, int) and 0 < n_mutations
n_mutations = int(mutation_rate * len(self.dna))
assert n_mutations > 0

graph = CartesianGraph(self)
active_regions = graph.determine_active_regions()

successful_mutations = 0
only_silent_mutations = True
Expand Down
38 changes: 1 addition & 37 deletions cgp/individual.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,46 +59,10 @@ def update_parameters_from_torch_class(self, torch_cls):

@staticmethod
def _mutate_genome(genome: Genome, mutation_rate: float, rng: np.random.RandomState) -> bool:
"""Mutate a given genome.
Parameters
----------
genome : Genome
Genome to be mutated.
mutation_rate : float
Proportion of genes to be mutated, between 0 and 1.
rng : numpy.RandomState
Random number generator instance.
Returns
-------
bool
Whether all mutations were silent.
"""
n_mutations = int(mutation_rate * len(genome.dna))
assert n_mutations > 0

graph = CartesianGraph(genome)
active_regions = graph.determine_active_regions()
only_silent_mutations = genome.mutate(n_mutations, active_regions, rng)

return only_silent_mutations
return genome.mutate(mutation_rate, rng)

@staticmethod
def _randomize_genome(genome: Genome, rng: np.random.RandomState) -> None:
"""Randomize the individual's genome.
Parameters
----------
genome : Genome
Genome to be randomized.
rng : numpy.RandomState
Random number generator instance to use for crossover.
Returns
-------
None
"""
genome.randomize(rng)

@staticmethod
Expand Down

0 comments on commit 00b9389

Please sign in to comment.