π¨ ExportΒΆ
Export Tree to list, dictionary, and pandas DataFrame.
Export Tree to |
Method |
|---|---|
Command Line / Others |
print_tree, yield_tree |
String |
tree_to_newick |
Dictionary |
tree_to_dict, tree_to_nested_dict |
DataFrame |
tree_to_dataframe |
Dot (for .dot, .png, .svg, .jpeg, etc.) |
tree_to_dot |
Pillow (for .png, .jpg, .jpeg, etc.) |
tree_to_pillow |
Mermaid Markdown (for .md) |
tree_to_mermaid |
While exporting to another data type, methods can take in arguments to determine what information to extract.
Method |
Extract node attributes |
Specify maximum depth |
Skip depth |
Extract leaves only |
Others |
|---|---|---|---|---|---|
print_tree |
Yes with attr_list or all_attrs |
Yes with max_depth |
No, but can specify subtree |
No |
Tree style |
yield_tree |
No, returns node |
Yes with max_depth |
No, but can specify subtree |
No |
Tree style |
tree_to_newick |
Yes with attr_list |
No |
No |
No |
Length separator and attribute prefix and separator |
tree_to_dict |
Yes with attr_dict or all_attrs |
Yes with max_depth |
Yes with skip_depth |
Yes with leaf_only |
Dict key for parent |
tree_to_nested_dict |
Yes with attr_dict or all_attrs |
Yes with max_depth |
No |
No |
Dict key for node name and node children |
tree_to_dataframe |
Yes with attr_dict or all_attrs |
Yes with max_depth |
Yes with skip_depth |
Yes with leaf_only |
Column name for path, node name, node parent |
tree_to_dot |
No |
No |
No |
No |
Graph attributes, background, node, edge colour, etc. |
tree_to_pillow |
No |
Yes, using keyword arguments similar to yield_tree |
No |
No |
Font (family, size, colour), background colour, etc. |
tree_to_mermaid |
No |
Yes, using keyword arguments similar to yield_tree |
No |
No |
Node shape, node fill, edge arrow, edge label etc. |
Functions:
|
Print tree in horizontal orientation to console, starting from tree. |
|
Yield tree in horizontal orientation to console, starting from tree. |
|
Print tree to console, starting from tree. |
|
Export tree to pandas DataFrame. |
|
Export tree to dictionary. |
|
Export tree or list of trees to image. |
|
Export tree to mermaid Markdown text. |
|
Export tree to nested dictionary. |
|
Export tree to Newick notation. |
|
Export tree to image (JPG, PNG). |
|
Generator method for customizing printing of tree, starting from tree. |
- bigtree.tree.export.hprint_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, intermediate_node_name: bool = True, style: str = 'const', custom_style: Iterable[str] = []) NoneΒΆ
Print tree in horizontal orientation to console, starting from tree.
Able to select which node to print from, resulting in a subtree, using node_name_or_path
Able to customize for maximum depth to print, using max_depth
- Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style
Default style is const style
If style is set to custom, user can choose their own style icons
Style icons should have the same number of characters
Printing tree
>>> from bigtree import Node, hprint_tree >>> root = Node("a") >>> b = Node("b", parent=root) >>> c = Node("c", parent=root) >>> d = Node("d", parent=b) >>> e = Node("e", parent=b) >>> hprint_tree(root) ββ d ββ b ββ€ β a ββ€ ββ e ββ c
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path="b") ββ d β b ββ€ ββ e
>>> hprint_tree(root, max_depth=2) ββ b β a ββ€ ββ c
Available Styles
>>> hprint_tree(root, style="ansi") /- d /- b -+ - a -+ \- e \- c
>>> hprint_tree(root, style="ascii") +- d +- b -+ - a -+ +- e +- c
>>> hprint_tree(root, style="const") ββ d ββ b ββ€ β a ββ€ ββ e ββ c
>>> hprint_tree(root, style="const_bold") ββ d ββ b ββ« β a ββ« ββ e ββ c
>>> hprint_tree(root, style="rounded") ββ d ββ b ββ€ β a ββ€ β°β e β°β c
>>> hprint_tree(root, style="double") ββ d ββ b ββ£ β a ββ£ ββ e ββ c
- Parameters:
tree (Node) β tree to print
node_name_or_path (str) β node to print from, becomes the root node of printing
max_depth (int) β maximum depth of tree to print, based on depth attribute, optional
intermediate_node_name (bool) β indicator if intermediate nodes have node names, defaults to True
style (str) β style of print, defaults to const style
custom_style (Iterable[str]) β style of icons, used when style is set to βcustomβ
- bigtree.tree.export.hyield_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, intermediate_node_name: bool = True, style: str = 'const', custom_style: Iterable[str] = []) List[str]ΒΆ
Yield tree in horizontal orientation to console, starting from tree.
Able to select which node to print from, resulting in a subtree, using node_name_or_path
Able to customize for maximum depth to print, using max_depth
- Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style
Default style is const style
If style is set to custom, user can choose their own style icons
Style icons should have the same number of characters
Printing tree
>>> from bigtree import Node, hyield_tree >>> root = Node("a") >>> b = Node("b", parent=root) >>> c = Node("c", parent=root) >>> d = Node("d", parent=b) >>> e = Node("e", parent=b) >>> result = hyield_tree(root) >>> print("\n".join(result)) ββ d ββ b ββ€ β a ββ€ ββ e ββ c
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path="b") ββ d β b ββ€ ββ e
>>> hprint_tree(root, max_depth=2) ββ b β a ββ€ ββ c
Available Styles
>>> hprint_tree(root, style="ansi") /- d /- b -+ - a -+ \- e \- c
>>> hprint_tree(root, style="ascii") +- d +- b -+ - a -+ +- e +- c
>>> hprint_tree(root, style="const") ββ d ββ b ββ€ β a ββ€ ββ e ββ c
>>> hprint_tree(root, style="const_bold") ββ d ββ b ββ« β a ββ« ββ e ββ c
>>> hprint_tree(root, style="rounded") ββ d ββ b ββ€ β a ββ€ β°β e β°β c
>>> hprint_tree(root, style="double") ββ d ββ b ββ£ β a ββ£ ββ e ββ c
- Parameters:
tree (Node) β tree to print
node_name_or_path (str) β node to print from, becomes the root node of printing
max_depth (int) β maximum depth of tree to print, based on depth attribute, optional
intermediate_node_name (bool) β indicator if intermediate nodes have node names, defaults to True
style (str) β style of print, defaults to const style
custom_style (Iterable[str]) β style of icons, used when style is set to βcustomβ
- Returns:
(List[str])
- bigtree.tree.export.print_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, all_attrs: bool = False, attr_list: Iterable[str] = [], attr_omit_null: bool = False, attr_bracket: List[str] = ['[', ']'], style: str = 'const', custom_style: Iterable[str] = []) NoneΒΆ
Print tree to console, starting from tree.
Able to select which node to print from, resulting in a subtree, using node_name_or_path
Able to customize for maximum depth to print, using max_depth
Able to choose which attributes to show or show all attributes, using attr_name_filter and all_attrs
Able to omit showing of attributes if it is null, using attr_omit_null
Able to customize open and close brackets if attributes are shown, using attr_bracket
- Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style
Default style is const style
If style is set to custom, user can choose their own style for stem, branch and final stem icons
Stem, branch, and final stem symbol should have the same number of characters
Printing tree
>>> from bigtree import Node, print_tree >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> print_tree(root) a βββ b β βββ d β βββ e βββ c
Printing Sub-tree
>>> print_tree(root, node_name_or_path="b") b βββ d βββ e
>>> print_tree(root, max_depth=2) a βββ b βββ c
Printing Attributes
>>> print_tree(root, attr_list=["age"]) a [age=90] βββ b [age=65] β βββ d [age=40] β βββ e [age=35] βββ c [age=60]
>>> print_tree(root, attr_list=["age"], attr_bracket=["*(", ")"]) a *(age=90) βββ b *(age=65) β βββ d *(age=40) β βββ e *(age=35) βββ c *(age=60)
Available Styles
>>> print_tree(root, style="ansi") a |-- b | |-- d | `-- e `-- c
>>> print_tree(root, style="ascii") a |-- b | |-- d | +-- e +-- c
>>> print_tree(root, style="const") a βββ b β βββ d β βββ e βββ c
>>> print_tree(root, style="const_bold") a β£ββ b β β£ββ d β βββ e βββ c
>>> print_tree(root, style="rounded") a βββ b β βββ d β β°ββ e β°ββ c
>>> print_tree(root, style="double") a β ββ b β β ββ d β βββ e βββ c
- Parameters:
tree (Node) β tree to print
node_name_or_path (str) β node to print from, becomes the root node of printing
max_depth (int) β maximum depth of tree to print, based on depth attribute, optional
all_attrs (bool) β indicator to show all attributes, defaults to False, overrides attr_list and attr_omit_null
attr_list (Iterable[str]) β list of node attributes to print, optional
attr_omit_null (bool) β indicator whether to omit showing of null attributes, defaults to False
attr_bracket (List[str]) β open and close bracket for all_attrs or attr_list
style (str) β style of print, defaults to const style
custom_style (Iterable[str]) β style of stem, branch and final stem, used when style is set to βcustomβ
- bigtree.tree.export.tree_to_dataframe(tree: T, path_col: str = 'path', name_col: str = 'name', parent_col: str = '', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0, skip_depth: int = 0, leaf_only: bool = False) DataFrameΒΆ
Export tree to pandas DataFrame.
All descendants from tree will be exported, tree can be the root node or child node of tree.
>>> from bigtree import Node, tree_to_dataframe >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> tree_to_dataframe(root, name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"}) path name parent person age 0 /a a None 90 1 /a/b b a 65 2 /a/b/d d b 40 3 /a/b/e e b 35 4 /a/c c a 60
For a subset of a tree.
>>> tree_to_dataframe(b, name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"}) path name parent person age 0 /a/b b a 65 1 /a/b/d d b 40 2 /a/b/e e b 35
- Parameters:
tree (Node) β tree to be exported
path_col (str) β column name for node.path_name, defaults to βpathβ
name_col (str) β column name for node.node_name, defaults to βnameβ
parent_col (str) β column name for node.parent.node_name, optional
attr_dict (Dict[str, str]) β dictionary mapping node attributes to column name, key: node attributes, value: corresponding column in dataframe, optional
all_attrs (bool) β indicator whether to retrieve all
Nodeattributes, overrides attr_dict, defaults to Falsemax_depth (int) β maximum depth to export tree, optional
skip_depth (int) β number of initial depths to skip, optional
leaf_only (bool) β indicator to retrieve only information from leaf nodes
- Returns:
(pd.DataFrame)
- bigtree.tree.export.tree_to_dict(tree: T, name_key: str = 'name', parent_key: str = '', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0, skip_depth: int = 0, leaf_only: bool = False) Dict[str, Any]ΒΆ
Export tree to dictionary.
All descendants from tree will be exported, tree can be the root node or child node of tree.
Exported dictionary will have key as node path, and node attributes as a nested dictionary.
>>> from bigtree import Node, tree_to_dict >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> tree_to_dict(root, name_key="name", parent_key="parent", attr_dict={"age": "person age"}) {'/a': {'name': 'a', 'parent': None, 'person age': 90}, '/a/b': {'name': 'b', 'parent': 'a', 'person age': 65}, '/a/b/d': {'name': 'd', 'parent': 'b', 'person age': 40}, '/a/b/e': {'name': 'e', 'parent': 'b', 'person age': 35}, '/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}
For a subset of a tree
>>> tree_to_dict(c, name_key="name", parent_key="parent", attr_dict={"age": "person age"}) {'/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}
- Parameters:
tree (Node) β tree to be exported
name_key (str) β dictionary key for node.node_name, defaults to βnameβ
parent_key (str) β dictionary key for node.parent.node_name, optional
attr_dict (Dict[str, str]) β dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional
all_attrs (bool) β indicator whether to retrieve all
Nodeattributes, overrides attr_dict, defaults to Falsemax_depth (int) β maximum depth to export tree, optional
skip_depth (int) β number of initial depths to skip, optional
leaf_only (bool) β indicator to retrieve only information from leaf nodes
- Returns:
(Dict[str, Any])
- bigtree.tree.export.tree_to_dot(tree: T | List[T], directed: bool = True, rankdir: str = 'TB', bg_colour: str = '', node_colour: str = '', node_shape: str = '', edge_colour: str = '', node_attr: Callable[[T], Dict[str, Any]] | str = '', edge_attr: Callable[[T], Dict[str, Any]] | str = '') pydot.DotΒΆ
Export tree or list of trees to image. Possible node attributes include style, fillcolor, shape.
>>> from bigtree import Node, tree_to_dot >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> graph = tree_to_dot(root)
Display image directly without saving (requires IPython)
>>> from IPython.display import Image, display >>> plt = Image(graph.create_png()) >>> display(plt) <IPython.core.display.Image object>
Export to image, dot file, etc.
>>> graph.write_png("assets/docstr/tree.png") >>> graph.write_dot("assets/docstr/tree.dot")
Export to string
>>> graph.to_string() 'strict digraph G {\nrankdir=TB;\na0 [label=a];\nb0 [label=b];\na0 -> b0;\nd0 [label=d];\nb0 -> d0;\ne0 [label=e];\nb0 -> e0;\nc0 [label=c];\na0 -> c0;\n}\n'
Defining node and edge attributes (using node attribute)
>>> class CustomNode(Node): ... def __init__(self, name, node_shape="", edge_label="", **kwargs): ... super().__init__(name, **kwargs) ... self.node_shape = node_shape ... self.edge_label = edge_label ... ... @property ... def edge_attr(self): ... if self.edge_label: ... return {"label": self.edge_label} ... return {} ... ... @property ... def node_attr(self): ... if self.node_shape: ... return {"shape": self.node_shape} ... return {} >>> >>> >>> root = CustomNode("a", node_shape="circle") >>> b = CustomNode("b", edge_label="child", parent=root) >>> c = CustomNode("c", edge_label="child", parent=root) >>> d = CustomNode("d", node_shape="square", edge_label="child", parent=b) >>> e = CustomNode("e", node_shape="square", edge_label="child", parent=b) >>> graph = tree_to_dot(root, node_colour="gold", node_shape="diamond", node_attr="node_attr", edge_attr="edge_attr") >>> graph.write_png("assets/export_tree_dot.png")
Alternative way to define node and edge attributes (using callable function)
>>> def get_node_attribute(node: Node): ... if node.is_leaf: ... return {"shape": "square"} ... return {"shape": "circle"} >>> >>> >>> root = CustomNode("a") >>> b = CustomNode("b", parent=root) >>> c = CustomNode("c", parent=root) >>> d = CustomNode("d", parent=b) >>> e = CustomNode("e", parent=b) >>> graph = tree_to_dot(root, node_colour="gold", node_attr=get_node_attribute) >>> graph.write_png("assets/export_tree_dot_callable.png")
- Parameters:
tree (Node/List[Node]) β tree or list of trees to be exported
directed (bool) β indicator whether graph should be directed or undirected, defaults to True
rankdir (str) β layout direction, defaults to βTBβ (top to bottom), can be βBTβ (bottom to top), βLRβ (left to right), βRLβ (right to left)
bg_colour (str) β background color of image, defaults to None
node_colour (str) β fill colour of nodes, defaults to None
node_shape (str) β shape of nodes, defaults to None Possible node_shape include βcircleβ, βsquareβ, βdiamondβ, βtriangleβ
edge_colour (str) β colour of edges, defaults to None
node_attr (str | Callable) β If string type, it refers to
Nodeattribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour and node_shape and defaults to None. Possible node styles include {βstyleβ: βfilledβ, βfillcolorβ: βgoldβ, βshapeβ: βdiamondβ}edge_attr (str | Callable) β If stirng type, it refers to
Nodeattribute for edge style. If callable type, it takes in the node itself and returns the edge style. This overrides edge_colour, and defaults to None. Possible edge styles include {βstyleβ: βboldβ, βlabelβ: βedge labelβ, βcolorβ: βblackβ}
- Returns:
(pydot.Dot)
- bigtree.tree.export.tree_to_mermaid(tree: T, title: str = '', rankdir: str = 'TB', line_shape: str = 'basis', node_colour: str = '', node_border_colour: str = '', node_border_width: float = 1, node_shape: str = 'rounded_edge', node_shape_attr: Callable[[T], str] | str = '', edge_arrow: str = 'normal', edge_arrow_attr: Callable[[T], str] | str = '', edge_label: str = '', node_attr: Callable[[T], str] | str = '', **kwargs: Any) strΒΆ
Export tree to mermaid Markdown text. Accepts additional keyword arguments as input to yield_tree.
- Parameters for customizations that applies to entire flowchart include:
Title, title
Layout direction, rankdir
Line shape or curvature, line_shape
Fill colour of nodes, node_colour
Border colour of nodes, node_border_colour
Border width of nodes, node_border_width
Node shape, node_shape
Edge arrow style, edge_arrow
- Parameters for customizations that apply to customized nodes:
Fill colour of nodes, fill under node_attr
Border colour of nodes, stroke under node_attr
Border width of nodes, stroke-width under node_attr
Node shape, node_shape_attr
Edge arrow style, edge_arrow_attr
Edge label, edge_label
Accepted Parameter Values
- Possible rankdir:
TB: top-to-bottom
BT: bottom-to-top
LR: left-to-right
RL: right-to-left
- Possible line_shape:
basis
bumpX: used in LR or RL direction
bumpY
cardinal: undirected
catmullRom: undirected
linear:
monotoneX: used in LR or RL direction
monotoneY
natural
step: used in LR or RL direction
stepAfter
stepBefore: used in LR or RL direction
- Possible node_shape:
rounded_edge: rectangular with rounded edges
stadium: (_) shape, rectangular with rounded ends
subroutine: ||_|| shape, rectangular with additional line at the ends
cylindrical: database node
circle: circular
asymmetric: >_| shape
rhombus: decision node
hexagon: <_> shape
parallelogram: /_/ shape
parallelogram_alt: \_\ shape, inverted parallelogram
trapezoid: /_\ shape
trapezoid_alt: \_/ shape, inverted trapezoid
double_circle
- Possible edge_arrow:
normal: directed arrow, shaded arrowhead
bold: bold directed arrow
dotted: dotted directed arrow
open: line, undirected arrow
bold_open: bold line
dotted_open: dotted line
invisible: no line
circle: directed arrow with filled circle arrowhead
cross: directed arrow with cross arrowhead
double_normal: bidirectional directed arrow
double_circle: bidirectional directed arrow with filled circle arrowhead
double_cross: bidirectional directed arrow with cross arrowhead
Refer to mermaid documentation for more information. Paste the output into any markdown file renderer to view the flowchart, alternatively visit the mermaid playground here.
Note
Advanced mermaid flowchart functionalities such as subgraphs and interactions (script, click) are not supported.
>>> from bigtree import tree_to_mermaid >>> root = Node("a", node_shape="rhombus") >>> b = Node("b", edge_arrow="bold", edge_label="Child 1", parent=root) >>> c = Node("c", edge_arrow="dotted", edge_label="Child 2", parent=root) >>> d = Node("d", node_style="fill:yellow, stroke:black", parent=b) >>> e = Node("e", parent=b) >>> graph = tree_to_mermaid(root) >>> print(graph) ```mermaid %%{ init: { 'flowchart': { 'curve': 'basis' } } }%% flowchart TB 0("a") --> 0-0("b") 0-0 --> 0-0-0("d") 0-0 --> 0-0-1("e") 0("a") --> 0-1("c") classDef default stroke-width:1 ```
Customize node shape, edge label, edge arrow, and custom node attributes
>>> graph = tree_to_mermaid(root, node_shape_attr="node_shape", edge_label="edge_label", edge_arrow_attr="edge_arrow", node_attr="node_style") >>> print(graph) ```mermaid %%{ init: { 'flowchart': { 'curve': 'basis' } } }%% flowchart TB 0{"a"} ==>|Child 1| 0-0("b") 0-0:::class0-0-0 --> 0-0-0("d") 0-0 --> 0-0-1("e") 0{"a"} -.->|Child 2| 0-1("c") classDef default stroke-width:1 classDef class0-0-0 fill:yellow, stroke:black ```
- Parameters:
tree (Node) β tree to be exported
title (str) β title, defaults to None
rankdir (str) β layout direction, defaults to βTBβ (top to bottom), can be βBTβ (bottom to top), βLRβ (left to right), βRLβ (right to left)
line_shape (str) β line shape or curvature, defaults to βbasisβ
node_colour (str) β fill colour of nodes, can be colour name or hexcode, defaults to None
node_border_colour (str) β border colour of nodes, can be colour name or hexcode, defaults to None
node_border_width (float) β width of node border, defaults to 1
node_shape (str) β node shape, sets the shape of every node, defaults to βrounded_edgeβ
node_shape_attr (str | Callable) β If string type, it refers to
Nodeattribute for node shape. If callable type, it takes in the node itself and returns the node shape. This sets the shape of custom nodes, and overrides default node_shape, defaults to Noneedge_arrow (str) β edge arrow style from parent to itself, sets the arrow style of every edge, defaults to βnormalβ
edge_arrow_attr (str | Callable) β If string type, it refers to
Nodeattribute for edge arrow style. If callable type, it takes in the node itself and returns the edge arrow style. This sets the edge arrow style of custom nodes from parent to itself, and overrides default edge_arrow, defaults to Noneedge_label (str) β
Nodeattribute for edge label from parent to itself, defaults to Nonenode_attr (str | Callable) β If string type, it refers to
Nodeattribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour, node_border_colour, and node_border_width, defaults to None
- Returns:
(str)
- bigtree.tree.export.tree_to_nested_dict(tree: T, name_key: str = 'name', child_key: str = 'children', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0) Dict[str, Any]ΒΆ
Export tree to nested dictionary.
All descendants from tree will be exported, tree can be the root node or child node of tree.
Exported dictionary will have key as node attribute names, and children as a nested recursive dictionary.
>>> from bigtree import Node, tree_to_nested_dict >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> tree_to_nested_dict(root, all_attrs=True) {'name': 'a', 'age': 90, 'children': [{'name': 'b', 'age': 65, 'children': [{'name': 'd', 'age': 40}, {'name': 'e', 'age': 35}]}, {'name': 'c', 'age': 60}]}
- Parameters:
tree (Node) β tree to be exported
name_key (str) β dictionary key for node.node_name, defaults to βnameβ
child_key (str) β dictionary key for list of children, optional
attr_dict (Dict[str, str]) β dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional
all_attrs (bool) β indicator whether to retrieve all
Nodeattributes, overrides attr_dict, defaults to Falsemax_depth (int) β maximum depth to export tree, optional
- Returns:
(Dict[str, Any])
- bigtree.tree.export.tree_to_newick(tree: T, intermediate_node_name: bool = True, length_attr: str = '', length_sep: str | NewickCharacter = NewickCharacter.SEP, attr_list: Iterable[str] = [], attr_prefix: str = '&&NHX:', attr_sep: str | NewickCharacter = NewickCharacter.SEP) strΒΆ
Export tree to Newick notation. Useful for describing phylogenetic tree.
- In the Newick Notation (or New Hampshire Notation),
Tree is represented in round brackets i.e., (child1,child2,child3)parent.
If there are nested tree, they will be in nested round brackets i.e., ((grandchild1)child1,(grandchild2,grandchild3)child2)parent.
If there is length attribute, they will be beside the name i.e., (child1:0.5,child2:0.1)parent.
If there are other attributes, attributes are represented in square brackets i.e., (child1:0.5[S:human],child2:0.1[S:human])parent[S:parent].
- Customizations include:
Omitting names of root and intermediate nodes, default all node names are shown.
Changing length separator to other symbol, default is :.
Adding an attribute prefix, default is &&NHX:.
Changing the attribute separator to other symbol, default is :.
>>> from bigtree import Node, tree_to_newick >>> root = Node("a", species="human") >>> b = Node("b", age=65, species="human", parent=root) >>> c = Node("c", age=60, species="human", parent=root) >>> d = Node("d", age=40, species="human", parent=b) >>> e = Node("e", age=35, species="human", parent=b) >>> root.show() a βββ b β βββ d β βββ e βββ c
>>> tree_to_newick(root) '((d,e)b,c)a'
>>> tree_to_newick(root, length_attr="age") '((d:40,e:35)b:65,c:60)a'
>>> tree_to_newick(root, length_attr="age", attr_list=["species"]) '((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]'
- Parameters:
tree (Node) β tree to be exported
intermediate_node_name (bool) β indicator if intermediate nodes have node names, defaults to True
length_attr (str) β node length attribute to extract to beside name, optional
length_sep (str) β separator between node name and length, used if length_attr is non-empty, defaults to β:β
attr_list (Iterable[str]) β list of node attributes to extract into square bracket, optional
attr_prefix (str) β prefix before all attributes, within square bracket, used if attr_list is non-empty, defaults to β&&NHX:β
attr_sep (str) β separator between attributes, within square brackets, used if attr_list is non-empty, defaults to β:β
- Returns:
(str)
- bigtree.tree.export.tree_to_pillow(tree: T, width: int = 0, height: int = 0, start_pos: Tuple[int, int] = (10, 10), font_family: str = '', font_size: int = 12, font_colour: Tuple[int, int, int] | str = 'black', bg_colour: Tuple[int, int, int] | str = 'white', **kwargs: Any) Image.ImageΒΆ
Export tree to image (JPG, PNG). Image will be similar format as print_tree, accepts additional keyword arguments as input to yield_tree.
>>> from bigtree import Node, tree_to_pillow >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> pillow_image = tree_to_pillow(root)
Export to image (PNG, JPG) file, etc.
>>> pillow_image.save("assets/docstr/tree_pillow.png") >>> pillow_image.save("assets/docstr/tree_pillow.jpg")
- Parameters:
tree (Node) β tree to be exported
width (int) β width of image, optional as width of image is calculated automatically
height (int) β height of image, optional as height of image is calculated automatically
start_pos (Tuple[int, int]) β start position of text, (x-offset, y-offset), defaults to (10, 10)
font_family (str) β file path of font family, requires .ttf file, defaults to DejaVuSans
font_size (int) β font size, defaults to 12
font_colour (Union[Tuple[int, int, int], str]) β font colour, accepts tuple of RGB values or string, defaults to black
bg_colour (Union[Tuple[int, int, int], str]) β background of image, accepts tuple of RGB values or string, defaults to white
- Returns:
(PIL.Image.Image)
- bigtree.tree.export.yield_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, style: str = 'const', custom_style: Iterable[str] = []) Iterable[Tuple[str, str, T]]ΒΆ
Generator method for customizing printing of tree, starting from tree.
Able to select which node to print from, resulting in a subtree, using node_name_or_path
Able to customize for maximum depth to print, using max_depth
- Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style
Default style is const style
If style is set to custom, user can choose their own style for stem, branch and final stem icons
Stem, branch, and final stem symbol should have the same number of characters
Yield tree
>>> from bigtree import Node, yield_tree >>> root = Node("a", age=90) >>> b = Node("b", age=65, parent=root) >>> c = Node("c", age=60, parent=root) >>> d = Node("d", age=40, parent=b) >>> e = Node("e", age=35, parent=b) >>> for branch, stem, node in yield_tree(root): ... print(f"{branch}{stem}{node.node_name}") a βββ b β βββ d β βββ e βββ c
Yield Sub-tree
>>> for branch, stem, node in yield_tree(root, node_name_or_path="b"): ... print(f"{branch}{stem}{node.node_name}") b βββ d βββ e
>>> for branch, stem, node in yield_tree(root, max_depth=2): ... print(f"{branch}{stem}{node.node_name}") a βββ b βββ c
Available Styles
>>> for branch, stem, node in yield_tree(root, style="ansi"): ... print(f"{branch}{stem}{node.node_name}") a |-- b | |-- d | `-- e `-- c
>>> for branch, stem, node in yield_tree(root, style="ascii"): ... print(f"{branch}{stem}{node.node_name}") a |-- b | |-- d | +-- e +-- c
>>> for branch, stem, node in yield_tree(root, style="const"): ... print(f"{branch}{stem}{node.node_name}") a βββ b β βββ d β βββ e βββ c
>>> for branch, stem, node in yield_tree(root, style="const_bold"): ... print(f"{branch}{stem}{node.node_name}") a β£ββ b β β£ββ d β βββ e βββ c
>>> for branch, stem, node in yield_tree(root, style="rounded"): ... print(f"{branch}{stem}{node.node_name}") a βββ b β βββ d β β°ββ e β°ββ c
>>> for branch, stem, node in yield_tree(root, style="double"): ... print(f"{branch}{stem}{node.node_name}") a β ββ b β β ββ d β βββ e βββ c
Printing Attributes
>>> for branch, stem, node in yield_tree(root, style="const"): ... print(f"{branch}{stem}{node.node_name} [age={node.age}]") a [age=90] βββ b [age=65] β βββ d [age=40] β βββ e [age=35] βββ c [age=60]
- Parameters:
tree (Node) β tree to print
node_name_or_path (str) β node to print from, becomes the root node of printing, optional
max_depth (int) β maximum depth of tree to print, based on depth attribute, optional
style (str) β style of print, defaults to const
custom_style (Iterable[str]) β style of stem, branch and final stem, used when style is set to βcustomβ