Skip to content

Fixed a divide by zero error in forceatlas2 - #7791

Merged
rossbar merged 3 commits into
networkx:mainfrom
oestej:forceatlas2-divby0
Jan 14, 2025
Merged

rossbar merged 3 commits into
networkx:mainfrom
oestej:forceatlas2-divby0

Conversation

@oestej

@oestej oestej commented Jan 10, 2025

Copy link
Copy Markdown
Contributor

When pos_arr includes a node at 0, 0, after normalization, a NaN occurs in the gravity calculation for that node, which propagates through the code to return NaNs for most values.

@dschult

dschult commented Jan 11, 2025

Copy link
Copy Markdown
Member

To get a divide by zero error here wouldn't we need all the node positions to be zero? That's the only way a norm can be zero. So how would that happen? Do you have a small enough example to put into a test for this?
How did you find this issue?

@oestej

oestej commented Jan 11, 2025 •

Copy link
Copy Markdown
Contributor Author

The problem I encountered, and an example that produces it

import networkx

nodes = [
    {"node_id": 1, "position": [0.0, 0.0]},
    {"node_id": 2, "position": [1.0, 12.0]},
    {"node_id": 3, "position": [2.0, -6.0]},
    {"node_id": 4, "position": [5.0, 0.0]},
    {"node_id": 5, "position": [9.0, -3.0]},
]

edges = [
    {"source": 1, "target": 2},
    {"source": 2, "target": 3},
    {"source": 3, "target": 4},
    {"source": 4, "target": 5},
    {"source": 5, "target": 1},
]

graph = networkx.Graph()
for node in nodes:
    graph.add_node(node["node_id"])
for edge in edges:
    graph.add_edge(edge["source"], edge["target"])


position_map = {node["node_id"]: node["position"] for node in nodes}
layout = networkx.forceatlas2_layout(graph, pos=position_map, max_iter=20)

print(layout)

Result

networkx/drawing/layout.py:1467: RuntimeWarning: invalid value encountered in divide
  -gravity
{1: array([nan, nan]), 2: array([nan, nan]), 3: array([nan, nan]), 4: array([nan, nan]), 5: array([nan, nan])}

Why this produces zero

Because we use axis=-1, I believe in this case it's taking the norm of the X and Y coordinates (i.e. distance to the origin to normalize gravity), which when both X and Y are zero will be zero. This isn't a problem with randomly generated points, but if the points feed in from other processes, especially ones with integer coordinates, there will often be something at the origin.

@dschult

dschult commented Jan 11, 2025

Copy link
Copy Markdown
Member

Got it -- Thanks for reporting this and for the example!!

I was thinking the positions had been shifted so the center was (0,0). My understanding is that Gravity should pull everything to the center instead of to the origin. The docstring suggests that gravity pulls to the center.

@cvanelteren can you weigh in on this? Should we be computing gravity based on distance to the origin, or distance to the center of all the other positions? Thanks!

@cvanelteren

Copy link
Copy Markdown
Contributor

Gravity should pull towards the center of mass of the graph not the origin of the plot. Good spot. It's been a long time since I reviewed this code but the calculation needs to be made based on the center of mass.

@cvanelteren

Copy link
Copy Markdown
Contributor

I guess something like

