@@ -1906,9 +1906,6 @@ def from_networkx(cls, g):
1906
1906
1907
1907
@param g: networkx Graph or DiGraph
1908
1908
"""
1909
- import networkx as nx
1910
- from collections import defaultdict
1911
-
1912
1909
# Graph attributes
1913
1910
gattr = dict (g .graph )
1914
1911
@@ -1931,7 +1928,7 @@ def from_networkx(cls, g):
1931
1928
1932
1929
# Edges and edge attributes
1933
1930
eattr_names = {name for (_ , _ , data ) in g .edges .data () for name in data }
1934
- eattr = defaultdict ( list )
1931
+ eattr = { name : [] for name in eattr_names }
1935
1932
edges = []
1936
1933
for (u , v , data ) in g .edges .data ():
1937
1934
edges .append ((vd [u ], vd [v ]))
@@ -2029,13 +2026,19 @@ def from_graph_tool(cls, g):
2029
2026
for i in range (vcount ):
2030
2027
graph .vs [i ][key ] = prop [i ]
2031
2028
2032
- # Edges
2033
- # NOTE: the order the edges are put in is necessary to set the
2034
- # attributes later on
2029
+ # Edges and edge attributes
2030
+ # NOTE: graph-tool is quite strongly typed, so each property is always
2031
+ # defined for all edges, using default values for the type. E.g. for a
2032
+ # string property/attribute the missing edges get an empty string.
2033
+ edges = []
2034
+ eattr_names = list (g .edge_properties )
2035
+ eattr = {name : [] for name in eattr_names }
2035
2036
for e in g .edges ():
2036
- edge = graph .add_edge (int (e .source ()), int (e .target ()))
2037
- for key , val in list (g .edge_properties .items ()):
2038
- edge [key ] = val [e ]
2037
+ edges .append ((int (e .source ()), int (e .target ())))
2038
+ for name , attr_map in list (g .edge_properties .items ()):
2039
+ eattr [name ].append (attr_map [e ])
2040
+
2041
+ graph .add_edges (edges , eattr )
2039
2042
2040
2043
return graph
2041
2044
0 commit comments