renard162 / BeeColPy

Artificial Bee Colony algorithm for Python
MIT License
15 stars 3 forks source link

Allow callback to easily monitor iterations #7

Open Marco-Masera opened 3 months ago

Marco-Masera commented 3 months ago

Hi. I'm currently using your package for an optimization problem. Since I needed to easily track iterations of the algorithm to extract some measures (such as diversity of the sampled solutions at each iterations, number of clusters etc) I forked your repository and added a callback function to the abc object constructor, allowing the user to see for each iterations which points of the cost function have been measured and the corresponding fitness.

I think this functions could interest other people looking for ways to observe, measure and babysit the optimization process. If you're interested, you could add this functionality to the package; the fork is at: https://github.com/Marco-Masera/BeeColPy_extended/tree/master

Breviel commented 2 weeks ago

@Marco-Masera I achieved that by doing following:

add callback to abc class:

        def __init__(self,
               function,
               boundaries,
               colony_size: int=40,
               scouts: float=0.5,
               iterations: int=50,
               min_max: str='min',
               nan_protection: bool=True,
               log_agents: bool=False,
               seed: int=None,
               callback=None):

                self.callback = callback

in the fit function add following before return:

        # Callback
        if self.callback is not None:
            self.callback(self.best_food_source.position)

now you get your values every iteration.

In the main program you can just print them out or do what you need:

      def beecol_callback(self, x):
              print(x)

      obj = beecolpy.abc(self.objective_test, bounds, n_pop, scouts, n_iter, 'min', True, callback=self.beecol_callback)
      obj.fit()

Hope this helps you.