netgraph
netgraph copied to clipboard
(Suggestion) Handling div-by-zero
Hi there! Running into a number of division warnings throughout the layout algorithm code, and thought I might offer up a few solutions for consideration
- I've used a "safe-divide" template for any time I do large matrix normalization (e.g. bulk vector norms in a denominator), and this works pretty great for me:
def _safe_div(num, den): return np.divide( num, den, out=np.zeros_like(num, dtype=float), where=den != 0, )
- another option for e.g. logs is to use
np.mask.<ufunc>
, which automatically handles errors in a pretty nice way, though the api won't assume any replacements so you need to start writingmasked_array.filled(0.)
or similar to get back a normal numpy array. This one is super nice for the dev side ,but users aren't generally familiar so I tend to hide masking details until I'm done with them.
For reference, here's an example just now when using the edge_layout='curved'
option:
python3.11/site-packages/netgraph/_utils.py:360: RuntimeWarning: invalid value encountered in divide
v = v / np.linalg.norm(v, axis=-1)[:, None] # unit vector
Some additive-smoothing code I was writing ran into stuff like this all the time before I switched to either a pre-allocated np.zeros_like
or an np.mask
.
Thanks, I am actually in the process of hunting down all warnings as part of the next major release, so this is very helpful. If you let me know your github associated email address, then I can credit you in the commit (once I get to it).