Skip to content

Instantly share code, notes, and snippets.

@cvanelteren
Last active March 24, 2022 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvanelteren/d4f65aaf79e566db34137dcbef4dc595 to your computer and use it in GitHub Desktop.
Save cvanelteren/d4f65aaf79e566db34137dcbef4dc595 to your computer and use it in GitHub Desktop.
import networkx as nx, numpy as np, matplotlib.pyplot as plt
np.random.seed(0)
g = nx.florentine_families_graph()
# g = nx.krackhardt_kite_graph()
pos = nx.random_layout(g)
x = {node: p[0] for node, p in pos.items()}
y = {node: p[1] for node, p in pos.items()}
l = {node: node for node in g.nodes()}
s = {node: 4 for node in g.nodes()}
nx.set_node_attributes(g, x, "x")
nx.set_node_attributes(g, y, "y")
nx.set_node_attributes(g, l, "label")
nx.set_node_attributes(g, s, "size")
for r in "rgb":
nx.set_node_attributes(g, 0, r)
nx.write_graphml(g, "f.graphml", named_key_ids=1)
import inspect
from subprocess import call
def get_pos(g):
pos = {}
p = np.zeros(2)
for node in g.nodes():
for idx, i in enumerate("x y".split()):
p[idx] = g.nodes[node][i]
pos[node] = p.copy()
return pos
base = "java -jar gephi-cli.jar force-atlas-2"
tmp = inspect.getargspec(nx.forceatlas2_layout)
print(tmp)
assert len(tmp.defaults) == len(tmp.args) - 1, len(tmp.defaults)
for default, arg in zip(tmp.defaults, tmp.args[1:]):
print(f"Checking {arg=}")
if arg not in "pos".split():
gephi_arg = arg.replace("_", "-")
# reverse flag
if arg in "dissuade_hubs distributed_action gravity".split():
continue
if type(default) is bool:
print(arg)
if arg == "edge_weight_influence":
t = 1.0
else:
default = not default
t = "true" if default else "false"
name = arg
command = f"{base} --max-iters=1000 --{gephi_arg}={t} -i f.graphml -o {name}.graphml"
print(arg, command)
call(command.split())
# gephi graph
gg = nx.read_graphml(f"{name}.graphml")
tmp = {arg: default, "scaling_ratio": 10.0, "n_iter": 1000}
nx_pos = nx.forceatlas2_layout(g, pos=pos, **tmp)
g_pos = get_pos(gg)
fig, ax = plt.subplots(1, 2)
nx.draw(g, nx_pos, ax=ax[0])
nx.draw(gg, g_pos, ax=ax[1])
ax[0].set_title("networkx")
ax[1].set_title("gephi")
fig.suptitle(arg)
for node in g.nodes():
d = ((g_pos[str(node)] - nx_pos[node]) ** 2).sum()
# this currently fails because gephi disregards input positions
try:
assert np.allclose(d, 0) # , (g_pos[node], nx_pos[node])
except Exception as e:
continue
# print(e)
plt.show(block=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment