netgraph icon indicating copy to clipboard operation
netgraph copied to clipboard

(Suggestion) Handling div-by-zero

Open rtbs-dev opened this issue 1 year ago • 1 comments

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 writing masked_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.

rtbs-dev avatar Feb 01 '24 16:02 rtbs-dev

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).

paulbrodersen avatar Feb 01 '24 17:02 paulbrodersen