From f6bccf800fb751ae22e84f822136057517b24e85 Mon Sep 17 00:00:00 2001
From: manuelpett <manuel.petit@inria.fr>
Date: Tue, 4 Jun 2024 10:44:32 +0200
Subject: [PATCH] Fix bugs related to generator/list in add_from_edges()

---
 src/timagetk/graphs/nx_graph.py | 28 ++++++++++++++++++++++++----
 1 file changed, 24 insertions(+), 4 deletions(-)

diff --git a/src/timagetk/graphs/nx_graph.py b/src/timagetk/graphs/nx_graph.py
index c017e3bb..7afaf27b 100644
--- a/src/timagetk/graphs/nx_graph.py
+++ b/src/timagetk/graphs/nx_graph.py
@@ -248,13 +248,33 @@ class Graph(nx.Graph):
         >>> g.add_edges_from([(7, 9)], key1="hello", key2="world")  # use an integer as node id, they don't
         >>> g.get_edge_data(7, 9)
         {'key1': 'hello', 'key2': 'world'}
+        >>> g.copy() # fix bug relate to generator
 
         """
-        if isinstance(ebunch_to_add[0], tuple):
-            if isinstance(ebunch_to_add[0][0], tuple):
-                ebunch_to_add = [(stuple(u), stuple(v)) for (u, v) in ebunch_to_add]
+        # TODO: Rewrite the add_edges_from() method from networkx
+        # Fix bug related to generator
+        if not isinstance(ebunch_to_add, list):
+            ebunch_to_add = list(ebunch_to_add) # force conversion from generator to list
+
+        processed_edges = []
+        for i, e in enumerate(ebunch_to_add):
+            if len(e) == 2:
+                u, v = e
+                if isinstance(u, tuple):
+                    u = stuple(u)
+                if isinstance(v, tuple):
+                    v = stuple(v)
+                processed_edges.append((u, v))
+            elif len(e) == 3:
+                u, v, d = e
+                if isinstance(u, tuple):
+                    u = stuple(u)
+                if isinstance(v, tuple):
+                    v = stuple(v)
+                processed_edges.append((u, v, d))
             else:
-                ebunch_to_add = [stuple(e) for (e) in ebunch_to_add]
+                raise ValueError(f"Invalid edge tuple length: {len(e)}. Expected length 2 or 3.")
+
         log.debug(f"List of edges to add: {ebunch_to_add}")
         nx.Graph.add_edges_from(self, ebunch_to_add, **kwargs)
 
-- 
GitLab