Repository navigation
Fixed a divide by zero error in forceatlas2 - #7791
Conversation
|
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? |
The problem I encountered, and an example that produces itimport 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)Resultnetworkx/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 zeroBecause 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. |
|
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! |
|
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. |
|
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)) |
|
Thanks @cvanelteren ! Looking at that suggestion I notice that in line 1502 (where we actually do the update) |
|
It looks like the center position moves around over time, so we should recalculate it each iteration. |
|
@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. |
|
You are right @dschult the center of mass should be in the loop (!). The other suggestion looks good to me. Thanks for being vigilant ;-). |
|
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
left a comment
There was a problem hiding this comment.
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.
rossbar
left a comment
There was a problem hiding this comment.
Very nice catch and an elegant solution, thanks @oestej @cvanelteren and @dschult !
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.