From 2079347ba6b1fc7c79c3053e51844d01ba7cf087 Mon Sep 17 00:00:00 2001 From: Jordi Date: Thu, 7 Mar 2024 19:52:33 +0100 Subject: [PATCH] text_viz.py: Add to_repr() that shows a representation that can recreate the tree. This is another interesting representation of a Tree. It allows to copy-paste the result and recreate the original tree, if used with infinite depth and number of children. --- ete4/core/text_viz.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ete4/core/text_viz.py b/ete4/core/text_viz.py index 354122c5..77011a3c 100644 --- a/ete4/core/text_viz.py +++ b/ete4/core/text_viz.py @@ -171,3 +171,18 @@ def get_branches_repr(are_last, is_leaf, px): return (prefix + ('└' if are_last[-1] else '├') + '─' * px + ('╴' if is_leaf else '┐')) + + +def to_repr(tree, depth=4, nchildren=3): + """Return a text representation that exactly recreates the tree. + + If depth and nchildren are None, return the full representation. + """ + children = tree.children[:nchildren] + depth_1 = depth if depth is None else depth - 1 + children_repr = '...' if depth == 0 else ( + ', '.join(to_repr(node, depth_1, nchildren) for node in children) + + ('' if nchildren is None or len(tree.children) <= nchildren + else ', ...')) + + return 'Tree(%r, [%s])' % (tree.props, children_repr)