Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for randomize_genome function of individual classes #190

Merged
merged 2 commits into from
Jul 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions cgp/population.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ def get_idx_for_new_individual(self) -> int:
def generate_random_individual(self) -> IndividualBase:
if isinstance(self._genome_params, dict):
genome: Genome = Genome(**self._genome_params)
genome.randomize(self.rng)
individual_s = IndividualSingleGenome(
fitness=None, genome=genome
) # type: IndividualBase # indicates to mypy that
Expand All @@ -93,15 +92,13 @@ def generate_random_individual(self) -> IndividualBase:
ind = individual_s
else:
genomes: List[Genome] = [Genome(**gd) for gd in self._genome_params]
for g in genomes:
g.randomize(self.rng)
individual_m = IndividualMultiGenome(
fitness=None, genome=genomes
) # type: IndividualBase # indicates to mypy that
# individual_m is an instance of a child class of
# IndividualBase
ind = individual_m

ind.randomize_genome(self.rng)
ind.idx = self.get_idx_for_new_individual()
return ind

Expand Down
14 changes: 14 additions & 0 deletions test/test_individual.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,17 @@ def test_update_parameters_from_torch_class_does_not_reset_fitness_for_unused_pa
g = _unpack_evaluation(individual.to_func(), individual_type)
x = 2.0
assert g([x])[0] == pytest.approx(x ** 2)


@pytest.mark.parametrize("individual_type", ["SingleGenome", "MultiGenome"])
def test_individual_randomize_genome(individual_type, rng_seed):
rng = np.random.RandomState(rng_seed)
primitives = (cgp.Add, cgp.Mul)
genome = cgp.Genome(1, 1, 2, 1, 1, primitives)
genome.randomize(rng)

dna_old = list(genome.dna)
individual = _create_individual(genome, individual_type=individual_type)

individual.randomize_genome(rng)
assert dna_old != _unpack_genome(individual, individual_type)