Example #1
0
def main():
    # make the scheduler first
    with Scheduler({'nanny': True, 'interface': 'lo'}) as mpi_scheduler:
        # create and run GA
        # acs = AdaptiveCoolingSchedule(1, 0.2, 0, 10000, 1.0, 20)
        # ga = ACSGa(initial_state=np.array([0.4, 0.3, -0.25, 0.01]),
        #            population_size=5,
        #            scheduler=mpi_scheduler,
        #            global_seed=96879,
        #            cooling_schedule=acs,
        #            table_size=20000,
        #            max_table_step=1,
        #            member_type=Member,
        #            save_filename=Path("test.acsga"),
        #            save_every=1000)
        # ga.run(sphere, 350, take_member=False)

        acs = AdaptiveCoolingSchedule(5.0, 100.0, 0.0, 500, 1.0, 50)  # 20
        ga = ACSGa(initial_state=np.array([0.4, 0.3, -0.25, 0.01]),
                   population_size=5,
                   scheduler=mpi_scheduler,
                   global_seed=96879,
                   cooling_schedule=acs,
                   table_size=20000,
                   max_table_step=1,
                   member_type=Member,
                   save_filename=Path("test.acsga"),
                   save_every=1000)
        ga.run(rosenbrock, 2000, take_member=False)
Example #2
0
def main():
    # make the scheduler first
    with Scheduler({'nanny': True, 'interface': 'lo'}) as mpi_scheduler:
        # create and run GA
        ga = AsyncCSAGa(initial_state=np.array([0.4, 0.3, -0.25, 0.01]),
                        initial_sigma=np.ones(4) * 5,
                        population_size=5,
                        scheduler=mpi_scheduler,
                        global_seed=96879,
                        table_size=200000,
                        max_table_step=1,
                        member_type=DiagnosticCSAMember,
                        save_filename=Path("test.csaga"))
        ga.run(sphere, 1000, take_member=False)
Example #3
0
def main():
    # make the scheduler first
    with Scheduler({'nanny': True, 'interface': 'lo'}) as mpi_scheduler:
        # create and run GA
        ga = AsyncCSAGa(initial_state=np.array([0.4, 0.3, -0.25, 0.01]),
                        initial_sigma=np.ones(4) * 5,
                        population_size=5,
                        scheduler=mpi_scheduler,
                        global_seed=96879,
                        table_size=200000,
                        max_table_step=1,
                        member_type=CSAMember,
                        save_filename=Path("test.csaga"),
                        save_every=1000)
        ga.run(sphere, 300, take_member=False)

        # load pop from file and continue
        ga = AsyncCSAGa.from_file("test.csaga",
                                  scheduler=mpi_scheduler,
                                  global_seed=432,
                                  save_filename="test.csaga")
        ga.run(sphere, 50, take_member=False)
Example #4
0
    def run(self,
            fitness_function: Callable[[np.ndarray], float],
            num_iterations: int,
            fitness_kwargs: Dict = None,
            take_member: bool = False):
        """
        Executes the genetic algorithm.
        :param fitness_function: a function that returns the fitness of a lineage.
        :param num_iterations: the number of steps to run.
        :param fitness_kwargs: any key word arguments for fitness_function.
        :param take_member: whether the fitness function requires the member to be
        provided or not (if not then expects an array) (default: False).
        """
        if fitness_kwargs is None:
            fitness_kwargs = {}

        if self._save_every is None:
            self._save_every = num_iterations

        # distribute members for each worker
        self._scheduler.wait_on_workers()
        num_workers = self._scheduler.num_workers()
        if num_workers == 0:
            raise ValueError("Error: there are no workers.")
        workers = self._scheduler.get_worker_names()
        if len(workers) == 0:
            raise ValueError("Error: there are no workers.")
        members = [
            self._scheduler.client.submit(initialize_member,
                                          self._member_type,
                                          self._member_type_kwargs,
                                          workers=[worker])
            for worker in workers
        ]

        # skip if population is loaded from file
        if not self._from_file:
            # create initial batch
            initial_batch = [
                self._scheduler.client.submit(dispatch_work,
                                              fitness_function,
                                              self._population[pop]['lineage'],
                                              members[i],
                                              i,
                                              fitness_kwargs,
                                              take_member,
                                              workers=[workers[i]])
                for i, pop_group in enumerate(
                    split_work(list(range(self._population_size)),
                               num_workers)) for pop in pop_group
            ]

            # wait for initial batch to complete and fill initial population
            for completed_job in Scheduler.as_completed(initial_batch):
                fitness, lineage, index = completed_job.result()
                self._set_initial(lineage, fitness)

        # submit jobs to all workers or till num iterations is saturated
        jobs = []
        for index in range(min(num_iterations, len(members))):
            self._anneal()
            jobs.append(
                self._scheduler.client.submit(dispatch_work,
                                              fitness_function,
                                              self._mutation(
                                                  self._selection()),
                                              members[index],
                                              index,
                                              fitness_kwargs,
                                              take_member=take_member,
                                              workers=[workers[index]]))
            self._step += 1

        # iterate ga until num_iterations reached
        working_batch = Scheduler.as_completed(jobs)
        for completed_job in working_batch:
            fitness, lineage, index = completed_job.result()
            self._replacement(lineage, fitness)
            self._update_fitness_history()
            if (self._save_filename is not None) and \
                    (self._step % self._save_every == 0):
                self.save_population(self._save_filename)

            if self._step < num_iterations:
                self._anneal()
                working_batch.add(
                    self._scheduler.client.submit(dispatch_work,
                                                  fitness_function,
                                                  self._mutation(
                                                      self._selection()),
                                                  members[index],
                                                  index,
                                                  fitness_kwargs,
                                                  take_member=take_member,
                                                  workers=[workers[index]]))
                self._step += 1

        if self._save_filename is not None:
            self.save_population(self._save_filename)