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

Implement callbacks for optimization cycle #18

Open
jnboehm opened this issue Feb 12, 2020 · 1 comment
Open

Implement callbacks for optimization cycle #18

jnboehm opened this issue Feb 12, 2020 · 1 comment

Comments

@jnboehm
Copy link

jnboehm commented Feb 12, 2020

I'd love for the algorithm to have an option to support callbacks, in order to get intermediate results during the optimization stage. I have implemented an approach that I am currently using for my use case, defaulting to the same behaviour that is currently implemented:

2020-02-12 16:47:32.069506000 +0100
@@ -149,7 +149,8 @@
     def forceatlas2(self,
                     G,  # a graph in 2D numpy ndarray format (or) scipy sparse matrix format
                     pos=None,  # Array of initial positions
-                    iterations=100  # Number of times to iterate the main loop
+                    iterations=100,  # Number of times to iterate the main loop
+                    callbacks_every_iters=0, callbacks=None
                     ):
         # Initializing, initAlgo()
         # ================================================================
@@ -174,16 +175,26 @@
         attraction_timer = Timer(name="Attraction forces")
         applyforces_timer = Timer(name="AdjustSpeedAndApplyForces step")
 
+        # transform into list if single func is passed
+        if callable(callbacks):
+            callbacks = [callbacks]
+
         # Each iteration of this loop represents a call to goAlgo().
         niters = range(iterations)
         if self.verbose:
             niters = tqdm(niters)
         for _i in niters:
-            for n in nodes:
+            for i, n in enumerate(nodes):
                 n.old_dx = n.dx
                 n.old_dy = n.dy
                 n.dx = 0
                 n.dy = 0
+                pos[i, 0] = n.x
+                pos[i, 1] = n.y
+
+            if callbacks_every_iters > 0 and (_i % callbacks_every_iters == 0):
+                if callbacks is not None:
+                    [c(_i, pos) for c in callbacks]
 
             # Barnes Hut optimization
             if self.barnesHutOptimize:
@bhargavchippada
Copy link
Owner

@jnboehm Thanks for this suggestion, I will include this mostly in the next version over the summer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants