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

(Suggestion) Handling div-by-zero #81

Open
rtbs-dev opened this issue Feb 1, 2024 · 1 comment
Open

(Suggestion) Handling div-by-zero #81

rtbs-dev opened this issue Feb 1, 2024 · 1 comment

Comments

@rtbs-dev
Copy link

rtbs-dev commented Feb 1, 2024

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.

@paulbrodersen
Copy link
Owner

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

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