@np_random_state("seed")
def forceatlas2_layout(
    G,
    pos=None,
    *,
    max_iter=100,
    jitter_tolerance=1.0,
    scaling_ratio=2.0,
    gravity=1.0,
    distributed_action=False,
    strong_gravity=False,
    node_mass=None,
    node_size=None,
    weight=None,
    dissuade_hubs=False,
    linlog=False,
    seed=None,
    dim=2,
):
    import numpy as np

    if len(G) == 0:
        return {}

    # Parse optional pos positions
    if pos is None:
        pos = nx.random_layout(G, dim=dim, seed=seed)
        pos_arr = np.array(list(pos.values()))
    else:
        pos_init = np.array(list(pos.values()))
        max_pos = pos_init.max(axis=0)
        min_pos = pos_init.min(axis=0)
        dim = max_pos.size
        pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
        for idx, node in enumerate(G):
            if node in pos:
                pos_arr[idx] = pos[node].copy()

    mass = np.zeros(len(G))
    size = np.zeros(len(G))

    adjust_sizes = False
    if node_size is None:
        node_size = {}
    else:
        adjust_sizes = True

    if node_mass is None:
        node_mass = {}

    for idx, node in enumerate(G):
        mass[idx] = node_mass.get(node, G.degree(node) + 1)
        size[idx] = node_size.get(node, 1)

    n = len(G)
    gravities = np.zeros((n, dim))
    attraction = np.zeros((n, dim))
    repulsion = np.zeros((n, dim))
    A = nx.to_numpy_array(G, weight=weight)

    def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
        import numpy as np
        opt_jitter = 0.05 * np.sqrt(n)
        min_jitter = np.sqrt(opt_jitter)
        max_jitter = 10
        min_speed_efficiency = 0.05

        other = min(max_jitter, opt_jitter * traction / n**2)
        jitter = jitter_tolerance * max(min_jitter, other)

        if swing / traction > 2.0:
            if speed_efficiency > min_speed_efficiency:
                speed_efficiency *= 0.5
            jitter = max(jitter, jitter_tolerance)
        if swing == 0:
            target_speed = np.inf
        else:
            target_speed = jitter * speed_efficiency * traction / swing

        if swing > jitter * traction:
            if speed_efficiency > min_speed_efficiency:
                speed_efficiency *= 0.7
        elif speed < 1000:
            speed_efficiency *= 1.3

        max_rise = 0.5
        speed = speed + min(target_speed - speed, max_rise * speed)
        return speed, speed_efficiency

    # Compute the center of mass of the graph
    center_of_mass = np.mean(pos_arr, axis=0)

    speed = 1
    speed_efficiency = 1
    swing = 1
    traction = 1
    for _ in range(max_iter):
        diff = pos_arr[:, None] - pos_arr[None]
        distance = np.linalg.norm(diff, axis=-1)

        if linlog:
            attraction = -np.log(1 + distance) / distance
            np.fill_diagonal(attraction, 0)
            attraction = np.einsum("ij, ij -> ij", attraction, A)
            attraction = np.einsum("ijk, ij -> ik", diff, attraction)
        else:
            attraction = -np.einsum("ijk, ij -> ik", diff, A)

        if distributed_action:
            attraction /= mass[:, None]

        tmp = mass[:, None] @ mass[None]
        if adjust_sizes:
            distance += -size[:, None] - size[None]

        d2 = distance**2
        np.fill_diagonal(tmp, 0)
        np.fill_diagonal(d2, 1)
        factor = (tmp / d2) * scaling_ratio
        repulsion = np.einsum("ijk, ij -> ik", diff, factor)

        # Gravity towards the center of mass
        gravities = (
            -gravity
            * mass[:, None]
            * (pos_arr - center_of_mass)
            / (np.linalg.norm(pos_arr - center_of_mass, axis=-1)[:, None])
        )
        gravities = np.nan_to_num(gravities, nan=0)  # Handle gravity at the center

        if strong_gravity:
            gravities *= np.linalg.norm(pos_arr - center_of_mass, axis=-1)[:, None]

        update = attraction + repulsion + gravities

        swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
        traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()

        speed, speed_efficiency = estimate_factor(
            n,
            swing,
            traction,
            speed,
            speed_efficiency,
            jitter_tolerance,
        )

        if adjust_sizes:
            swinging = mass * np.linalg.norm(update, axis=-1)
            factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
            df = np.linalg.norm(update, axis=-1)
            factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
        else:
            swinging = mass * np.linalg.norm(update, axis=-1)
            factor = speed / (1 + np.sqrt(speed * swinging))

        pos_arr += update * factor[:, None]
        if abs((update * factor[:, None]).sum()) < 1e-10:
            break

    return dict(zip(G, pos_arr))

@dschult

dschult commented Jan 12, 2025

Copy link
Copy Markdown
Member

Thanks @cvanelteren !

Looking at that suggestion I notice that in line 1502 (where we actually do the update)
we stop (break) only if the abs of the sum of the updates is small. But doing the abs of the sum allows positive and negative updates to cancel before the abs has a chance to make them all positive. Should it be
if abs(update * factor[:, None]).sum() <= 1e-10:
instead of
if abs((update * factor[:, None]).sum()) <= 1e-10:

@dschult

dschult commented Jan 12, 2025

Copy link
Copy Markdown
Member

It looks like the center position moves around over time, so we should recalculate it each iteration.
Does that make sense?

@dschult

dschult commented Jan 12, 2025

Copy link
Copy Markdown
Member

@oestej, Are you willing to check the box/button on the right side of the PR discussion that allows maintainers to make changes to the PR? I've got @cvanelteren 's changes set up and some other small improvements. I could push them if you give me permission.

@cvanelteren

Copy link
Copy Markdown
Contributor

You are right @dschult the center of mass should be in the loop (!). The other suggestion looks good to me. Thanks for being vigilant ;-).

@oestej

oestej commented Jan 12, 2025

Copy link
Copy Markdown
Contributor Author

Altered to allow edits, sorry about the delay. Turns out that's not available on enterprise-associated repos, so needed to migrate it to my personal account first.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is ready to go. I approve this PR.

I took the liberty of making a couple of changes that avoid unneeded computation. See comments below.

Comment thread networkx/drawing/layout.py Resolved
Comment thread networkx/drawing/layout.py Resolved
Comment thread networkx/drawing/layout.py Resolved
Comment thread networkx/drawing/layout.py Resolved

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice catch and an elegant solution, thanks @oestej @cvanelteren and @dschult !

@rossbar
rossbar merged commit 7ac7125 into networkx:main Jan 14, 2025
@jarrodmillman jarrodmillman added this to the 3.5 milestone Jan 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

5 participants