Skip to content

improve from_networkx performance #402

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

Merged
merged 1 commit into from
May 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions src/igraph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1920,6 +1920,7 @@ def from_networkx(cls, g):
@param g: networkx Graph or DiGraph
"""
import networkx as nx
from collections import defaultdict

# Graph attributes
gattr = dict(g.graph)
Expand All @@ -1942,13 +1943,15 @@ def from_networkx(cls, g):
graph.vs[vd[v]][key] = val

# Edges and edge attributes
# NOTE: we need to do both together to deal well with multigraphs
# Each e might have a length of 2 (graphs) or 3 (multigraphs, the
# third element is the "color" of the edge)
for e, (_, _, datum) in zip(g.edges, g.edges.data()):
eid = graph.add_edge(vd[e[0]], vd[e[1]])
for key, val in list(datum.items()):
eid[key] = val
eattr_names = {name for (_, _, data) in g.edges.data() for name in data}
eattr = defaultdict(list)
edges = []
for (u, v, data) in g.edges.data():
edges.append((vd[u], vd[v]))
for name in eattr_names:
eattr[name].append(data.get(name))

graph.add_edges(edges, eattr)

return graph

Expand Down