0

There is a small change to the networkx package which makes it behave how I want, as per this answer.

I.e. I just need to add this code to one of the files in the package code.

# ADD THIS LINE - prevent things from flying off into infinity if not connected
displacement = displacement - pos / ( k * np.sqrt(nnodes))

Is there a way to do this programatically without actually modifying the source code? Would this be a case of "monkey patching"? If it's possible, how do I do it please?

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • It would be important to know, where in the package the modification is needed. Function/Class/etc.? – Franz Sep 09 '20 at 07:16

1 Answers1

1

Looking at the linked answer and the code for the spring_layout function what you want to do is change the function _fruchterman_reingold. Since it's not possible to add the code line inside the function at runtime you will need to define your own function implementing the desired changes and then bind the internal networkx _fruchterman_reingold to your function, which indeed is a kind of monkey patching. The code may look as follows:

# Assume you already defined the modified function and name it my_reingold 

import networkx as nx
nx.drawing.layout._fruchterman_reingold = my_reingold

That said, there's no need to patch Networkx source code or monkey patch at runtime, you may just copy the code you need from the layout.py file (namely fruchterman_reingold_layout, _fruchterman_reingold, _sparse_fruchterman_reingold) and create your little function/module, which is inherently more safe tough maybe less fun.

Happy-Monad
  • 1,962
  • 1
  • 6
  • 13
  • Thanks for this. I'm a little unclear though - are you describing two different solutions? One being overriding `nx.drawing.layout._fruchterman_reingold = my_reingold` and another which doesn't? It's your second paragraph, after the code snippet which confuses me - you seem to be suggesting an alternative to the solution you give but I'm not sure exactly what that involves. – Robin Andrews Sep 09 '20 at 14:15
  • @RobinAndrews yes, I described an alternative but similar solution. Examining the code for the spring_layout function I could see it's internally made up of three functions. The first solution involves overriding while in the second I suggest to make your own "spring-layout" function. To make the function I suggested grabbing the original networkx code and putting it into a file with the desired modifications, then later import it as any other function/module. Please let me know if there's something unclear. – Happy-Monad Sep 10 '20 at 06:26