Repository: higra/Higra (language: python)

Issue:
Unable to create an empty Tree
Hi,

I am unable to create an empty Tree despite the fact that the constructor seems to exist on the C++ side:

https://github.com/higra/Higra/blob/3e0d566becadc86d9244ed2e67ffc35a041ba0ec/include/higra/structure/tree_graph.hpp#L107-L109

The code below throws a segmentation fault.

```python

import higra as hg

t = hg.Tree([])
```

This bug was reproduced using the version `0.6.5`.


Discussion / hints:

Fix patch:
diff --git a/include/higra/structure/tree_graph.hpp b/include/higra/structure/tree_graph.hpp
index c5867f60..6a6a7f0a 100644
--- a/include/higra/structure/tree_graph.hpp
+++ b/include/higra/structure/tree_graph.hpp
@@ -255,6 +255,12 @@ namespace hg {
         private:
 
             void _init() {
+                if (_parents.size() == 0) {
+                    _root = invalid_index;
+                    _num_vertices = 0;
+                    _num_leaves = 0;
+                    return;
+                }
                 hg_assert(_parents.shape().size() == 1, "parents must be a linear (1d) array");
                 _num_vertices = _parents.size();
                 _root = _num_vertices - 1;


Test patch:
diff --git a/test/cpp/structure/test_tree.cpp b/test/cpp/structure/test_tree.cpp
index 8f76c43a..9cd11555 100644
--- a/test/cpp/structure/test_tree.cpp
+++ b/test/cpp/structure/test_tree.cpp
@@ -32,6 +32,10 @@ namespace tree {
         hg::tree t1;
         REQUIRE(hg::num_vertices(t1) == 0);
 
+        array_1d<index_t> p1{};
+        hg::tree t11(p1);
+        REQUIRE(hg::num_vertices(t11) == 0);
+
         array_1d<index_t> p2{5, 5, 6, 6, 6, 7, 7, 7};
         hg::tree t2(p2);
         REQUIRE(hg::num_vertices(t2) == 8);
diff --git a/test/python/test_structure/test_tree.py b/test/python/test_structure/test_tree.py
index acf282d5..d69de1a0 100644
--- a/test/python/test_structure/test_tree.py
+++ b/test/python/test_structure/test_tree.py
@@ -40,6 +40,15 @@ def test_size_tree(self):
         self.assertTrue(t.parent(4) == 6)
         self.assertTrue(np.all(t.parent((0, 5, 2, 3, 7)) == (5, 7, 6, 6, 7)))
 
+    def test_empty_tree(self):
+        t = hg.Tree([])
+
+        self.assertTrue(t.category() == hg.TreeCategory.PartitionTree)
+        self.assertTrue(t.root() == -1)
+        self.assertTrue(t.num_vertices() == 0)
+        self.assertTrue(t.num_edges() == 0)
+        self.assertTrue(t.num_leaves() == 0)
+
     def test_dynamic_attributes(self):
         t = TestTree.get_tree()
         t.new_attribute = 42