Example #1
0
    def test_baselogger_can_write_to_stdout(self, capsys, simple_chromosomes):
        logger = BaseLogger(target=None, stdout=True)

        pop = Population(chromosomes=simple_chromosomes,
                         eval_function=lambda x: x)
        pop.evaluate()
        logger.log(pop)
        read_stdout = [line for line in capsys.readouterr().out.split('\n') if line != '']
        assert len(read_stdout) == len(pop)
Example #2
0
 def test_baselogger_works_via_evolution(self, tmpdir, capsys):
     log_file = tmpdir.join('log.txt')
     logger = BaseLogger(target=log_file, stdout=True)
     pop = Population(chromosomes=range(10),
                      eval_function=lambda x: x,
                      logger=logger)
     evo = (Evolution().survive(fraction=0.5).breed(
         parent_picker=pick_random,
         combiner=lambda mom, dad: (mom + dad) / 2 +
         (random.random() - 0.5),
         n_parents=2).log(foo='bar'))
     _ = pop.evolve(evolution=evo, n=2)
     # check characteristics of the file
     with open(log_file, "r") as f:
         read_file = [item.replace("\n", "") for item in f.readlines()]
         # size of the log should be appropriate
         assert len(read_file) == 2 * len(pop)
         # bar needs to be in every single line
         assert all(['bar' in row for row in read_file])
     # check characteristics of stoud
     read_stdout = [
         line for line in capsys.readouterr().out.split('\n') if line != ''
     ]
     assert len(read_stdout) == 2 * len(pop)
     assert all(['bar' in row for row in read_stdout])
Example #3
0
 def test_baselogger_can_accept_kwargs(self, tmpdir, simple_chromosomes,
                                       simple_evaluation_function):
     log_file = tmpdir.join('log.txt')
     logger = BaseLogger(target=log_file, stdout=False)
     pop = Population(chromosomes=simple_chromosomes,
                      eval_function=simple_evaluation_function,
                      logger=logger)
     # we should see that a file was created with an appropriate number of rows
     pop.log(foo="bar")
     with open(log_file, "r") as f:
         assert len(f.readlines()) == len(simple_chromosomes)
         assert all(["bar" in l for l in f.readlines()])
     # we should see that a file was created with an appropriate number of rows
     pop.log(foo="meh")
     with open(log_file, "r") as f:
         assert len(f.readlines()) == (2 * len(simple_chromosomes))
         assert all(['meh' in l for l in f.readlines()[-10:]])
Example #4
0
 def __init__(self,
              chromosomes: Iterable,
              eval_function: Callable[..., float],
              maximize: bool = True,
              logger=None,
              generation: int = 0,
              intended_size: Optional[int] = None,
              checkpoint_target: Optional[str] = None,
              serializer=None):
     self.id = str(uuid4())[:6]
     self.documented_best = None
     self.eval_function = eval_function
     self.generation = generation
     self.individuals = [
         Individual(chromosome=chromosome) for chromosome in chromosomes
     ]
     self.intended_size = intended_size or len(self.individuals)
     self.maximize = maximize
     self.logger = logger or BaseLogger()
     self.serializer = serializer or SimpleSerializer(
         target=checkpoint_target)
Example #5
0
 def test_baselogger_can_write_file_without_stdout(
         self, tmpdir, capsys, simple_chromosomes,
         simple_evaluation_function):
     log_file = tmpdir.join('log.txt')
     logger = BaseLogger(target=log_file, stdout=False)
     pop = Population(chromosomes=simple_chromosomes,
                      eval_function=simple_evaluation_function,
                      logger=logger)
     # we should see that a file was created with an appropriate number of rows
     pop.log()
     with open(log_file, "r") as f:
         assert len(f.readlines()) == len(simple_chromosomes)
     # we should see that a file was created with an appropriate number of rows
     pop.log()
     with open(log_file, "r") as f:
         assert len(f.readlines()) == (2 * len(simple_chromosomes))
     read_stdout = [
         line for line in capsys.readouterr().out.split('\n') if line != ''
     ]
     # there should be nothing printed
     assert len(read_stdout) == 0
Example #6
0
    child_x = (mom[0] + dad[0]) / 2
    child_y = (mom[1] + dad[1]) / 2
    return child_x, child_y


def add_noise(chromosome, sigma):
    """
    This is a function that will add some noise to the chromosome.
    """
    new_x = chromosome[0] + (random.random() - 0.5) * sigma
    new_y = chromosome[1] + (random.random() - 0.5) * sigma
    return new_x, new_y


pop = Population(chromosomes=[random_start() for _ in range(200)],
                 eval_function=func_to_optimise,
                 maximize=True,
                 logger=BaseLogger(target="/tmp/evol.log"))

evo1 = (Evolution().survive(fraction=0.1).breed(
    parent_picker=pick_random_parents,
    combiner=make_child).mutate(mutate_function=add_noise, sigma=0.2).log())

evo2 = (Evolution().survive(n=10).breed(parent_picker=pick_random_parents,
                                        combiner=make_child).mutate(
                                            mutate_function=add_noise,
                                            sigma=0.1).log())

evo3 = (Evolution().repeat(evo1, n=20).repeat(evo2, n=20))

pop = pop.evolve(evo3, n=3)
Example #7
0
    child_x = (mom[0] + dad[0]) / 2
    child_y = (mom[1] + dad[1]) / 2
    return child_x, child_y


def add_noise(chromosome, sigma):
    """
    This is a function that will add some noise to the chromosome.
    """
    new_x = chromosome[0] + (random.random() - 0.5) * sigma
    new_y = chromosome[1] + (random.random() - 0.5) * sigma
    return new_x, new_y


with NamedTemporaryFile() as tmpfile:
    logger = BaseLogger(target=tmpfile.name)
    pop = Population(chromosomes=[random_start() for _ in range(200)],
                     eval_function=func_to_optimise,
                     maximize=True, concurrent_workers=2)

    evo1 = (Evolution()
            .survive(fraction=0.1)
            .breed(parent_picker=pick_random_parents, combiner=make_child)
            .mutate(mutate_function=add_noise, sigma=0.2)
            .callback(logger.log))

    evo2 = (Evolution()
            .survive(n=10)
            .breed(parent_picker=pick_random_parents, combiner=make_child)
            .mutate(mutate_function=add_noise, sigma=0.1)
            .callback(logger.log))