⏰ Benchmark
+Visit this page for results of pytest-benchmark.
+ + + + + + + + + + + + + + + + +diff --git a/404.html b/404.html index 956d899e..c51d22b6 100644 --- a/404.html +++ b/404.html @@ -676,6 +676,8 @@ + + @@ -715,6 +717,27 @@ +
Visit this page for results of pytest-benchmark.
+ + + + + + + + + + + + + + + + +Tree Implementation and Methods for Python, integrated with Python list, dictionary, and pandas DataFrame.
It is pythonic, making it easy to learn and extendable to many types of workflows.
Install bigtree
with pip
or conda
and get up and running in minutes
Getting started
View demonstration on how to use bigtree
Reference
Articles relating to trees and bigtree
View articles
Do support if you like this project!
Support me
Related Links:
For Binary Tree implementation, there are 3 main components. Binary Node inherits from Node, so the components in Tree implementation are also available in Binary Tree.
"},{"location":"binarytree/#node","title":"\ud83c\udf3f Node","text":"BinaryNode
, Node with binary tree rulesAll notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
"},{"location":"changelog/#unreleased","title":"Unreleased","text":""},{"location":"changelog/#added","title":"Added","text":"docstr-coverage
.docstr-coverage
.hprint_tree
and hyield_tree
to be compatible with BinaryNode
where child nodes can be None type.__getitem__
and __delitem__
magic methods.__contains__
magic method.__iter__
magic method.find_children
, find_child
, and find_child_by_name
.hprint_tree
and hyield_tree
to allow hiding names of intermediate node.newick_to_tree
to handle invalid closing and use of apostrophe.tree_to_newick
to handle special characters by wrapping them in apostrophe.get_subtree
method to retrieve subtree.hprint_tree
and hyield_tree
to print and retrieve results for tree in horizontal orientation.hshow
method to print tree in horizontal orientation to console.newick_to_tree
to convert Newick notation to tree.tree_to_newick
to accept more parameters to parse length and attributes.tree_to_newick
.exact
parameter, default is prune and keep descendants.plot.py
utils file for coverage report.get_tree_diff
enhanced to compare tree attributes by taking in attr_list
parameter, and indicates difference with (~)
.get_tree_diff
compare tree structure by considering all nodes (previously only consider leaf nodes).__getitem__
and __delitem__
magic methods.append
and extend
methods.__contains__
magic method.__iter__
magic method. Results in children setter to only accept list/tuple/set instead of iterable types.tree_to_dot
accepts callable to set node and edge attrs for custom node (backward-compatible).tree_to_mermaid
accepts callable to set node shape attr, edge arrow attr and node attr for custom node (backward-compatible).tree_to_mermaid
to prevent possible path confusion (backward-compatible).shift_and_replace_nodes
and copy_and_replace_nodes_from_tree_to_tree
in README.shift_and_replace_nodes
.copy_and_replace_nodes_from_tree_to_tree
.replace_logic
.tree_to_mermaid
.clone_tree
.yield_tree
and print_tree
.tree_to_pillow
function to reference online font file instead of relative path.pandas
optional dependency.to_dataframe
method is called on empty calendar.prune_path
and max_depth
.get_attr
method to allow default return value.add_path_to_tree
, dataframe_to_tree
, dataframe_to_tree_by_relation
to allow custom node types that takes in constructor arguments.str
type besides int
type.nested_dict_to_tree
to throw TypeError if child_key is not list type.path_name
to allow different node name of different dtypes; map everything to string type.find_relative_path
to find relative path from node.zigzag_iter
and zigzaggroup_iter
Tree traversal methods.path_name
to reduce number of recursive calls to root node for sep
.list_to_tree_by_relation
and dataframe_to_tree_by_relation
method to allow duplicate intermediate nodes (default is false).node_shape
parameter in dag_to_dot
export function for easier way to customize node shape.add_dict_to_tree_by_name
method rename argument from path_attrs
to name_attrs
.tree_to_dot
to handle cases when not all nodes have edge_attr
.dag_to_dot
to perform dictionary copy to prevent style from being overridden for child nodes.dataframe_to_tree
to handle case when path column is not the first column.Iterable
instead of List
for list_to_tree
and list_to_tree_by_relation
methods.sep
.show
method to print tree to console.sep
parameter to constructor instead of using getter and setter methods to set sep
.from_paths
for faster search performance, added with_full_path
parameter.to_paths
to be full path for faster search performance.to_paths
.sep
in paths by performing string replacement at the start.copy=True
.sep
differing in from_paths
and to_paths
which should not throw error.find_child
and find_children
to find single child or multiple children based on user-defined condition.numpy
package, only reject None
attributes when creating tree from DataFrame (previously it rejects [None]
).numpy
package, enhance test cases.find_children
to find_child_by_name
for clarity.mypy
.sep
of tree differing from the sep
in from_paths
and to_paths
.mypy
, added type checks to pre-commit hooks.go_to
method to be consistent with List[List[DAGNode]]
type.yield_tree
if node_name_or_path
is not found.print_tree
checking attributes with hasattr
to handle cases of null or 0 value attributes, add more test cases.node_shape
parameter in tree_to_dot
export function for easier way to customize node shape.go_to
BaseNode method to travel from one node to another node from the same tree.go_to
DAGNode method to travel from one node to another node from the same DAG.merge_leaves
type of modification, enhance documentation to provide more examples and illustrations.str_to_tree
accept prefixes to support unicode characters in node names.str_to_tree
to construct tree from tree string.tree_to_dot
to perform dictionary copy to prevent style from being overridden for child nodes.BNode
to BinaryNode
, and construct method list_to_btree
to list_to_binarytree
.print_tree
output to image using Pillow package.merge_children
argument not working as expected.merge_children
argument not working as expected.dataframe_to_tree_by_relation
unable to find parent node.bgcolor
to bg_colour
.list_to_tree_tuples
to list_to_tree_by_relation
.sep
for nested_dict_to_tree
.bigtree is a tree implementation package for Python. It integrates with Python lists, dictionaries, and pandas DataFrame.
Thank you for taking the time to contribute. Contributing to this package is an excellent opportunity to dive into tree implementations.
"},{"location":"contributing/#set-up","title":"Set Up","text":"First, fork the repository and clone the forked repository.
$ git clone git@github.com:<your-username>/bigtree.git\n
Next, create a virtual environment and activate it.
$ conda create -n bigtree_venv python=3.10\n$ conda activate bigtree_venv\n
To check if it worked,
$ which pip\n/<some directory>/envs/bigtree_venv/bin/pip\n
From the project folder, install the required python packages locally in editable mode and set up pre-commit checks.
$ python -m pip install -e \".[all]\"\n$ python -m pip install pre-commit\n$ pre-commit install\n
"},{"location":"contributing/#developing","title":"Developing","text":"After making your changes, create a new branch, add and commit your changed files. In this example, lets assume the changed file is README.md
. If there are any pre-commit changes and/or comments, do modify, re-add and re-commit your files.
$ git checkout -b chore/update-readme\n$ git add README.md\n$ git commit -m \"chore: updated README\"\n
Push your changes to your created branch and create a pull request from your fork.
$ git push origin chore/update-readme\n
"},{"location":"contributing/#testing-and-documentation","title":"Testing and Documentation","text":"If there are changes related to code, please make sure that the unit tests pass and the code coverage is 100%.
$ python -m pip install pytest coverage\n$ pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=bigtree\n
Make sure your add/update the tests and documentations accordingly.
If there are changes to the docstrings and/or sample codes in the docstring, do run the following lines of code to generate the coverage report and test report for docstrings. Refer to the console log for information on the file location of the reports.
$ python -m pip install hatch\n$ hatch run docs:coverage\n$ hatch run docs:doctest\n
"},{"location":"contributing/#convention-and-standards","title":"Convention and Standards","text":"When creating branches, it is recommended to create them in the format type/action
. For example,
$ git checkout -b feat/add-this\n
When performing commits, it is also recommended to follow conventional commits when writing commit messages.
During pre-commit checks, this project checks and formats code using black
, flake8
, isort
, and mypy
.
For testing, this project uses pytest
and coverage
package for testing of codes, and docstr-coverage
and doctest
package for testing of docstrings.
Please open an issue to discuss important changes before embarking on an implementation.
"},{"location":"dag/","title":"\ud83c\udf34 Directed Acyclic Graph (DAG)","text":"For Directed Acyclic Graph (DAG) implementation, there are 4 main components.
"},{"location":"dag/#node","title":"\ud83c\udf3c Node","text":"DAGNode
, extendable class for constructing Directed Acyclic Graph (DAG)Tree Implementation and Methods for Python, integrated with Python list, dictionary, and pandas DataFrame.
It is pythonic, making it easy to learn and extendable to many types of workflows.
Install bigtree
with pip
or conda
and get up and running in minutes
Getting started
View demonstration on how to use bigtree
Reference
Articles relating to trees and bigtree
View articles
Do support if you like this project!
Support me
Related Links:
There are two ways to install bigtree
, with pip (recommended) or conda.
To install bigtree
, run the following line in command prompt:
If tree needs to use pandas methods, it requires additional dependencies. Run the following line in command prompt:
pip install 'bigtree[pandas]'If tree needs to be exported to image, it requires additional dependencies. Run the following lines in command prompt:
pip install 'bigtree[image]'brew install gprof2dot # for MacOSconda install graphviz # for WindowsAlternatively, install all optional dependencies with the following line in command prompt:
pip install 'bigtree[all]'"},{"location":"install/#installation-with-conda","title":"Installation with conda","text":"To install bigtree
with conda, run the following line in command prompt:
For Tree implementation, there are 9 main components.
"},{"location":"tree/#node","title":"\ud83c\udf3a Node","text":"BaseNode
, extendable classNode
, BaseNode with node name attributeNode
, using parent and children constructorsNode
typeConstruct Binary Tree from a list.
"},{"location":"bigtree/binarytree/construct/#binary-tree-construct-methods","title":"Binary Tree Construct Methods","text":"Construct Binary Tree from Using heapq structure Add node attributes Listlist_to_binarytree
No"},{"location":"bigtree/binarytree/construct/#bigtree.binarytree.construct","title":"bigtree.binarytree.construct","text":""},{"location":"bigtree/binarytree/construct/#bigtree.binarytree.construct.list_to_binarytree","title":"list_to_binarytree","text":"list_to_binarytree(heapq_list, node_type=BinaryNode)\n
Construct tree from a list of numbers (int or float) in heapq format.
Examples:
>>> from bigtree import list_to_binarytree, tree_to_dot\n>>> nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>> root = list_to_binarytree(nums_list)\n>>> root.show()\n1\n\u251c\u2500\u2500 2\n\u2502 \u251c\u2500\u2500 4\n\u2502 \u2502 \u251c\u2500\u2500 8\n\u2502 \u2502 \u2514\u2500\u2500 9\n\u2502 \u2514\u2500\u2500 5\n\u2502 \u2514\u2500\u2500 10\n\u2514\u2500\u2500 3\n \u251c\u2500\u2500 6\n \u2514\u2500\u2500 7\n>>> graph = tree_to_dot(root, node_colour=\"gold\")\n>>> graph.write_png(\"assets/construct_binarytree.png\")\n
Parameters:
Name Type Description Defaultheapq_list
List[int]
list containing integer node names, ordered in heapq fashion
requirednode_type
Type[BinaryNode]
node type of tree to be created, defaults to BinaryNode
BinaryNode
Returns:
Type DescriptionBinaryNode
(BinaryNode)
"},{"location":"bigtree/dag/","title":"\ud83c\udf34 Directed Acyclic Graph (DAG)","text":""},{"location":"bigtree/dag/construct/","title":"\u2728 Construct","text":"Construct Directed Acyclic Graph (DAG) from list, dictionary, and pandas DataFrame.
"},{"location":"bigtree/dag/construct/#dag-construct-methods","title":"DAG Construct Methods","text":"Construct DAG from Using parent-child relation Add node attributes Listlist_to_dag
No Dictionary dict_to_dag
Yes DataFrame dataframe_to_dag
Yes These functions are not standalone functions. Under the hood, they have the following dependency,
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct","title":"bigtree.dag.construct","text":""},{"location":"bigtree/dag/construct/#bigtree.dag.construct.list_to_dag","title":"list_to_dag","text":"list_to_dag(relations, node_type=DAGNode)\n
Construct DAG from list of tuples containing parent-child names. Note that node names must be unique.
Examples:
>>> from bigtree import list_to_dag, dag_iterator\n>>> relations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\n>>> dag = list_to_dag(relations_list)\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultrelations
List[Tuple[str, str]]
list containing tuple of parent-child names
requirednode_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct.dict_to_dag","title":"dict_to_dag","text":"dict_to_dag(\n relation_attrs, parent_key=\"parents\", node_type=DAGNode\n)\n
Construct DAG from nested dictionary, key
: child name, value
: dictionary of parent names, attribute name, and attribute value. Note that node names must be unique.
Examples:
>>> from bigtree import dict_to_dag, dag_iterator\n>>> relation_dict = {\n... \"a\": {\"step\": 1},\n... \"b\": {\"step\": 1},\n... \"c\": {\"parents\": [\"a\", \"b\"], \"step\": 2},\n... \"d\": {\"parents\": [\"a\", \"c\"], \"step\": 2},\n... \"e\": {\"parents\": [\"d\"], \"step\": 3},\n... }\n>>> dag = dict_to_dag(relation_dict, parent_key=\"parents\")\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultrelation_attrs
Dict[str, Any]
dictionary containing node, node parents, and node attribute information, key: child name, value: dictionary of parent names, node attribute, and attribute value
requiredparent_key
str
key of dictionary to retrieve list of parents name, defaults to 'parent'
'parents'
node_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct.dataframe_to_dag","title":"dataframe_to_dag","text":"dataframe_to_dag(\n data,\n child_col=\"\",\n parent_col=\"\",\n attribute_cols=[],\n node_type=DAGNode,\n)\n
Construct DAG from pandas DataFrame. Note that node names must be unique.
child_col
and parent_col
specify columns for child name and parent name to construct DAG.attribute_cols
specify columns for node attribute for child name.child_col
takes first column, parent_col
takes second column, and all other columns are attribute_cols
.Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_dag, dag_iterator\n>>> relation_data = pd.DataFrame([\n... [\"a\", None, 1],\n... [\"b\", None, 1],\n... [\"c\", \"a\", 2],\n... [\"c\", \"b\", 2],\n... [\"d\", \"a\", 2],\n... [\"d\", \"c\", 2],\n... [\"e\", \"d\", 3],\n... ],\n... columns=[\"child\", \"parent\", \"step\"]\n... )\n>>> dag = dataframe_to_dag(relation_data)\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredchild_col
str
column of data containing child name information, defaults to '' if not set, it will take the first column of data
''
parent_col
str
column of data containing parent name information, defaults to '' if not set, it will take the second column of data
''
attribute_cols
List[str]
columns of data containing child node attribute information, if not set, it will take all columns of data except child_col
and parent_col
[]
node_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/export/","title":"\ud83d\udd28 Export","text":"Export Directed Acyclic Graph (DAG) to list, dictionary, and pandas DataFrame.
"},{"location":"bigtree/dag/export/#dag-export-methods","title":"DAG Export Methods","text":"Export DAG to Method Extract node attributes Listdag_to_list
No Dictionary dag_to_dict
Yes with attr_dict
or all_attrs
DataFrame dag_to_dataframe
Yes with attr_dict
or all_attrs
Dot (for .dot, .png, .svg, .jpeg, etc.) dag_to_dot
No"},{"location":"bigtree/dag/export/#bigtree.dag.export","title":"bigtree.dag.export","text":""},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_list","title":"dag_to_list","text":"dag_to_list(dag)\n
Export DAG to list of tuples containing parent-child names
Examples:
>>> from bigtree import DAGNode, dag_to_list\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_list(a)\n[('a', 'c'), ('a', 'd'), ('b', 'c'), ('c', 'd'), ('d', 'e')]\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredReturns:
Type DescriptionList[Tuple[str, str]]
(List[Tuple[str, str]])
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dict","title":"dag_to_dict","text":"dag_to_dict(\n dag, parent_key=\"parents\", attr_dict={}, all_attrs=False\n)\n
Export DAG to dictionary.
Exported dictionary will have key as child name, and parent names and node attributes as a nested dictionary.
Examples:
>>> from bigtree import DAGNode, dag_to_dict\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_dict(a, parent_key=\"parent\", attr_dict={\"step\": \"step no.\"})\n{'a': {'step no.': 1}, 'c': {'parent': ['a', 'b'], 'step no.': 2}, 'd': {'parent': ['a', 'c'], 'step no.': 2}, 'b': {'step no.': 1}, 'e': {'parent': ['d'], 'step no.': 3}}\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredparent_key
str
dictionary key for node.parent.node_name
, defaults to parents
'parents'
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 Node
attributes, defaults to False
False
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dataframe","title":"dag_to_dataframe","text":"dag_to_dataframe(\n dag,\n name_col=\"name\",\n parent_col=\"parent\",\n attr_dict={},\n all_attrs=False,\n)\n
Export DAG to pandas DataFrame.
Examples:
>>> from bigtree import DAGNode, dag_to_dataframe\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_dataframe(a, name_col=\"name\", parent_col=\"parent\", attr_dict={\"step\": \"step no.\"})\n name parent step no.\n0 a None 1\n1 c a 2\n2 d a 2\n3 b None 1\n4 c b 2\n5 d c 2\n6 e d 3\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredname_col
str
column name for node.node_name
, defaults to 'name'
'name'
parent_col
str
column name for node.parent.node_name
, defaults to 'parent'
'parent'
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 Node
attributes, defaults to False
False
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dot","title":"dag_to_dot","text":"dag_to_dot(\n dag,\n rankdir=\"TB\",\n bg_colour=\"\",\n node_colour=\"\",\n node_shape=\"\",\n edge_colour=\"\",\n node_attr=\"\",\n edge_attr=\"\",\n)\n
Export DAG or list of DAGs to image. Note that node names must be unique. Possible node attributes include style, fillcolor, shape.
Examples:
>>> from bigtree import DAGNode, dag_to_dot\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_graph = dag_to_dot(a)\n
Display image directly without saving (requires IPython)
>>> from IPython.display import Image, display\n>>> plt = Image(dag_graph.create_png())\n>>> display(plt)\n<IPython.core.display.Image object>\n
Export to image, dot file, etc.
>>> dag_graph.write_png(\"assets/docstr/tree_dag.png\")\n>>> dag_graph.write_dot(\"assets/docstr/tree_dag.dot\")\n
Export to string
>>> dag_graph.to_string()\n'strict digraph G {\\nrankdir=TB;\\nc [label=c];\\na [label=a];\\na -> c;\\nd [label=d];\\na [label=a];\\na -> d;\\nc [label=c];\\nb [label=b];\\nb -> c;\\nd [label=d];\\nc [label=c];\\nc -> d;\\ne [label=e];\\nd [label=d];\\nd -> e;\\n}\\n'\n
Parameters:
Name Type Description Defaultdag
Union[DAGNode, List[DAGNode]]
DAG or list of DAGs to be exported
requiredrankdir
str
set direction of graph layout, defaults to 'TB', can be 'BT, 'LR', 'RL'
'TB'
bg_colour
str
background color of image, defaults to ''
''
node_colour
str
fill colour of nodes, defaults to ''
''
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 ''
''
node_attr
str
node attribute for style, overrides node_colour, defaults to '' Possible node attributes include {\"style\": \"filled\", \"fillcolor\": \"gold\"}
''
edge_attr
str
edge attribute for style, overrides edge_colour, defaults to '' Possible edge attributes include {\"style\": \"bold\", \"label\": \"edge label\", \"color\": \"black\"}
''
Returns:
Type DescriptionDot
(pydot.Dot)
"},{"location":"bigtree/node/","title":"\ud83c\udf3f Node","text":""},{"location":"bigtree/node/basenode/","title":"\ud83c\udf31 BaseNode","text":""},{"location":"bigtree/node/basenode/#bigtree.node.basenode","title":"bigtree.node.basenode","text":""},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode","title":"BaseNode","text":"BaseNode(parent=None, children=None, **kwargs)\n
BaseNode extends any Python class to a tree node. Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other with parent
and children
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
Examples:
>>> from bigtree import Node, print_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65)\n>>> c = Node(\"c\", age=60)\n>>> d = Node(\"d\", age=40)\n>>> root.children = [b, c]\n>>> d.parent = b\n>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u2514\u2500\u2500 d [age=40]\n\u2514\u2500\u2500 c [age=60]\n
>>> from bigtree import Node\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65)\n>>> c = Node(\"c\", age=60)\n>>> d = Node(\"d\", age=40)\n>>> root >> b\n>>> root >> c\n>>> d << b\n>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u2514\u2500\u2500 d [age=40]\n\u2514\u2500\u2500 c [age=60]\n
Directly passing parent
argument.
>>> from bigtree import Node\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n
Directly passing children
argument.
>>> from bigtree import Node\n>>> d = Node(\"d\")\n>>> c = Node(\"c\")\n>>> b = Node(\"b\", children=[d])\n>>> a = Node(\"a\", children=[b, c])\n
BaseNode Creation
Node can be created by instantiating a BaseNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import Node\n>>> root = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
BaseNode Attributes
These are node attributes that have getter and/or setter methods.
Get and set other BaseNode
parent
: Get/set parent nodechildren
: Get/set child nodesGet other BaseNode
ancestors
: Get ancestors of node excluding self, iteratordescendants
: Get descendants of node excluding self, iteratorleaves
: Get all leaf node(s) from self, iteratorsiblings
: Get siblings of selfleft_sibling
: Get sibling left of selfright_sibling
: Get sibling right of selfGet BaseNode
configuration
node_path
: Get tuple of nodes from rootis_root
: Get indicator if self is root nodeis_leaf
: Get indicator if self is leaf noderoot
: Get root node of treedepth
: Get depth of selfmax_depth
: Get maximum depth from root to leaf nodeBaseNode Methods
These are methods available to be performed on BaseNode
.
Constructor methods
from_dict()
: Create BaseNode from dictionaryBaseNode
methods
describe()
: Get node information sorted by attributes, return list of tuplesget_attr(attr_name: str)
: Get value of node attributeset_attrs(attrs: dict)
: Set node attribute name(s) and value(s)go_to(node: Self)
: Get a path from own node to another node from same treeappend(node: Self)
: Add child to nodeextend(nodes: List[Self])
: Add multiple children to nodecopy()
: Deep copy selfsort()
: Sort child nodesproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.parents","title":"parentsproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Self, ...])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.sort","title":"sort","text":"sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.name
, reverse=True
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node('a')\n>>> c = Node(\"c\", parent=a)\n>>> b = Node(\"b\", parent=a)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 b\n>>> a.sort(key=lambda node: node.name)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
"},{"location":"bigtree/node/binarynode/","title":"\ud83c\udf38 BinaryNode","text":""},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode","title":"bigtree.node.binarynode","text":""},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode","title":"BinaryNode","text":"BinaryNode(\n name=\"\",\n left=None,\n right=None,\n parent=None,\n children=None,\n **kwargs\n)\n
Bases: Node
BinaryNode is an extension of Node, and is able to extend to any Python class for Binary Tree implementation. Nodes can have attributes if they are initialized from BinaryNode
, dictionary, or pandas DataFrame.
BinaryNode can be linked to each other with children
, left
, or right
setter methods. If initialized with children
, it must be length 2, denoting left and right child.
Examples:
>>> from bigtree import BinaryNode, print_tree\n>>> a = BinaryNode(1)\n>>> b = BinaryNode(2)\n>>> c = BinaryNode(3)\n>>> d = BinaryNode(4)\n>>> a.children = [b, c]\n>>> b.right = d\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 2\n\u2502 \u2514\u2500\u2500 4\n\u2514\u2500\u2500 3\n
Directly passing left
, right
, or children
argument.
>>> from bigtree import BinaryNode\n>>> d = BinaryNode(4)\n>>> c = BinaryNode(3)\n>>> b = BinaryNode(2, right=d)\n>>> a = BinaryNode(1, children=[b, c])\n
BinaryNode Creation
Node can be created by instantiating a BinaryNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import BinaryNode\n>>> a = BinaryNode.from_dict({\"name\": \"1\"})\n>>> a\nBinaryNode(name=1, val=1)\n
BinaryNode Attributes
These are node attributes that have getter and/or setter methods.
Get BinaryNode
configuration
left
: Get left childrenright
: Get right childrenproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.sep","title":"sepproperty
writable
","text":"sep\n
Get separator, gets from root node
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.path_name","title":"path_nameproperty
","text":"path_name\n
Get path name, separated by self.sep
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.left","title":"leftproperty
writable
","text":"left\n
Get left children
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.right","title":"rightproperty
writable
","text":"right\n
Get right children
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.parent","title":"parentproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Optional[Self]])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.show","title":"show","text":"show(**kwargs)\n
Print tree to console, takes in same keyword arguments as print_tree
function
hshow(**kwargs)\n
Print tree in horizontal orientation to console, takes in same keyword arguments as hprint_tree
function
sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.val
, reverse=True
Examples:
>>> from bigtree import BinaryNode, print_tree\n>>> a = BinaryNode(1)\n>>> c = BinaryNode(3, parent=a)\n>>> b = BinaryNode(2, parent=a)\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 3\n\u2514\u2500\u2500 2\n>>> a.sort(key=lambda node: node.val)\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 2\n\u2514\u2500\u2500 3\n
"},{"location":"bigtree/node/dagnode/","title":"\ud83c\udf3c DAGNode","text":""},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode","title":"bigtree.node.dagnode","text":""},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode","title":"DAGNode","text":"DAGNode(name='', parents=None, children=None, **kwargs)\n
Base DAGNode extends any Python class to a DAG node, for DAG implementation. In DAG implementation, a node can have multiple parents.
Parents and children cannot be reassigned once assigned, as Nodes are allowed to have multiple parents and children. If each node only has one parent, use Node
class. DAGNodes can have attributes if they are initialized from DAGNode
or dictionary.
DAGNode can be linked to each other with parents
and children
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> c.parents = [a, b]\n>>> c.children = [d]\n
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> a >> c\n>>> b >> c\n>>> d << c\n
Directly passing parents
argument.
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\", parents=[a, b])\n>>> d = DAGNode(\"d\", parents=[c])\n
Directly passing children
argument.
>>> from bigtree import DAGNode\n>>> d = DAGNode(\"d\")\n>>> c = DAGNode(\"c\", children=[d])\n>>> b = DAGNode(\"b\", children=[c])\n>>> a = DAGNode(\"a\", children=[c])\n
DAGNode Creation
Node can be created by instantiating a DAGNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import DAGNode\n>>> a = DAGNode.from_dict({\"name\": \"a\", \"age\": 90})\n
DAGNode Attributes
These are node attributes that have getter and/or setter methods.
Get and set other DAGNode
parents
: Get/set parent nodeschildren
: Get/set child nodesGet other DAGNode
ancestors
: Get ancestors of node excluding self, iteratordescendants
: Get descendants of node excluding self, iteratorsiblings
: Get siblings of selfGet DAGNode
configuration
node_name
: Get node name, without accessing name
directlyis_root
: Get indicator if self is root nodeis_leaf
: Get indicator if self is leaf nodeDAGNode Methods
These are methods available to be performed on DAGNode
.
Constructor methods
from_dict()
: Create DAGNode from dictionaryDAGNode
methods
describe()
: Get node information sorted by attributes, return list of tuplesget_attr(attr_name: str)
: Get value of node attributeset_attrs(attrs: dict)
: Set node attribute name(s) and value(s)go_to(node: Self)
: Get a path from own node to another node from same DAGcopy()
: Deep copy selfproperty
writable
","text":"parent\n
Do not allow parent
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.parents","title":"parentsproperty
writable
","text":"parents\n
Get parent nodes
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.dagnode import DAGNode\n>>> a = DAGNode('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nDAGNode(a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.go_to","title":"go_to","text":"go_to(node)\n
Get list of possible paths from current node to specified node from same tree
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> a >> c\n>>> b >> c\n>>> c >> d\n>>> a >> d\n>>> a.go_to(c)\n[[DAGNode(a, ), DAGNode(c, )]]\n>>> a.go_to(d)\n[[DAGNode(a, ), DAGNode(c, ), DAGNode(d, )], [DAGNode(a, ), DAGNode(d, )]]\n>>> a.go_to(b)\nTraceback (most recent call last):\n ...\nbigtree.utils.exceptions.TreeError: It is not possible to go to DAGNode(b, )\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionList[List[T]]
(List[List[Self]])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone DAGNode
Examples:
>>> from bigtree.node.dagnode import DAGNode\n>>> a = DAGNode('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/","title":"\ud83c\udf3a Node","text":""},{"location":"bigtree/node/node/#bigtree.node.node","title":"bigtree.node.node","text":""},{"location":"bigtree/node/node/#bigtree.node.node.Node","title":"Node","text":"Node(name='', sep='/', **kwargs)\n
Bases: BaseNode
Node is an extension of BaseNode, and is able to extend to any Python class. Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other with parent
and children
setter methods.
Examples:
>>> from bigtree import Node\n>>> a = Node(\"a\")\n>>> b = Node(\"b\")\n>>> c = Node(\"c\")\n>>> d = Node(\"d\")\n>>> b.parent = a\n>>> b.children = [c, d]\n
Directly passing parent
argument.
>>> from bigtree import Node\n>>> a = Node(\"a\")\n>>> b = Node(\"b\", parent=a)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n
Directly passing children
argument.
>>> from bigtree import Node\n>>> d = Node(\"d\")\n>>> c = Node(\"c\")\n>>> b = Node(\"b\", children=[c, d])\n>>> a = Node(\"a\", children=[b])\n
Node Creation
Node can be created by instantiating a Node
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Node Attributes
These are node attributes that have getter and/or setter methods.
Get and set Node
configuration
sep
: Get/set separator for path nameGet Node
configuration
node_name
: Get node name, without accessing name
directlypath_name
: Get path name from root, separated by sep
Node Methods
These are methods available to be performed on Node
.
Node
methods
show()
: Print tree to consolehshow()
: Print tree in horizontal orientation to consoleproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Self, ...])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.parents","title":"parentsproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.sep","title":"sepproperty
writable
","text":"sep\n
Get separator, gets from root node
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.path_name","title":"path_nameproperty
","text":"path_name\n
Get path name, separated by self.sep
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.sort","title":"sort","text":"sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.name
, reverse=True
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node('a')\n>>> c = Node(\"c\", parent=a)\n>>> b = Node(\"b\", parent=a)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 b\n>>> a.sort(key=lambda node: node.name)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.show","title":"show","text":"show(**kwargs)\n
Print tree to console, takes in same keyword arguments as print_tree
function
hshow(**kwargs)\n
Print tree in horizontal orientation to console, takes in same keyword arguments as hprint_tree
function
Construct Tree from list, dictionary, and pandas DataFrame.
To decide which method to use, consider your data type and data values.
Construct tree from Using full path Using parent-child relation Using notation Add node attributes Stringstr_to_tree
NA newick_to_tree
No (for str_to_tree
)Yes (for newick_to_tree
) List list_to_tree
list_to_tree_by_relation
NA No Dictionary dict_to_tree
nested_dict_to_tree
NA Yes DataFrame dataframe_to_tree
dataframe_to_tree_by_relation
NA Yes"},{"location":"bigtree/tree/construct/#tree-add-attributes-methods","title":"Tree Add Attributes Methods","text":"To add attributes to an existing tree,
Add attributes from Using full path Using node name Stringadd_path_to_tree
NA Dictionary add_dict_to_tree_by_path
add_dict_to_tree_by_name
DataFrame add_dataframe_to_tree_by_path
add_dataframe_to_tree_by_name
Note
If attributes are added to existing tree using full path, paths that previously did not exist will be added. If attributes are added to existing tree using node name, names that previously did not exist will not be created.
These functions are not standalone functions. Under the hood, they have the following dependency,
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct","title":"bigtree.tree.construct","text":""},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_path_to_tree","title":"add_path_to_tree","text":"add_path_to_tree(\n tree,\n path,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_attrs={},\n)\n
Add nodes and attributes to existing tree in-place, return node of path added. Adds to existing tree from list of path strings.
Path should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import add_path_to_tree, Node\n>>> root = Node(\"a\")\n>>> add_path_to_tree(root, \"a/b/c\")\nNode(/a/b/c, )\n>>> root.show()\na\n\u2514\u2500\u2500 b\n \u2514\u2500\u2500 c\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredpath
str
path to be added to tree
requiredsep
str
path separator for input path
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_attrs
Dict[str, Any]
attributes to add to node, key: attribute name, value: attribute value, optional
{}
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dict_to_tree_by_path","title":"add_dict_to_tree_by_path","text":"add_dict_to_tree_by_path(\n tree, path_attrs, sep=\"/\", duplicate_name_allowed=True\n)\n
Add nodes and attributes to tree in-place, return root of tree. Adds to existing tree from nested dictionary, key
: path, value
: dict of attribute name and attribute value.
Path should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import Node, add_dict_to_tree_by_path\n>>> root = Node(\"a\")\n>>> path_dict = {\n... \"a\": {\"age\": 90},\n... \"a/b\": {\"age\": 65},\n... \"a/c\": {\"age\": 60},\n... \"a/b/d\": {\"age\": 40},\n... \"a/b/e\": {\"age\": 35},\n... \"a/c/f\": {\"age\": 38},\n... \"a/b/e/g\": {\"age\": 10},\n... \"a/b/e/h\": {\"age\": 6},\n... }\n>>> root = add_dict_to_tree_by_path(root, path_dict)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredpath_attrs
Dict[str, Dict[str, Any]]
dictionary containing node path and attribute information, key: node path, value: dict of node attribute name and attribute value
requiredsep
str
path separator for input path_attrs
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dict_to_tree_by_name","title":"add_dict_to_tree_by_name","text":"add_dict_to_tree_by_name(\n tree, name_attrs, join_type=\"left\"\n)\n
Add attributes to tree, return new root of tree. Adds to existing tree from nested dictionary, key
: name, value
: dict of attribute name and attribute value.
Function can return all existing tree nodes or only tree nodes that are in the input dictionary keys depending on join type. Input dictionary keys that are not existing node names will be ignored. Note that if multiple nodes have the same name, attributes will be added to all nodes sharing the same name.
Examples:
>>> from bigtree import Node, add_dict_to_tree_by_name\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> name_dict = {\n... \"a\": {\"age\": 90},\n... \"b\": {\"age\": 65},\n... }\n>>> root = add_dict_to_tree_by_name(root, name_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredname_attrs
Dict[str, Dict[str, Any]]
dictionary containing node name and attribute information, key: node name, value: dict of node attribute name and attribute value
requiredjoin_type
str
join type with attribute, default of 'left' takes existing tree nodes, if join_type is set to 'inner' it will only take tree nodes that are in name_attrs
key and drop others
'left'
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dataframe_to_tree_by_path","title":"add_dataframe_to_tree_by_path","text":"add_dataframe_to_tree_by_path(\n tree,\n data,\n path_col=\"\",\n attribute_cols=[],\n sep=\"/\",\n duplicate_name_allowed=True,\n)\n
Add nodes and attributes to tree in-place, return root of tree.
path_col
and attribute_cols
specify columns for node path and attributes to add to existing tree. If columns are not specified, path_col
takes first column and all other columns are attribute_cols
Path in path column should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path in path column can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> import pandas as pd\n>>> from bigtree import add_dataframe_to_tree_by_path, Node\n>>> root = Node(\"a\")\n>>> path_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"a/b\", 65],\n... [\"a/c\", 60],\n... [\"a/b/d\", 40],\n... [\"a/b/e\", 35],\n... [\"a/c/f\", 38],\n... [\"a/b/e/g\", 10],\n... [\"a/b/e/h\", 6],\n... ],\n... columns=[\"PATH\", \"age\"]\n... )\n>>> root = add_dataframe_to_tree_by_path(root, path_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requireddata
DataFrame
data containing node path and attribute information
requiredpath_col
str
column of data containing path_name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
sep
str
path separator for input path_col
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dataframe_to_tree_by_name","title":"add_dataframe_to_tree_by_name","text":"add_dataframe_to_tree_by_name(\n tree,\n data,\n name_col=\"\",\n attribute_cols=[],\n join_type=\"left\",\n)\n
Add attributes to tree, return new root of tree.
name_col
and attribute_cols
specify columns for node name and attributes to add to existing tree. If columns are not specified, the first column will be taken as name column and all other columns as attributes.
Function can return all existing tree nodes or only tree nodes that are in the input data node names. Input data node names that are not existing node names will be ignored. Note that if multiple nodes have the same name, attributes will be added to all nodes sharing same name.
Examples:
>>> import pandas as pd\n>>> from bigtree import add_dataframe_to_tree_by_name, Node\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> name_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"b\", 65],\n... ],\n... columns=[\"NAME\", \"age\"]\n... )\n>>> root = add_dataframe_to_tree_by_name(root, name_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requireddata
DataFrame
data containing node name and attribute information
requiredname_col
str
column of data containing name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
column(s) of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
join_type
str
join type with attribute, default of 'left' takes existing tree nodes, if join_type is set to 'inner' it will only take tree nodes with attributes and drop the other nodes
'left'
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.str_to_tree","title":"str_to_tree","text":"str_to_tree(\n tree_string, tree_prefix_list=[], node_type=Node\n)\n
Construct tree from tree string
Examples:
>>> from bigtree import str_to_tree\n>>> tree_str = 'a\\n\u251c\u2500\u2500 b\\n\u2502 \u251c\u2500\u2500 d\\n\u2502 \u2514\u2500\u2500 e\\n\u2502 \u251c\u2500\u2500 g\\n\u2502 \u2514\u2500\u2500 h\\n\u2514\u2500\u2500 c\\n \u2514\u2500\u2500 f'\n>>> root = str_to_tree(tree_str, tree_prefix_list=[\"\u251c\u2500\u2500\", \"\u2514\u2500\u2500\"])\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaulttree_string
str
String to construct tree
requiredtree_prefix_list
List[str]
List of prefix to mark the end of tree branch/stem and start of node name, optional. If not specified, it will infer unicode characters and whitespace as prefix.
[]
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.list_to_tree","title":"list_to_tree","text":"list_to_tree(\n paths,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from list of path strings.
Path should contain Node
name, separated by sep
.
Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import list_to_tree\n>>> path_list = [\"a/b\", \"a/c\", \"a/b/d\", \"a/b/e\", \"a/c/f\", \"a/b/e/g\", \"a/b/e/h\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaultpaths
Iterable[str]
list containing path strings
requiredsep
str
path separator for input paths
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.list_to_tree_by_relation","title":"list_to_tree_by_relation","text":"list_to_tree_by_relation(\n relations, allow_duplicates=False, node_type=Node\n)\n
Construct tree from list of tuple containing parent-child names.
Since tree is created from parent-child names, only names of leaf nodes may be repeated. Error will be thrown if names of intermediate nodes are repeated as there will be confusion. This error can be ignored by setting allow_duplicates
to be True.
Examples:
>>> from bigtree import list_to_tree_by_relation\n>>> relations_list = [(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\"), (\"b\", \"e\"), (\"c\", \"f\"), (\"e\", \"g\"), (\"e\", \"h\")]\n>>> root = list_to_tree_by_relation(relations_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaultrelations
Iterable[Tuple[str, str]]
list containing tuple containing parent-child names
requiredallow_duplicates
bool
allow duplicate intermediate nodes such that child node will be tagged to multiple parent nodes, defaults to False
False
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dict_to_tree","title":"dict_to_tree","text":"dict_to_tree(\n path_attrs,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from nested dictionary using path, key
: path, value
: dict of attribute name and attribute value.
Path should contain Node
name, separated by sep
.
Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import dict_to_tree\n>>> path_dict = {\n... \"a\": {\"age\": 90},\n... \"a/b\": {\"age\": 65},\n... \"a/c\": {\"age\": 60},\n... \"a/b/d\": {\"age\": 40},\n... \"a/b/e\": {\"age\": 35},\n... \"a/c/f\": {\"age\": 38},\n... \"a/b/e/g\": {\"age\": 10},\n... \"a/b/e/h\": {\"age\": 6},\n... }\n>>> root = dict_to_tree(path_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultpath_attrs
Dict[str, Any]
dictionary containing path and node attribute information, key: path, value: dict of tree attribute and attribute value
requiredsep
str
path separator of input path_attrs
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.nested_dict_to_tree","title":"nested_dict_to_tree","text":"nested_dict_to_tree(\n node_attrs,\n name_key=\"name\",\n child_key=\"children\",\n node_type=Node,\n)\n
Construct tree from nested recursive dictionary.
key
: name_key
, child_key
, or any attributes key.value
of name_key
(str): node name.value
of child_key
(List[Dict[str, Any]]): list of dict containing name_key
and child_key
(recursive).Examples:
>>> from bigtree import nested_dict_to_tree\n>>> path_dict = {\n... \"name\": \"a\",\n... \"age\": 90,\n... \"children\": [\n... {\"name\": \"b\",\n... \"age\": 65,\n... \"children\": [\n... {\"name\": \"d\", \"age\": 40},\n... {\"name\": \"e\", \"age\": 35, \"children\": [\n... {\"name\": \"g\", \"age\": 10},\n... ]},\n... ]},\n... ],\n... }\n>>> root = nested_dict_to_tree(path_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n \u251c\u2500\u2500 d [age=40]\n \u2514\u2500\u2500 e [age=35]\n \u2514\u2500\u2500 g [age=10]\n
Parameters:
Name Type Description Defaultnode_attrs
Dict[str, Any]
dictionary containing node, children, and node attribute information, key: name_key
and child_key
value of name_key
(str): node name value of child_key
(List[Dict[str, Any]]): list of dict containing name_key
and child_key
(recursive)
name_key
str
key of node name, value is type str
'name'
child_key
str
key of child list, value is type list
'children'
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dataframe_to_tree","title":"dataframe_to_tree","text":"dataframe_to_tree(\n data,\n path_col=\"\",\n attribute_cols=[],\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from pandas DataFrame using path, return root of tree.
path_col
and attribute_cols
specify columns for node path and attributes to construct tree. If columns are not specified, path_col
takes first column and all other columns are attribute_cols
.
Path in path column can start from root node name
, or start with sep
.
Path in path column should contain Node
name, separated by sep
.
All paths should start from the same root node.
Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_tree\n>>> path_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"a/b\", 65],\n... [\"a/c\", 60],\n... [\"a/b/d\", 40],\n... [\"a/b/e\", 35],\n... [\"a/c/f\", 38],\n... [\"a/b/e/g\", 10],\n... [\"a/b/e/h\", 6],\n... ],\n... columns=[\"PATH\", \"age\"]\n... )\n>>> root = dataframe_to_tree(path_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredpath_col
str
column of data containing path_name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
sep
str
path separator of input path_col
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dataframe_to_tree_by_relation","title":"dataframe_to_tree_by_relation","text":"dataframe_to_tree_by_relation(\n data,\n child_col=\"\",\n parent_col=\"\",\n attribute_cols=[],\n allow_duplicates=False,\n node_type=Node,\n)\n
Construct tree from pandas DataFrame using parent and child names, return root of tree.
Since tree is created from parent-child names, only names of leaf nodes may be repeated. Error will be thrown if names of intermediate nodes are repeated as there will be confusion. This error can be ignored by setting allow_duplicates
to be True.
child_col
and parent_col
specify columns for child name and parent name to construct tree. attribute_cols
specify columns for node attribute for child name. If columns are not specified, child_col
takes first column, parent_col
takes second column, and all other columns are attribute_cols
.
Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_tree_by_relation\n>>> relation_data = pd.DataFrame([\n... [\"a\", None, 90],\n... [\"b\", \"a\", 65],\n... [\"c\", \"a\", 60],\n... [\"d\", \"b\", 40],\n... [\"e\", \"b\", 35],\n... [\"f\", \"c\", 38],\n... [\"g\", \"e\", 10],\n... [\"h\", \"e\", 6],\n... ],\n... columns=[\"child\", \"parent\", \"age\"]\n... )\n>>> root = dataframe_to_tree_by_relation(relation_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredchild_col
str
column of data containing child name information, defaults to None if not set, it will take the first column of data
''
parent_col
str
column of data containing parent name information, defaults to None if not set, it will take the second column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except child_col
and parent_col
[]
allow_duplicates
bool
allow duplicate intermediate nodes such that child node will be tagged to multiple parent nodes, defaults to False
False
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.newick_to_tree","title":"newick_to_tree","text":"newick_to_tree(\n tree_string,\n length_attr=\"length\",\n attr_prefix=\"&&NHX:\",\n node_type=Node,\n)\n
Construct tree from Newick notation, return root of tree.
In the Newick Notation (or New Hampshire Notation)
(child1,child2,child3)parent
.((grandchild1)child1,(grandchild2,grandchild3)child2)parent
.(child1:0.5,child2:0.1)parent
.(child1:0.5[S:human],child2:0.1[S:human])parent[S:parent]
.Variations supported
[
, ]
, (
, )
, :
, ,
) in node name, attribute name, and attribute values if they are enclosed in single quotes i.e., '(name:!)'.nodeN
with N representing a number.Examples:
>>> from bigtree import newick_to_tree\n>>> root = newick_to_tree(\"((d,e)b,c)a\")\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> root = newick_to_tree(\"((d:40,e:35)b:65,c:60)a\", length_attr=\"age\")\n>>> root.show(attr_list=[\"age\"])\na\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
>>> root = newick_to_tree(\n... \"((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]\",\n... length_attr=\"age\",\n... )\n>>> root.show(all_attrs=True)\na [species=human]\n\u251c\u2500\u2500 b [age=65, species=human]\n\u2502 \u251c\u2500\u2500 d [age=40, species=human]\n\u2502 \u2514\u2500\u2500 e [age=35, species=human]\n\u2514\u2500\u2500 c [age=60, species=human]\n
Parameters:
Name Type Description Defaulttree_string
str
Newick notation to construct tree
requiredlength_attr
str
attribute name to store node length, optional, defaults to 'length'
'length'
attr_prefix
str
prefix before all attributes, within square bracket, used to detect attributes, defaults to \"&&NHX:\"
'&&NHX:'
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/export/","title":"\ud83d\udd28 Export","text":""},{"location":"bigtree/tree/export/#tree-export-methods","title":"Tree Export Methods","text":"Export Tree to list, dictionary, and pandas DataFrame.
Export Tree to Method Command Line / Othersprint_tree
, yield_tree
, hprint_tree
, hyield_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_mermaid
Mermaid Markdown (for .md) tree_to_mermaid
"},{"location":"bigtree/tree/export/#tree-export-customizations","title":"Tree Export Customizations","text":"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 Othersprint_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."},{"location":"bigtree/tree/export/#bigtree.tree.export","title":"bigtree.tree.export","text":""},{"location":"bigtree/tree/export/#bigtree.tree.export.print_tree","title":"print_tree","text":"print_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n all_attrs=False,\n attr_list=[],\n attr_omit_null=False,\n attr_bracket=[\"[\", \"]\"],\n style=\"const\",\n custom_style=[],\n)\n
Print tree to console, starting from tree
.
node_name_or_path
max_depth
attr_name_filter
and all_attrs
attr_omit_null
attr_bracket
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 charactersExamples:
Printing tree
>>> from bigtree import Node, print_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> print_tree(root)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
Printing Sub-tree
>>> print_tree(root, node_name_or_path=\"b\")\nb\n\u251c\u2500\u2500 d\n\u2514\u2500\u2500 e\n
>>> print_tree(root, max_depth=2)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
Printing Attributes
>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
>>> print_tree(root, attr_list=[\"age\"], attr_bracket=[\"*(\", \")\"])\na *(age=90)\n\u251c\u2500\u2500 b *(age=65)\n\u2502 \u251c\u2500\u2500 d *(age=40)\n\u2502 \u2514\u2500\u2500 e *(age=35)\n\u2514\u2500\u2500 c *(age=60)\n
Available Styles
>>> print_tree(root, style=\"ansi\")\na\n|-- b\n| |-- d\n| `-- e\n`-- c\n
>>> print_tree(root, style=\"ascii\")\na\n|-- b\n| |-- d\n| +-- e\n+-- c\n
>>> print_tree(root, style=\"const\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> print_tree(root, style=\"const_bold\")\na\n\u2523\u2501\u2501 b\n\u2503 \u2523\u2501\u2501 d\n\u2503 \u2517\u2501\u2501 e\n\u2517\u2501\u2501 c\n
>>> print_tree(root, style=\"rounded\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2570\u2500\u2500 e\n\u2570\u2500\u2500 c\n
>>> print_tree(root, style=\"double\")\na\n\u2560\u2550\u2550 b\n\u2551 \u2560\u2550\u2550 d\n\u2551 \u255a\u2550\u2550 e\n\u255a\u2550\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
all_attrs
bool
indicator to show all attributes, defaults to False, overrides attr_list
and attr_omit_null
False
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
False
attr_bracket
List[str]
open and close bracket for all_attrs
or attr_list
['[', ']']
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of stem, branch and final stem, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.yield_tree","title":"yield_tree","text":"yield_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n style=\"const\",\n custom_style=[],\n)\n
Generator method for customizing printing of tree, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Yield tree
>>> from bigtree import Node, yield_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> for branch, stem, node in yield_tree(root):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
Yield Sub-tree
>>> for branch, stem, node in yield_tree(root, node_name_or_path=\"b\"):\n... print(f\"{branch}{stem}{node.node_name}\")\nb\n\u251c\u2500\u2500 d\n\u2514\u2500\u2500 e\n
>>> for branch, stem, node in yield_tree(root, max_depth=2):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
Available Styles
>>> for branch, stem, node in yield_tree(root, style=\"ansi\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n|-- b\n| |-- d\n| `-- e\n`-- c\n
>>> for branch, stem, node in yield_tree(root, style=\"ascii\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n|-- b\n| |-- d\n| +-- e\n+-- c\n
>>> for branch, stem, node in yield_tree(root, style=\"const\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> for branch, stem, node in yield_tree(root, style=\"const_bold\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u2523\u2501\u2501 b\n\u2503 \u2523\u2501\u2501 d\n\u2503 \u2517\u2501\u2501 e\n\u2517\u2501\u2501 c\n
>>> for branch, stem, node in yield_tree(root, style=\"rounded\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2570\u2500\u2500 e\n\u2570\u2500\u2500 c\n
>>> for branch, stem, node in yield_tree(root, style=\"double\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u2560\u2550\u2550 b\n\u2551 \u2560\u2550\u2550 d\n\u2551 \u255a\u2550\u2550 e\n\u255a\u2550\u2550 c\n
Printing Attributes
>>> for branch, stem, node in yield_tree(root, style=\"const\"):\n... print(f\"{branch}{stem}{node.node_name} [age={node.age}]\")\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
style
str
style of print, defaults to const
'const'
custom_style
Iterable[str]
style of stem, branch and final stem, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.hprint_tree","title":"hprint_tree","text":"hprint_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n intermediate_node_name=True,\n style=\"const\",\n custom_style=[],\n)\n
Print tree in horizontal orientation to console, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Printing tree
>>> from bigtree import Node, hprint_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> hprint_tree(root)\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path=\"b\")\n \u250c\u2500 d\n\u2500 b \u2500\u2524\n \u2514\u2500 e\n
>>> hprint_tree(root, max_depth=2)\n \u250c\u2500 b\n\u2500 a \u2500\u2524\n \u2514\u2500 c\n
Available Styles
>>> hprint_tree(root, style=\"ansi\")\n /- d\n /- b -+\n- a -+ \\- e\n \\- c\n
>>> hprint_tree(root, style=\"ascii\")\n +- d\n +- b -+\n- a -+ +- e\n +- c\n
>>> hprint_tree(root, style=\"const\")\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
>>> hprint_tree(root, style=\"const_bold\")\n \u250f\u2501 d\n \u250f\u2501 b \u2501\u252b\n\u2501 a \u2501\u252b \u2517\u2501 e\n \u2517\u2501 c\n
>>> hprint_tree(root, style=\"rounded\")\n \u256d\u2500 d\n \u256d\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2570\u2500 e\n \u2570\u2500 c\n
>>> hprint_tree(root, style=\"double\")\n \u2554\u2550 d\n \u2554\u2550 b \u2550\u2563\n\u2550 a \u2550\u2563 \u255a\u2550 e\n \u255a\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
intermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
True
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of icons, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.hyield_tree","title":"hyield_tree","text":"hyield_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n intermediate_node_name=True,\n style=\"const\",\n custom_style=[],\n)\n
Yield tree in horizontal orientation to console, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Printing tree
>>> from bigtree import Node, hyield_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> result = hyield_tree(root)\n>>> print(\"\\n\".join(result))\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path=\"b\")\n \u250c\u2500 d\n\u2500 b \u2500\u2524\n \u2514\u2500 e\n
>>> hprint_tree(root, max_depth=2)\n \u250c\u2500 b\n\u2500 a \u2500\u2524\n \u2514\u2500 c\n
Available Styles
>>> hprint_tree(root, style=\"ansi\")\n /- d\n /- b -+\n- a -+ \\- e\n \\- c\n
>>> hprint_tree(root, style=\"ascii\")\n +- d\n +- b -+\n- a -+ +- e\n +- c\n
>>> hprint_tree(root, style=\"const\")\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
>>> hprint_tree(root, style=\"const_bold\")\n \u250f\u2501 d\n \u250f\u2501 b \u2501\u252b\n\u2501 a \u2501\u252b \u2517\u2501 e\n \u2517\u2501 c\n
>>> hprint_tree(root, style=\"rounded\")\n \u256d\u2500 d\n \u256d\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2570\u2500 e\n \u2570\u2500 c\n
>>> hprint_tree(root, style=\"double\")\n \u2554\u2550 d\n \u2554\u2550 b \u2550\u2563\n\u2550 a \u2550\u2563 \u255a\u2550 e\n \u255a\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
intermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
True
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of icons, used when style
is set to 'custom'
[]
Returns:
Type DescriptionList[str]
(List[str])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_newick","title":"tree_to_newick","text":"tree_to_newick(\n tree,\n intermediate_node_name=True,\n length_attr=\"\",\n length_sep=NewickCharacter.SEP,\n attr_list=[],\n attr_prefix=\"&&NHX:\",\n attr_sep=NewickCharacter.SEP,\n)\n
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]
.
:
.&&NHX:
.:
.Examples:
>>> from bigtree import Node, tree_to_newick\n>>> root = Node(\"a\", species=\"human\")\n>>> b = Node(\"b\", age=65, species=\"human\", parent=root)\n>>> c = Node(\"c\", age=60, species=\"human\", parent=root)\n>>> d = Node(\"d\", age=40, species=\"human\", parent=b)\n>>> e = Node(\"e\", age=35, species=\"human\", parent=b)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> tree_to_newick(root)\n'((d,e)b,c)a'\n
>>> tree_to_newick(root, length_attr=\"age\")\n'((d:40,e:35)b:65,c:60)a'\n
>>> tree_to_newick(root, length_attr=\"age\", attr_list=[\"species\"])\n'((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]'\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredintermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
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 \":\"
SEP
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:\"
'&&NHX:'
attr_sep
str
separator between attributes, within square brackets, used if attr_list is non-empty, defaults to \":\"
SEP
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dict","title":"tree_to_dict","text":"tree_to_dict(\n tree,\n name_key=\"name\",\n parent_key=\"\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n skip_depth=0,\n leaf_only=False,\n)\n
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.
Examples:
>>> from bigtree import Node, tree_to_dict\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_dict(root, name_key=\"name\", parent_key=\"parent\", attr_dict={\"age\": \"person age\"})\n{'/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}}\n
For a subset of a tree
>>> tree_to_dict(c, name_key=\"name\", parent_key=\"parent\", attr_dict={\"age\": \"person age\"})\n{'/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredname_key
str
dictionary key for node.node_name
, defaults to 'name'
'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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
skip_depth
int
number of initial depths to skip, optional
0
leaf_only
bool
indicator to retrieve only information from leaf nodes
False
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_nested_dict","title":"tree_to_nested_dict","text":"tree_to_nested_dict(\n tree,\n name_key=\"name\",\n child_key=\"children\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n)\n
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.
Examples:
>>> from bigtree import Node, tree_to_nested_dict\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_nested_dict(root, all_attrs=True)\n{'name': 'a', 'age': 90, 'children': [{'name': 'b', 'age': 65, 'children': [{'name': 'd', 'age': 40}, {'name': 'e', 'age': 35}]}, {'name': 'c', 'age': 60}]}\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredname_key
str
dictionary key for node.node_name
, defaults to 'name'
'name'
child_key
str
dictionary key for list of children, optional
'children'
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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dataframe","title":"tree_to_dataframe","text":"tree_to_dataframe(\n tree,\n path_col=\"path\",\n name_col=\"name\",\n parent_col=\"\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n skip_depth=0,\n leaf_only=False,\n)\n
Export tree to pandas DataFrame.
All descendants from tree
will be exported, tree
can be the root node or child node of tree.
Examples:
>>> from bigtree import Node, tree_to_dataframe\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_dataframe(root, name_col=\"name\", parent_col=\"parent\", path_col=\"path\", attr_dict={\"age\": \"person age\"})\n path name parent person age\n0 /a a None 90\n1 /a/b b a 65\n2 /a/b/d d b 40\n3 /a/b/e e b 35\n4 /a/c c a 60\n
For a subset of a tree.
>>> tree_to_dataframe(b, name_col=\"name\", parent_col=\"parent\", path_col=\"path\", attr_dict={\"age\": \"person age\"})\n path name parent person age\n0 /a/b b a 65\n1 /a/b/d d b 40\n2 /a/b/e e b 35\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredpath_col
str
column name for node.path_name
, defaults to 'path'
'path'
name_col
str
column name for node.node_name
, defaults to 'name'
'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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
skip_depth
int
number of initial depths to skip, optional
0
leaf_only
bool
indicator to retrieve only information from leaf nodes
False
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dot","title":"tree_to_dot","text":"tree_to_dot(\n tree,\n directed=True,\n rankdir=\"TB\",\n bg_colour=\"\",\n node_colour=\"\",\n node_shape=\"\",\n edge_colour=\"\",\n node_attr=\"\",\n edge_attr=\"\",\n)\n
Export tree or list of trees to image. Possible node attributes include style, fillcolor, shape.
Examples:
>>> from bigtree import Node, tree_to_dot\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> graph = tree_to_dot(root)\n
Display image directly without saving (requires IPython)
>>> from IPython.display import Image, display\n>>> plt = Image(graph.create_png())\n>>> display(plt)\n<IPython.core.display.Image object>\n
Export to image, dot file, etc.
>>> graph.write_png(\"assets/docstr/tree.png\")\n>>> graph.write_dot(\"assets/docstr/tree.dot\")\n
Export to string
>>> graph.to_string()\n'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'\n
Defining node and edge attributes (using node attribute)
>>> class CustomNode(Node):\n... def __init__(self, name, node_shape=\"\", edge_label=\"\", **kwargs):\n... super().__init__(name, **kwargs)\n... self.node_shape = node_shape\n... self.edge_label = edge_label\n...\n... @property\n... def edge_attr(self):\n... if self.edge_label:\n... return {\"label\": self.edge_label}\n... return {}\n...\n... @property\n... def node_attr(self):\n... if self.node_shape:\n... return {\"shape\": self.node_shape}\n... return {}\n>>>\n>>>\n>>> root = CustomNode(\"a\", node_shape=\"circle\")\n>>> b = CustomNode(\"b\", edge_label=\"child\", parent=root)\n>>> c = CustomNode(\"c\", edge_label=\"child\", parent=root)\n>>> d = CustomNode(\"d\", node_shape=\"square\", edge_label=\"child\", parent=b)\n>>> e = CustomNode(\"e\", node_shape=\"square\", edge_label=\"child\", parent=b)\n>>> graph = tree_to_dot(root, node_colour=\"gold\", node_shape=\"diamond\", node_attr=\"node_attr\", edge_attr=\"edge_attr\")\n>>> graph.write_png(\"assets/export_tree_dot.png\")\n
Alternative way to define node and edge attributes (using callable function)
>>> def get_node_attribute(node: Node):\n... if node.is_leaf:\n... return {\"shape\": \"square\"}\n... return {\"shape\": \"circle\"}\n>>>\n>>>\n>>> root = CustomNode(\"a\")\n>>> b = CustomNode(\"b\", parent=root)\n>>> c = CustomNode(\"c\", parent=root)\n>>> d = CustomNode(\"d\", parent=b)\n>>> e = CustomNode(\"e\", parent=b)\n>>> graph = tree_to_dot(root, node_colour=\"gold\", node_attr=get_node_attribute)\n>>> graph.write_png(\"assets/export_tree_dot_callable.png\")\n
Parameters:
Name Type Description Defaulttree
Node / List[Node]
tree or list of trees to be exported
requireddirected
bool
indicator whether graph should be directed or undirected, defaults to True
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)
'TB'
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 Node
attribute 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 Node
attribute 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:
Type DescriptionDot
(pydot.Dot)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_pillow","title":"tree_to_pillow","text":"tree_to_pillow(\n tree,\n width=0,\n height=0,\n start_pos=(10, 10),\n font_family=\"\",\n font_size=12,\n font_colour=\"black\",\n bg_colour=\"white\",\n **kwargs\n)\n
Export tree to image (JPG, PNG). Image will be similar format as print_tree
, accepts additional keyword arguments as input to yield_tree
.
Examples:
>>> from bigtree import Node, tree_to_pillow\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> pillow_image = tree_to_pillow(root)\n
Export to image (PNG, JPG) file, etc.
>>> pillow_image.save(\"assets/docstr/tree_pillow.png\")\n>>> pillow_image.save(\"assets/docstr/tree_pillow.jpg\")\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredwidth
int
width of image, optional as width of image is calculated automatically
0
height
int
height of image, optional as height of image is calculated automatically
0
start_pos
Tuple[int, int]
start position of text, (x-offset, y-offset), defaults to (10, 10)
(10, 10)
font_family
str
file path of font family, requires .ttf file, defaults to DejaVuSans
''
font_size
int
font size, defaults to 12
12
font_colour
Union[Tuple[int, int, int], str]
font colour, accepts tuple of RGB values or string, defaults to black
'black'
bg_colour
Union[Tuple[int, int, int], str]
background of image, accepts tuple of RGB values or string, defaults to white
'white'
Returns:
Type DescriptionImage
(PIL.Image.Image)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_mermaid","title":"tree_to_mermaid","text":"tree_to_mermaid(\n tree,\n title=\"\",\n rankdir=\"TB\",\n line_shape=\"basis\",\n node_colour=\"\",\n node_border_colour=\"\",\n node_border_width=1,\n node_shape=\"rounded_edge\",\n node_shape_attr=\"\",\n edge_arrow=\"normal\",\n edge_arrow_attr=\"\",\n edge_label=\"\",\n node_attr=\"\",\n **kwargs\n)\n
Export tree to mermaid Markdown text. Accepts additional keyword arguments as input to yield_tree
.
title
rankdir
line_shape
node_colour
node_border_colour
node_border_width
node_shape
edge_arrow
node_attr
node_attr
node_attr
node_shape_attr
edge_arrow_attr
edge_label
Accepted Parameter Values
Possible rankdirTB
: top-to-bottomBT
: bottom-to-topLR
: left-to-rightRL
: right-to-leftbasis
bumpX
: used in LR or RL directionbumpY
cardinal
: undirectedcatmullRom
: undirectedlinear
:monotoneX
: used in LR or RL directionmonotoneY
natural
step
: used in LR or RL directionstepAfter
stepBefore
: used in LR or RL directionrounded_edge
: rectangular with rounded edgesstadium
: (_) shape, rectangular with rounded endssubroutine
: ||_|| shape, rectangular with additional line at the endscylindrical
: database nodecircle
: circularasymmetric
: >_| shaperhombus
: decision nodehexagon
: <_> shapeparallelogram
: /_/ shapeparallelogram_alt
: \\_\\ shape, inverted parallelogramtrapezoid
: /_\\ shapetrapezoid_alt
: \\_/ shape, inverted trapezoiddouble_circle
normal
: directed arrow, shaded arrowheadbold
: bold directed arrowdotted
: dotted directed arrowopen
: line, undirected arrowbold_open
: bold linedotted_open
: dotted lineinvisible
: no linecircle
: directed arrow with filled circle arrowheadcross
: directed arrow with cross arrowheaddouble_normal
: bidirectional directed arrowdouble_circle
: bidirectional directed arrow with filled circle arrowheaddouble_cross
: bidirectional directed arrow with cross arrowheadRefer 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.
Examples:
>>> from bigtree import tree_to_mermaid\n>>> root = Node(\"a\", node_shape=\"rhombus\")\n>>> b = Node(\"b\", edge_arrow=\"bold\", edge_label=\"Child 1\", parent=root)\n>>> c = Node(\"c\", edge_arrow=\"dotted\", edge_label=\"Child 2\", parent=root)\n>>> d = Node(\"d\", node_style=\"fill:yellow, stroke:black\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> graph = tree_to_mermaid(root)\n>>> print(graph)\n```mermaid\n%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0(\"a\") --> 0-0(\"b\")\n0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0(\"a\") --> 0-1(\"c\")\nclassDef default stroke-width:1\n```\n
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\")\n>>> print(graph)\n```mermaid\n%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0{\"a\"} ==>|Child 1| 0-0(\"b\")\n0-0:::class0-0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0{\"a\"} -.->|Child 2| 0-1(\"c\")\nclassDef default stroke-width:1\nclassDef class0-0-0 fill:yellow, stroke:black\n```\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredtitle
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)
'TB'
line_shape
str
line shape or curvature, defaults to 'basis'
'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
1
node_shape
str
node shape, sets the shape of every node, defaults to 'rounded_edge'
'rounded_edge'
node_shape_attr
str | Callable
If string type, it refers to Node
attribute 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 None
''
edge_arrow
str
edge arrow style from parent to itself, sets the arrow style of every edge, defaults to 'normal'
'normal'
edge_arrow_attr
str | Callable
If string type, it refers to Node
attribute 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 None
''
edge_label
str
Node
attribute for edge label from parent to itself, defaults to None
''
node_attr
str | Callable
If string type, it refers to Node
attribute 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:
Type Descriptionstr
(str)
"},{"location":"bigtree/tree/helper/","title":"\ud83d\udd27 Helper","text":"Helper functions that can come in handy.
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper","title":"bigtree.tree.helper","text":""},{"location":"bigtree/tree/helper/#bigtree.tree.helper.clone_tree","title":"clone_tree","text":"clone_tree(tree, node_type)\n
Clone tree to another Node
type. If the same type is needed, simply do a tree.copy().
Examples:
>>> from bigtree import BaseNode, Node, clone_tree\n>>> root = BaseNode(name=\"a\")\n>>> b = BaseNode(name=\"b\", parent=root)\n>>> clone_tree(root, Node)\nNode(/a, )\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to be cloned, must inherit from BaseNode
requirednode_type
Type[BaseNode]
type of cloned tree
requiredReturns:
Type DescriptionBaseNodeT
(BaseNode)
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.get_subtree","title":"get_subtree","text":"get_subtree(tree, node_name_or_path='', max_depth=0)\n
Get subtree based on node name or node path, and/or maximum depth of tree.
Examples:
>>> from bigtree import Node, get_subtree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=root)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 c\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Get subtree
>>> root_subtree = get_subtree(root, \"b\")\n>>> root_subtree.show()\nb\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 d\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requirednode_name_or_path
str
node name or path to get subtree, defaults to None
''
max_depth
int
maximum depth of subtree, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.prune_tree","title":"prune_tree","text":"prune_tree(\n tree, prune_path=\"\", exact=False, sep=\"/\", max_depth=0\n)\n
Prune tree by path or depth, returns the root of a copy of the original tree.
For pruning by prune_path
,
exact=True
, all descendants of prune path will be removed.For pruning by max_depth
,
max_depth
will be removed.Path should contain Node
name, separated by sep
.
Examples:
>>> from bigtree import Node, prune_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=root)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 c\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Prune (default is keep descendants)
>>> root_pruned = prune_tree(root, \"a/b\")\n>>> root_pruned.show()\na\n\u2514\u2500\u2500 b\n \u251c\u2500\u2500 c\n \u2514\u2500\u2500 d\n
Prune exact path
>>> root_pruned = prune_tree(root, \"a/b\", exact=True)\n>>> root_pruned.show()\na\n\u2514\u2500\u2500 b\n
Prune multiple paths
>>> root_pruned = prune_tree(root, [\"a/b/d\", \"a/e\"])\n>>> root_pruned.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Prune by depth
>>> root_pruned = prune_tree(root, max_depth=2)\n>>> root_pruned.show()\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 e\n
Parameters:
Name Type Description Defaulttree
Union[BinaryNode, Node]
existing tree
requiredprune_path
List[str] | str
prune path(s), all siblings along the prune path(s) will be removed
''
exact
bool
prune path(s) to be exactly the path, defaults to False (descendants of the path are retained)
False
sep
str
path separator of prune_path
'/'
max_depth
int
maximum depth of pruned tree, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionUnion[BinaryNodeT, NodeT]
(Union[BinaryNode, Node])
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.get_tree_diff","title":"get_tree_diff","text":"get_tree_diff(\n tree, other_tree, only_diff=True, attr_list=[]\n)\n
Get difference of tree
to other_tree
, changes are relative to tree
.
Compares the difference in tree structure (default), but can also compare tree attributes using attr_list
. Function can return only the differences (default), or all original tree nodes and differences.
Comparing tree structure:
tree
.other_tree
but not tree
.tree
but not other_tree
.Examples:
>>> # Create original tree\n>>> from bigtree import Node, get_tree_diff, list_to_tree\n>>> root = list_to_tree([\"Downloads/Pictures/photo1.jpg\", \"Downloads/file1.doc\", \"Downloads/photo2.jpg\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 photo2.jpg\n
>>> # Create other tree\n>>> root_other = list_to_tree([\"Downloads/Pictures/photo1.jpg\", \"Downloads/Pictures/photo2.jpg\", \"Downloads/file1.doc\"])\n>>> root_other.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> # Get tree differences\n>>> tree_diff = get_tree_diff(root, root_other)\n>>> tree_diff.show()\nDownloads\n\u251c\u2500\u2500 photo2.jpg (-)\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg (+)\n
>>> tree_diff = get_tree_diff(root, root_other, only_diff=False)\n>>> tree_diff.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg (+)\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 photo2.jpg (-)\n
Comparing tree attributes
attr_list
.tree
, value in other_tree
]>>> # Create original tree\n>>> root = Node(\"Downloads\")\n>>> picture_folder = Node(\"Pictures\", parent=root)\n>>> photo2 = Node(\"photo1.jpg\", tags=\"photo1\", parent=picture_folder)\n>>> file1 = Node(\"file1.doc\", tags=\"file1\", parent=root)\n>>> root.show(attr_list=[\"tags\"])\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg [tags=photo1]\n\u2514\u2500\u2500 file1.doc [tags=file1]\n
>>> # Create other tree\n>>> root_other = Node(\"Downloads\")\n>>> picture_folder = Node(\"Pictures\", parent=root_other)\n>>> photo1 = Node(\"photo1.jpg\", tags=\"photo1-edited\", parent=picture_folder)\n>>> photo2 = Node(\"photo2.jpg\", tags=\"photo2-new\", parent=picture_folder)\n>>> file1 = Node(\"file1.doc\", tags=\"file1\", parent=root_other)\n>>> root_other.show(attr_list=[\"tags\"])\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg [tags=photo1-edited]\n\u2502 \u2514\u2500\u2500 photo2.jpg [tags=photo2-new]\n\u2514\u2500\u2500 file1.doc [tags=file1]\n
>>> # Get tree differences\n>>> tree_diff = get_tree_diff(root, root_other, attr_list=[\"tags\"])\n>>> tree_diff.show(attr_list=[\"tags\"])\nDownloads\n\u2514\u2500\u2500 Pictures\n \u251c\u2500\u2500 photo1.jpg (~) [tags=('photo1', 'photo1-edited')]\n \u2514\u2500\u2500 photo2.jpg (+)\n
Parameters:
Name Type Description Defaulttree
Node
tree to be compared against
requiredother_tree
Node
tree to be compared with
requiredonly_diff
bool
indicator to show all nodes or only nodes that are different (+/-), defaults to True
True
attr_list
List[str]
tree attributes to check for difference, defaults to empty list
[]
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/modify/","title":"\ud83d\udcdd Modify","text":"There are two types of modification available
from_paths
(list of paths) and to_paths
(list of paths).from_paths
(list of paths) and to_paths
(list of paths).In non-replacing scenario, there are several configurations available for customization.
Configuration Description Default Valuecopy
Indicates whether it is to shift the nodes, or copy the nodes False (nodes are shifted, not copied) to_tree
Indicates whether shifting/copying is within the same tree, or between different trees None (nodes are shifted/copied within the same tree) skippable
Skip shifting/copying of nodes if from_path cannot be found False (from-node must be found) overriding
Override existing node if it exists False (to-node must not exist) merge_children
Shift/copy children of from-node and remove intermediate parent node False (children are not merged) merge_leaves
Shift/copy leaves of from-node and remove all intermediate nodes False (leaves are not merged) delete_children
Shift/copy node only and delete its children False (nodes are shifted/copied together with children) In replacing scenario, all the configurations are also available except overriding
, merge_children
, and merge_leaves
as it is doing a one-to-one replacement. It is by default overriding, and there is nothing to merge.
Note
merge_children
and merge_leaves
cannot be simultaneously set to True
.
Note
Error will always be thrown if multiple from-nodes are found, paths in from_paths
must be unique.
There are several ways you can mix and match the tree modification methods. If you know all the parameters to choose, feel free to use copy_or_shift_logic
or replace_logic
methods as they are the most customizable. All other methods calls these 2 methods directly.
shift_nodes
Copy Same tree No copy_nodes
Copy Between two trees No copy_nodes_from_tree_to_tree
Any Any No copy_or_shift_logic
Shift Same tree Yes shift_and_replace_nodes
Copy Between two trees Yes copy_and_replace_nodes_from_tree_to_tree
Any Any Yes replace_logic
"},{"location":"bigtree/tree/modify/#tree-modification-illustration","title":"Tree Modification Illustration","text":""},{"location":"bigtree/tree/modify/#sample-tree-modification-shift-copy-delete","title":"Sample Tree Modification (Shift, Copy, Delete)","text":"Setting Sample path in from_paths
Sample path in to_paths
Description Default \"/a/c\" \"/a/b/c\" Shift/copy node c
Default \"/c\" \"/a/b/c\" Shift/copy node c
Default \"c\" \"/a/b/c\" Shift/copy node c
Default \"/a/e\" None Delete node e
skippable \"/a/c\" \"/a/b/c\" Shift/copy node c
, skip if \"/a/c\" cannot be found"},{"location":"bigtree/tree/modify/#sample-tree-modification-advanced","title":"Sample Tree Modification (Advanced)","text":"Setting Sample path in from_paths
Sample path in to_paths
Description overriding \"a/b/c\" \"a/d/c\" Shift/copy node c
, override if \"a/d/c\" exists merge_children \"a/b/c\" \"a/d/c\" If path not present: Shift/copy children of node c
to be children of node d
, removing node c
If path present: Shift/copy children of node c
to be merged with existing \"a/d/c\" children merge_children + overriding \"a/b/c\" \"a/d/c\" If path not present: Behaves like merge_childrenIf path present: Behaves like overriding merge_leaves \"a/b/c\" \"a/d/c\" If path not present: Shift/copy leaves of node c
to be children of node d
If path present: Shift/copy leaves of node c
to be merged with existing \"a/d/c\" children - merge_leaves + overriding \"a/b/c\" \"a/d/c\" If path not present: Behaves like merge_leavesIf path present: Behaves like overriding, but original node c
remains delete_children \"a/b\" \"a/d/b\" Shift/copy node b
only without any node b
children"},{"location":"bigtree/tree/modify/#bigtree.tree.modify","title":"bigtree.tree.modify","text":""},{"location":"bigtree/tree/modify/#bigtree.tree.modify.shift_nodes","title":"shift_nodes","text":"shift_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Shift nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
from_paths
, note that copy
must be set to False.If merge_children=True
,
to_path
is not present, it shifts children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it shifts leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained, original non-leaf nodes in from_path
are retained.Examples:
>>> from bigtree import list_to_tree, str_to_tree, shift_nodes\n>>> root = list_to_tree([\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... tree=root,\n... from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n... to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
To delete node,
>>> root = list_to_tree([\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(root, [\"Downloads/photo1.jpg\"], [None])\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 file1.doc\n
In overriding case,
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg\n
>>> shift_nodes(root, [\"Downloads/Misc/Pictures\"], [\"Downloads/Pictures\"], overriding=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In merge_children=True
case, child nodes are shifted instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_children=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_leaves=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 Applications\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 dummy\n\u2502 \u2514\u2500\u2500 Files\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 file1.doc\n
In delete_children=True
case, only the node is shifted without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo1.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
>>> shift_nodes(root, [\"Applications\"], [\"Downloads/Applications\"], delete_children=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Applications\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to shift node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_nodes","title":"copy_nodes","text":"copy_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
If merge_children=True
,
to_path
is not present, it copies children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.Examples:
>>> from bigtree import list_to_tree, str_to_tree, copy_nodes\n>>> root = list_to_tree([\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... tree=root,\n... from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n... to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In overriding case,
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg\n
>>> copy_nodes(root, [\"Downloads/Misc/Pictures\"], [\"Downloads/Pictures\"], overriding=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In merge_children=True
case, child nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_children=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_leaves=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 dummy\n\u2502 \u2514\u2500\u2500 Files\n\u2502 \u2514\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 file1.doc\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo1.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
>>> copy_nodes(root, [\"Applications\"], [\"Downloads/Applications\"], delete_children=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Applications\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.shift_and_replace_nodes","title":"shift_and_replace_nodes","text":"shift_and_replace_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n delete_children=False,\n with_full_path=False,\n)\n
Shift nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Examples:
>>> from bigtree import str_to_tree, shift_and_replace_nodes\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n
>>> shift_and_replace_nodes(root, [\"Downloads/Pictures\"], [\"Downloads/Misc/dummy\"])\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In delete_children=True
case, only the node is shifted without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n
>>> shift_and_replace_nodes(root, [\"Downloads/Pictures\"], [\"Downloads/Misc/dummy\"], delete_children=True)\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 Pictures\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to shift node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_nodes_from_tree_to_tree","title":"copy_nodes_from_tree_to_tree","text":"copy_nodes_from_tree_to_tree(\n from_tree,\n to_tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
If merge_children=True
,
to_path
is not present, it copies children of from_path
to_path
is present, and overriding=False
, original and new children are mergedto_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.If merge_leaves=True
,
to_path
is not present, it copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.Examples:
>>> from bigtree import Node, str_to_tree, copy_nodes_from_tree_to_tree\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 file1.doc\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
>>> root_other = Node(\"Documents\")\n>>> copy_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures\", \"Documents/New Misc/Misc\"],\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 New Misc\n \u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In overriding case,
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... overriding=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In merge_children=True
case, child nodes are copied instead of the parent node.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... merge_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo3.jpg\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... merge_leaves=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo3.jpg\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 photo2.jpg\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root_other = Node(\"Documents\")\n>>> root_other.show()\nDocuments\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... delete_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2514\u2500\u2500 Misc\n
Parameters:
Name Type Description Defaultfrom_tree
Node
tree to copy nodes from
requiredto_tree
Node
tree to copy nodes to
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_and_replace_nodes_from_tree_to_tree","title":"copy_and_replace_nodes_from_tree_to_tree","text":"copy_and_replace_nodes_from_tree_to_tree(\n from_tree,\n to_tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Examples:
>>> from bigtree import str_to_tree, copy_and_replace_nodes_from_tree_to_tree\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 file1.doc\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u251c\u2500\u2500 Pictures2\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc2\"\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 Misc2\n
>>> copy_and_replace_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures2/photo2.jpg\", \"Documents/Misc2\"],\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u251c\u2500\u2500 Pictures2\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc2\"\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 Misc2\n
>>> copy_and_replace_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures2/photo2.jpg\", \"Documents/Misc2\"],\n... delete_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 Pictures\n\u2514\u2500\u2500 Misc\n
Parameters:
Name Type Description Defaultfrom_tree
Node
tree to copy nodes from
requiredto_tree
Node
tree to copy nodes to
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_or_shift_logic","title":"copy_or_shift_logic","text":"copy_or_shift_logic(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n copy=False,\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n to_tree=None,\n with_full_path=False,\n)\n
Shift or copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
from_paths
, note that copy
must be set to False.If merge_children=True
,
to_path
is not present, it shifts/copies children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it shifts/copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained, original non-leaf nodes in from_path
are retained.Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
copy
bool
indicator to copy node, defaults to False
False
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to shift/copy node only without children, defaults to False
False
to_tree
Node
tree to copy to, defaults to None
None
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.replace_logic","title":"replace_logic","text":"replace_logic(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n copy=False,\n skippable=False,\n delete_children=False,\n to_tree=None,\n with_full_path=False,\n)\n
Shift or copy nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
copy
bool
indicator to copy node, defaults to False
False
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to shift/copy node only without children, defaults to False
False
to_tree
Node
tree to copy to, defaults to None
None
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/search/","title":"\ud83d\udd0d Search","text":"Search methods for Trees.
Search by One node One or more nodes General methodfind
, find_child
findall
, find_children
Node name find_name
, find_child_by_name
find_names
Node path find_path
, find_full_path
, find_relative_path
find_paths
, find_relative_path
Node attributes find_attr
find_attrs
"},{"location":"bigtree/tree/search/#bigtree.tree.search","title":"bigtree.tree.search","text":""},{"location":"bigtree/tree/search/#bigtree.tree.search.findall","title":"findall","text":"findall(\n tree, condition, max_depth=0, min_count=0, max_count=0\n)\n
Search tree for nodes matching condition (callable function).
Examples:
>>> from bigtree import Node, findall\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> findall(root, lambda node: node.age > 62)\n(Node(/a, age=90), Node(/a/b, age=65))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
max_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
min_count
int
checks for minimum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
max_count
int
checks for maximum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
Returns:
Type DescriptionTuple[T, ...]
(Tuple[BaseNode, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find","title":"find","text":"find(tree, condition, max_depth=0)\n
Search tree for single node matching condition (callable function).
Examples:
>>> from bigtree import Node, find\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find(root, lambda node: node.age == 65)\nNode(/a/b, age=65)\n>>> find(root, lambda node: node.age > 5)\nTraceback (most recent call last):\n ...\nbigtree.utils.exceptions.SearchError: Expected less than 1 element(s), found 4 elements\n(Node(/a, age=90), Node(/a/b, age=65), Node(/a/c, age=60), Node(/a/c/d, age=40))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
max_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionT
(BaseNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_name","title":"find_name","text":"find_name(tree, name, max_depth=0)\n
Search tree for single node matching name attribute.
Examples:
>>> from bigtree import Node, find_name\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_name(root, \"c\")\nNode(/a/c, age=60)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredname
str
value to match for name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_names","title":"find_names","text":"find_names(tree, name, max_depth=0)\n
Search tree for multiple node(s) matching name attribute.
Examples:
>>> from bigtree import Node, find_names\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"b\", age=40, parent=c)\n>>> find_names(root, \"c\")\n(Node(/a/c, age=60),)\n>>> find_names(root, \"b\")\n(Node(/a/b, age=65), Node(/a/c/b, age=40))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredname
str
value to match for name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[NodeT]
(Iterable[Node])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_relative_path","title":"find_relative_path","text":"find_relative_path(tree, path_name)\n
Search tree for single node matching relative path attribute.
Examples:
>>> from bigtree import Node, find_relative_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_relative_path(d, \"..\")\n(Node(/a/c, age=60),)\n>>> find_relative_path(d, \"../../b\")\n(Node(/a/b, age=65),)\n>>> find_relative_path(d, \"../../*\")\n(Node(/a/b, age=65), Node(/a/c, age=60))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (relative path) of path_name attribute
requiredReturns:
Type DescriptionIterable[NodeT]
(Iterable[Node])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_full_path","title":"find_full_path","text":"find_full_path(tree, path_name)\n
Search tree for single node matching path attribute.
find_path
but faster.Examples:
>>> from bigtree import Node, find_full_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_full_path(root, \"/a/c/d\")\nNode(/a/c/d, age=40)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) of path_name attribute
requiredReturns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_path","title":"find_path","text":"find_path(tree, path_name)\n
Search tree for single node matching path attribute.
Examples:
>>> from bigtree import Node, find_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_path(root, \"c\")\nNode(/a/c, age=60)\n>>> find_path(root, \"/c\")\nNode(/a/c, age=60)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) or trailing part (partial path) of path_name attribute
requiredReturns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_paths","title":"find_paths","text":"find_paths(tree, path_name)\n
Search tree for multiple nodes matching path attribute.
Examples:
>>> from bigtree import Node, find_paths\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"c\", age=40, parent=c)\n>>> find_paths(root, \"/a/c\")\n(Node(/a/c, age=60),)\n>>> find_paths(root, \"/c\")\n(Node(/a/c, age=60), Node(/a/c/c, age=40))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) or trailing part (partial path) of path_name attribute
requiredReturns:
Type DescriptionTuple[NodeT, ...]
(Tuple[Node, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_attr","title":"find_attr","text":"find_attr(tree, attr_name, attr_value, max_depth=0)\n
Search tree for single node matching custom attribute.
Examples:
>>> from bigtree import Node, find_attr\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_attr(root, \"age\", 65)\nNode(/a/b, age=65)\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredattr_name
str
attribute name to perform matching
requiredattr_value
Any
value to match for attr_name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_attrs","title":"find_attrs","text":"find_attrs(tree, attr_name, attr_value, max_depth=0)\n
Search tree for node(s) matching custom attribute.
Examples:
>>> from bigtree import Node, find_attrs\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=65, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_attrs(root, \"age\", 65)\n(Node(/a/b, age=65), Node(/a/c, age=65))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredattr_name
str
attribute name to perform matching
requiredattr_value
Any
value to match for attr_name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionTuple[BaseNode, ...]
(Tuple[BaseNode, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_children","title":"find_children","text":"find_children(tree, condition, min_count=0, max_count=0)\n
Search children for nodes matching condition (callable function).
Examples:
>>> from bigtree import Node, find_children\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_children(root, lambda node: node.age > 30)\n(Node(/a/b, age=65), Node(/a/c, age=60))\n
Parameters:
Name Type Description Defaulttree
BaseNode / DAGNode
tree to search for its children
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
min_count
int
checks for minimum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
max_count
int
checks for maximum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
Returns:
Type DescriptionTuple[Union[T, DAGNodeT], ...]
(BaseNode/DAGNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_child","title":"find_child","text":"find_child(tree, condition)\n
Search children for single node matching condition (callable function).
Examples:
>>> from bigtree import Node, find_child\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_child(root, lambda node: node.age > 62)\nNode(/a/b, age=65)\n
Parameters:
Name Type Description Defaulttree
BaseNode / DAGNode
tree to search for its child
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
Returns:
Type DescriptionUnion[T, DAGNodeT]
(BaseNode/DAGNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_child_by_name","title":"find_child_by_name","text":"find_child_by_name(tree, name)\n
Search tree for single node matching name attribute.
Examples:
>>> from bigtree import Node, find_child_by_name\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_child_by_name(root, \"c\")\nNode(/a/c, age=60)\n>>> find_child_by_name(c, \"d\")\nNode(/a/c/d, age=40)\n
Parameters:
Name Type Description Defaulttree
Node / DAGNode
tree to search, parent node
requiredname
str
value to match for name attribute, child node
requiredReturns:
Type DescriptionUnion[NodeT, DAGNodeT]
(Node/DAGNode)
"},{"location":"bigtree/utils/","title":"\ud83d\udd27 Utils","text":""},{"location":"bigtree/utils/iterators/","title":"\u27b0 Iterators","text":"Iterator methods for Trees and DAGs.
"},{"location":"bigtree/utils/iterators/#iterator-methods","title":"Iterator Methods","text":"Data Structure Algorithm Description Binary Tree In-order Traversal Depth-First Search, LNR Tree Pre-order Traversal Depth-First Search, NLR Tree Post-Order Traversal Depth-First Search, LRN Tree Level-Order Traversal Breadth-First Search Tree ZigZag Traversal Breadth-First Search Tree ZigZag Group Traversal Breadth-First Search DAG General Depth-First Search"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators","title":"bigtree.utils.iterators","text":""},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.inorder_iter","title":"inorder_iter","text":"inorder_iter(tree, filter_condition=None, max_depth=0)\n
Iterate through all children of a tree.
In-Order Iteration Algorithm, LNR 1. Recursively traverse the current node's left subtree. 2. Visit the current node. 3. Recursively traverse the current node's right subtree.
Examples:
>>> from bigtree import BinaryNode, list_to_binarytree, inorder_iter\n>>> num_list = [1, 2, 3, 4, 5, 6, 7, 8]\n>>> root = list_to_binarytree(num_list)\n>>> root.show()\n1\n\u251c\u2500\u2500 2\n\u2502 \u251c\u2500\u2500 4\n\u2502 \u2502 \u2514\u2500\u2500 8\n\u2502 \u2514\u2500\u2500 5\n\u2514\u2500\u2500 3\n \u251c\u2500\u2500 6\n \u2514\u2500\u2500 7\n
>>> [node.node_name for node in inorder_iter(root)]\n['8', '4', '2', '5', '1', '6', '3', '7']\n
>>> [node.node_name for node in inorder_iter(root, filter_condition=lambda x: x.node_name in [\"1\", \"4\", \"3\", \"6\", \"7\"])]\n['4', '1', '6', '3', '7']\n
>>> [node.node_name for node in inorder_iter(root, max_depth=3)]\n['4', '2', '5', '1', '6', '3', '7']\n
Parameters:
Name Type Description Defaulttree
BinaryNode
input tree
requiredfilter_condition
Optional[Callable[[BinaryNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[BinaryNodeT]
(Iterable[BinaryNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.preorder_iter","title":"preorder_iter","text":"preorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Pre-Order Iteration Algorithm, NLR 1. Visit the current node. 2. Recursively traverse the current node's left subtree. 3. Recursively traverse the current node's right subtree.
It is topologically sorted because a parent node is processed before its child nodes.
Examples:
>>> from bigtree import Node, list_to_tree, preorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in preorder_iter(root)]\n['a', 'b', 'd', 'e', 'g', 'h', 'c', 'f']\n
>>> [node.node_name for node in preorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'g', 'f']\n
>>> [node.node_name for node in preorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'b', 'd', 'c', 'f']\n
>>> [node.node_name for node in preorder_iter(root, max_depth=3)]\n['a', 'b', 'd', 'e', 'c', 'f']\n
Parameters:
Name Type Description Defaulttree
Union[BaseNode, DAGNode]
input tree
requiredfilter_condition
Optional[Callable[[T], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[T], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[T]
(Union[Iterable[BaseNode], Iterable[DAGNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.postorder_iter","title":"postorder_iter","text":"postorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Post-Order Iteration Algorithm, LRN 1. Recursively traverse the current node's left subtree. 2. Recursively traverse the current node's right subtree. 3. Visit the current node.
Examples:
>>> from bigtree import Node, list_to_tree, postorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in postorder_iter(root)]\n['d', 'g', 'h', 'e', 'b', 'f', 'c', 'a']\n
>>> [node.node_name for node in postorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['d', 'g', 'e', 'f', 'a']\n
>>> [node.node_name for node in postorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['d', 'b', 'f', 'c', 'a']\n
>>> [node.node_name for node in postorder_iter(root, max_depth=3)]\n['d', 'e', 'b', 'f', 'c', 'a']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.levelorder_iter","title":"levelorder_iter","text":"levelorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Level-Order Iteration Algorithm 1. Recursively traverse the nodes on same level.
Examples:
>>> from bigtree import Node, list_to_tree, levelorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in levelorder_iter(root)]\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n
>>> [node.node_name for node in levelorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'f', 'g']\n
>>> [node.node_name for node in levelorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'b', 'c', 'd', 'f']\n
>>> [node.node_name for node in levelorder_iter(root, max_depth=3)]\n['a', 'b', 'c', 'd', 'e', 'f']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.levelordergroup_iter","title":"levelordergroup_iter","text":"levelordergroup_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Level-Order Group Iteration Algorithm 1. Recursively traverse the nodes on same level, returns nodes level by level in a nested list.
Examples:
>>> from bigtree import Node, list_to_tree, levelordergroup_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root)]\n[['a'], ['b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n[['a'], [], ['d', 'e', 'f'], ['g']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n[['a'], ['b', 'c'], ['d', 'f']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, max_depth=3)]\n[['a'], ['b', 'c'], ['d', 'e', 'f']]\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[Iterable[BaseNodeT]]
(Iterable[Iterable[BaseNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.zigzag_iter","title":"zigzag_iter","text":"zigzag_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
ZigZag Iteration Algorithm 1. Recursively traverse the nodes on same level, in a zigzag manner across different levels.
Examples:
>>> from bigtree import Node, list_to_tree, zigzag_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in zigzag_iter(root)]\n['a', 'c', 'b', 'd', 'e', 'f', 'h', 'g']\n
>>> [node.node_name for node in zigzag_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'f', 'g']\n
>>> [node.node_name for node in zigzag_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'c', 'b', 'd', 'f']\n
>>> [node.node_name for node in zigzag_iter(root, max_depth=3)]\n['a', 'c', 'b', 'd', 'e', 'f']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.zigzaggroup_iter","title":"zigzaggroup_iter","text":"zigzaggroup_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
ZigZag Group Iteration Algorithm 1. Recursively traverse the nodes on same level, in a zigzag manner across different levels, returns nodes level by level in a nested list.
Examples:
>>> from bigtree import Node, list_to_tree, zigzaggroup_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root)]\n[['a'], ['c', 'b'], ['d', 'e', 'f'], ['h', 'g']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n[['a'], [], ['d', 'e', 'f'], ['g']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n[['a'], ['c', 'b'], ['d', 'f']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, max_depth=3)]\n[['a'], ['c', 'b'], ['d', 'e', 'f']]\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[Iterable[BaseNodeT]]
(Iterable[Iterable[BaseNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.dag_iterator","title":"dag_iterator","text":"dag_iterator(dag)\n
Iterate through all nodes of a Directed Acyclic Graph (DAG). Note that node names must be unique. Note that DAG must at least have two nodes to be shown on graph.
Examples:
>>> from bigtree import DAGNode, dag_iterator\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(a)]\n[('a', 'c'), ('a', 'd'), ('b', 'c'), ('c', 'd'), ('d', 'e')]\n
Parameters:
Name Type Description Defaultdag
DAGNode
input dag
requiredReturns:
Type DescriptionIterable[Tuple[DAGNodeT, DAGNodeT]]
(Iterable[Tuple[DAGNode, DAGNode]])
"},{"location":"bigtree/utils/plot/","title":"\ud83d\udcca Plot","text":"Plotting methods for Trees.
"},{"location":"bigtree/utils/plot/#bigtree.utils.plot","title":"bigtree.utils.plot","text":""},{"location":"bigtree/utils/plot/#bigtree.utils.plot.reingold_tilford","title":"reingold_tilford","text":"reingold_tilford(\n tree_node,\n sibling_separation=1.0,\n subtree_separation=1.0,\n level_separation=1.0,\n x_offset=0.0,\n y_offset=0.0,\n)\n
Algorithm for drawing tree structure, retrieves (x, y)
coordinates for a tree structure. Adds x
and y
attributes to every node in the tree. Modifies tree in-place.
This algorithm[1] is an improvement over Reingold Tilford algorithm[2].
According to Reingold Tilford's paper, a tree diagram should satisfy the following aesthetic rules,
Examples:
>>> from bigtree import reingold_tilford, list_to_tree\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> reingold_tilford(root)\n>>> root.show(attr_list=[\"x\", \"y\"])\na [x=1.25, y=3.0]\n\u251c\u2500\u2500 b [x=0.5, y=2.0]\n\u2502 \u251c\u2500\u2500 d [x=0.0, y=1.0]\n\u2502 \u2514\u2500\u2500 e [x=1.0, y=1.0]\n\u2502 \u251c\u2500\u2500 g [x=0.5, y=0.0]\n\u2502 \u2514\u2500\u2500 h [x=1.5, y=0.0]\n\u2514\u2500\u2500 c [x=2.0, y=2.0]\n \u2514\u2500\u2500 f [x=2.0, y=1.0]\n
References
Parameters:
Name Type Description Defaulttree_node
BaseNode
tree to compute (x, y) coordinate
requiredsibling_separation
float
minimum distance between adjacent siblings of the tree
1.0
subtree_separation
float
minimum distance between adjacent subtrees of the tree
1.0
level_separation
float
fixed distance between adjacent levels of the tree
1.0
x_offset
float
graph offset of x-coordinates
0.0
y_offset
float
graph offset of y-coordinates
0.0
"},{"location":"bigtree/workflows/","title":"\ud83d\udc77 Workflows","text":""},{"location":"bigtree/workflows/app_calendar/","title":"\ud83d\udcc6 Calendar App","text":""},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar","title":"bigtree.workflows.app_calendar","text":""},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar","title":"Calendar","text":"Calendar(name)\n
Calendar Implementation with Big Tree. - Calendar has four levels - year, month, day, and event name (with event attributes)
Examples:
Initializing and Adding Events
>>> from bigtree import Calendar\n>>> calendar = Calendar(\"My Calendar\")\n>>> calendar.add_event(\"Gym\", \"2023-01-01 18:00\")\n>>> calendar.add_event(\"Dinner\", \"2023-01-01\", date_format=\"%Y-%m-%d\", budget=20)\n>>> calendar.add_event(\"Gym\", \"2023-01-02 18:00\")\n>>> calendar.show()\nMy Calendar\n2023-01-01 00:00:00 - Dinner (budget: 20)\n2023-01-01 18:00:00 - Gym\n2023-01-02 18:00:00 - Gym\n
Search for Events
>>> calendar.find_event(\"Gym\")\n2023-01-01 18:00:00 - Gym\n2023-01-02 18:00:00 - Gym\n
Removing Events
>>> import datetime as dt\n>>> calendar.delete_event(\"Gym\", dt.date(2023, 1, 1))\n>>> calendar.show()\nMy Calendar\n2023-01-01 00:00:00 - Dinner (budget: 20)\n2023-01-02 18:00:00 - Gym\n
Export Calendar
>>> calendar.to_dataframe()\n path name date time budget\n0 /My Calendar/2023/01/01/Dinner Dinner 2023-01-01 00:00:00 20.0\n1 /My Calendar/2023/01/02/Gym Gym 2023-01-02 18:00:00 NaN\n
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.add_event","title":"add_event","text":"add_event(\n event_name,\n event_datetime,\n date_format=\"%Y-%m-%d %H:%M\",\n **kwargs\n)\n
Add event to calendar
Parameters:
Name Type Description Defaultevent_name
str
event name to be added
requiredevent_datetime
Union[str, datetime]
event date and time
requireddate_format
str
specify datetime format if event_datetime is str
'%Y-%m-%d %H:%M'
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.delete_event","title":"delete_event","text":"delete_event(event_name, event_date=None)\n
Delete event from calendar
Parameters:
Name Type Description Defaultevent_name
str
event name to be deleted
requiredevent_date
date
event date to be deleted
None
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.find_event","title":"find_event","text":"find_event(event_name)\n
Find event by name, prints result to console
Parameters:
Name Type Description Defaultevent_name
str
event name
required"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.show","title":"show","text":"show()\n
Show calendar, prints result to console
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.to_dataframe","title":"to_dataframe","text":"to_dataframe()\n
Export calendar to DataFrame
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/workflows/app_todo/","title":"\u2714\ufe0f To Do App","text":""},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo","title":"bigtree.workflows.app_todo","text":""},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo","title":"AppToDo","text":"AppToDo(app_name='')\n
To-Do List Implementation with Big Tree. - To-Do List has three levels - app name, list name, and item name. - If list name is not given, item will be assigned to a General
list.
Examples:
Initializing and Adding Items
>>> from bigtree import AppToDo\n>>> app = AppToDo(\"To Do App\")\n>>> app.add_item(item_name=\"Homework 1\", list_name=\"School\")\n>>> app.add_item(item_name=[\"Milk\", \"Bread\"], list_name=\"Groceries\", description=\"Urgent\")\n>>> app.add_item(item_name=\"Cook\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u251c\u2500\u2500 Groceries\n\u2502 \u251c\u2500\u2500 Milk [description=Urgent]\n\u2502 \u2514\u2500\u2500 Bread [description=Urgent]\n\u2514\u2500\u2500 General\n \u2514\u2500\u2500 Cook\n
Reorder List and Item
>>> app.prioritize_list(list_name=\"General\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Milk [description=Urgent]\n \u2514\u2500\u2500 Bread [description=Urgent]\n
>>> app.prioritize_item(item_name=\"Bread\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Removing Items
>>> app.remove_item(\"Homework 1\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Exporting and Importing List
>>> app.save(\"assets/docstr/list.json\")\n>>> app2 = AppToDo.load(\"assets/docstr/list.json\")\n>>> app2.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Initialize To-Do app
Parameters:
Name Type Description Defaultapp_name
str
name of to-do app, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.add_list","title":"add_list","text":"add_list(list_name, **kwargs)\n
Add list to app
If list is present, return list node, else a new list will be created
Parameters:
Name Type Description Defaultlist_name
str
name of list
requiredReturns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.prioritize_list","title":"prioritize_list","text":"prioritize_list(list_name)\n
Prioritize list in app, shift it to be the first list
Parameters:
Name Type Description Defaultlist_name
str
name of list
required"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.add_item","title":"add_item","text":"add_item(item_name, list_name='', **kwargs)\n
Add items to list
Parameters:
Name Type Description Defaultitem_name
str / List[str]
items to be added
requiredlist_name
str
list to add items to, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.remove_item","title":"remove_item","text":"remove_item(item_name, list_name='')\n
Remove items from list
Parameters:
Name Type Description Defaultitem_name
str / List[str]
items to be added
requiredlist_name
str
list to add items to, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.prioritize_item","title":"prioritize_item","text":"prioritize_item(item_name)\n
Prioritize item in list, shift it to be the first item in list
Parameters:
Name Type Description Defaultitem_name
str
name of item
required"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.show","title":"show","text":"show(**kwargs)\n
Print tree to console
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.load","title":"loadstaticmethod
","text":"load(json_path)\n
Load To-Do app from json
Parameters:
Name Type Description Defaultjson_path
str
json load path
requiredReturns:
Type DescriptionAppToDo
(Self)
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.save","title":"save","text":"save(json_path)\n
Save To-Do app as json
Parameters:
Name Type Description Defaultjson_path
str
json save path
required"},{"location":"demo/","title":"\ud83d\udccb Demonstration","text":""},{"location":"demo/binarytree/","title":"\ud83d\udccb Binary Tree Demonstration","text":"Compared to nodes in tree, nodes in Binary Tree are only allowed maximum of 2 children. Since BinaryNode extends from Node, construct, traverse, search, export methods from Node are applicable to Binary Tree as well.
"},{"location":"demo/binarytree/#construct-binary-tree","title":"Construct Binary Tree","text":""},{"location":"demo/binarytree/#1-from-binarynode","title":"1. From BinaryNode","text":"BinaryNode can be linked to each other with parent
, children
, left
, and right
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
from bigtree import BinaryNode, tree_to_dot\n\ne = BinaryNode(5)\nd = BinaryNode(4)\nc = BinaryNode(3)\nb = BinaryNode(2, left=d, right=e)\na = BinaryNode(1, children=[b, c])\nf = BinaryNode(6, parent=c)\ng = BinaryNode(7, parent=c)\nh = BinaryNode(8, parent=d)\n\ngraph = tree_to_dot(a, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/binarytree.png\")\n
"},{"location":"demo/binarytree/#2-from-list","title":"2. From list","text":"Construct nodes only, list has similar format as heapq
list.
from bigtree import list_to_binarytree\n\nnums_list = [1, 2, 3, 4, 5, 6, 7, 8]\nroot = list_to_binarytree(nums_list)\nroot.show()\n# 1\n# \u251c\u2500\u2500 2\n# \u2502 \u251c\u2500\u2500 4\n# \u2502 \u2502 \u2514\u2500\u2500 8\n# \u2502 \u2514\u2500\u2500 5\n# \u2514\u2500\u2500 3\n# \u251c\u2500\u2500 6\n# \u2514\u2500\u2500 7\n
"},{"location":"demo/binarytree/#traverse-binary-tree","title":"Traverse Binary Tree","text":"In addition to the traversal methods in the usual tree, binary tree includes in-order traversal method.
from bigtree import (\n inorder_iter,\n levelorder_iter,\n levelordergroup_iter,\n list_to_binarytree,\n postorder_iter,\n preorder_iter,\n zigzag_iter,\n zigzaggroup_iter,\n)\n\nnums_list = [1, 2, 3, 4, 5, 6, 7, 8]\nroot = list_to_binarytree(nums_list)\nroot.show()\n# 1\n# \u251c\u2500\u2500 2\n# \u2502 \u251c\u2500\u2500 4\n# \u2502 \u2502 \u2514\u2500\u2500 8\n# \u2502 \u2514\u2500\u2500 5\n# \u2514\u2500\u2500 3\n# \u251c\u2500\u2500 6\n# \u2514\u2500\u2500 7\n\n[node.name for node in inorder_iter(root)]\n# ['8', '4', '2', '5', '1', '6', '3', '7']\n\n[node.name for node in preorder_iter(root)]\n# ['1', '2', '4', '8', '5', '3', '6', '7']\n\n[node.name for node in postorder_iter(root)]\n# ['8', '4', '5', '2', '6', '7', '3', '1']\n\n[node.name for node in levelorder_iter(root)]\n# ['1', '2', '3', '4', '5', '6', '7', '8']\n\n[[node.name for node in node_group] for node_group in levelordergroup_iter(root)]\n# [['1'], ['2', '3'], ['4', '5', '6', '7'], ['8']]\n\n[node.name for node in zigzag_iter(root)]\n# ['1', '3', '2', '4', '5', '6', '7', '8']\n\n[[node.name for node in node_group] for node_group in zigzaggroup_iter(root)]\n# [['1'], ['3', '2'], ['4', '5', '6', '7'], ['8']]\n
"},{"location":"demo/dag/","title":"\ud83d\udccb DAG Demonstration","text":"Compared to nodes in tree, nodes in DAG are able to have multiple parents.
"},{"location":"demo/dag/#construct-dag","title":"Construct DAG","text":""},{"location":"demo/dag/#1-from-dagnode","title":"1. From DAGNode","text":"DAGNodes can be linked to each other in the following ways:
parents
and children
setter methodsparents
or children
argumentparent_node >> child_node
or child_node << parent_node
from bigtree import DAGNode, dag_to_dot\n\na = DAGNode(\"a\")\nb = DAGNode(\"b\")\nc = DAGNode(\"c\", parents=[a, b])\nd = DAGNode(\"d\", parents=[a, c])\ne = DAGNode(\"e\", parents=[d])\nf = DAGNode(\"f\", parents=[c, d])\nh = DAGNode(\"h\")\ng = DAGNode(\"g\", parents=[c], children=[h])\n\ngraph = dag_to_dot(a, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/dag.png\")\n
"},{"location":"demo/dag/#2-from-list","title":"2. From list","text":"Construct nodes only, list contains parent-child tuples.
from bigtree import list_to_dag, dag_iterator\n\nrelations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\ndag = list_to_dag(relations_list)\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#3-from-nested-dictionary","title":"3. From nested dictionary","text":"Construct nodes with attributes, key
: child name, value
: dict of parent name, child node attributes.
from bigtree import dict_to_dag, dag_iterator\n\nrelation_dict = {\n \"a\": {\"step\": 1},\n \"b\": {\"step\": 1},\n \"c\": {\"parents\": [\"a\", \"b\"], \"step\": 2},\n \"d\": {\"parents\": [\"a\", \"c\"], \"step\": 2},\n \"e\": {\"parents\": [\"d\"], \"step\": 3},\n}\ndag = dict_to_dag(relation_dict, parent_key=\"parents\")\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#4-from-pandas-dataframe","title":"4. From pandas DataFrame","text":"Construct nodes with attributes, pandas DataFrame contains child column, parent column, and attribute columns.
import pandas as pd\nfrom bigtree import dataframe_to_dag, dag_iterator\n\npath_data = pd.DataFrame(\n [\n [\"a\", None, 1],\n [\"b\", None, 1],\n [\"c\", \"a\", 2],\n [\"c\", \"b\", 2],\n [\"d\", \"a\", 2],\n [\"d\", \"c\", 2],\n [\"e\", \"d\", 3],\n ],\n columns=[\"child\", \"parent\", \"step\"],\n)\ndag = dataframe_to_dag(path_data)\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#dag-attributes-and-operations","title":"DAG Attributes and Operations","text":"Note that using DAGNode
as superclass inherits the default class attributes (properties) and operations (methods).
from bigtree import list_to_dag\n\nrelations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\ndag = list_to_dag(relations_list)\ndag\n# DAGNode(d, )\n\n# Accessing children\nnode_e = dag[\"e\"]\nnode_a = dag.parents[0]\n
Below are the tables of attributes available to DAGNode
class.
node_a.is_root
True Check if leaf node dag.is_leaf
False Get node name (only for Node
) dag.node_name
'd' Attributes wrt structure Code Returns Get child/children node_a.children
(DAGNode(c, ), DAGNode(d, )) Get parents dag.parents
(DAGNode(a, ), DAGNode(c, )) Get siblings dag.siblings
(DAGNode(c, ),) Get ancestors dag.ancestors
[DAGNode(a, ), DAGNode(b, ), DAGNode(c, )] Get descendants dag.descendants
[DAGNode(e, )] Below is the table of operations available to DAGNode
class.
dag.describe(exclude_prefix=\"_\")
[('name', 'd')] Find path(s) from one node to another node_a.go_to(dag)
[[DAGNode(a, ), DAGNode(c, ), DAGNode(d, description=dag-tag)], [DAGNode(a, ), DAGNode(d, description=dag-tag)]] Set attribute(s) dag.set_attrs({\"description\": \"dag-tag\"})
None Get attribute dag.get_attr(\"description\")
'dag-tag' Copy DAG dag.copy()
None"},{"location":"demo/tree/","title":"\ud83d\udccb Tree Demonstration","text":"Here are some codes to get started.
"},{"location":"demo/tree/#construct-tree","title":"Construct Tree","text":"Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other in the following ways:
parent
and children
setter methodsparent
or children
argumentparent >> child
or child << parent
.append(child)
or .extend([child1, child2])
methodsparent
and children
setter methodsparent
or children
argumentBitshift operatorappend
and extend
from bigtree import Node, tree_to_dot\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot.children = [b, c]\nd.parent = b\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n\nroot.hshow()\n# \u250c\u2500 b \u2500\u2500\u2500 d\n# \u2500 a \u2500\u2524\n# \u2514\u2500 c\n\ngraph = tree_to_dot(root, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/tree.png\")\n
from bigtree import Node\n\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\", parent=b)\nroot = Node(\"a\", children=[b, c])\n
from bigtree import Node\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot >> b\nroot >> c\nd << b\n
from bigtree import Node\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot.extend([b, c])\nb.append(d)\n
"},{"location":"demo/tree/#2-from-str","title":"2. From str","text":"Construct nodes only. Newick string notation supports parsing attributes.
Tree stringNewick stringfrom bigtree import str_to_tree\n\ntree_str = \"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\"\nroot = str_to_tree(tree_str)\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2502 \u251c\u2500\u2500 g\n# \u2502 \u2514\u2500\u2500 h\n# \u2514\u2500\u2500 c\n# \u2514\u2500\u2500 f\n
from bigtree import newick_to_tree\n\nnewick_str = \"((d,(g,h)e)b,(f)c)a\"\nroot = newick_to_tree(newick_str)\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2502 \u251c\u2500\u2500 g\n# \u2502 \u2514\u2500\u2500 h\n# \u2514\u2500\u2500 c\n# \u2514\u2500\u2500 f\n
"},{"location":"demo/tree/#3-from-list","title":"3. From list","text":"Construct nodes only. List can contain either full paths or tuples of parent-child names.
Full pathsParent-child namesfrom bigtree import list_to_tree\n\nroot = list_to_tree([\"a/b/d\", \"a/c\"])\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n
from bigtree import list_to_tree_by_relation\n\nroot = list_to_tree_by_relation([(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\")])\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n
"},{"location":"demo/tree/#4-from-nested-dictionary","title":"4. From nested dictionary","text":"Construct nodes with attributes. Dictionary can be in a flat structure where key
is path and value
is dictionary of node attribute names and values, or in a recursive structure where key
is node attribute names and value
is node attribute values, and list of children (recursive).
from bigtree import dict_to_tree\n\npath_dict = {\n \"a\": {\"age\": 90},\n \"a/b\": {\"age\": 65},\n \"a/c\": {\"age\": 60},\n \"a/b/d\": {\"age\": 40},\n}\nroot = dict_to_tree(path_dict)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
from bigtree import nested_dict_to_tree\n\npath_dict = {\n \"name\": \"a\",\n \"age\": 90,\n \"children\": [\n {\n \"name\": \"b\",\n \"age\": 65,\n \"children\": [\n {\"name\": \"d\", \"age\": 40},\n ],\n },\n {\"name\": \"c\", \"age\": 60},\n ],\n}\nroot = nested_dict_to_tree(path_dict)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
"},{"location":"demo/tree/#5-from-pandas-dataframe","title":"5. From pandas DataFrame","text":"Construct nodes with attributes. Pandas DataFrame can contain either path column or parent-child columns. Other columns can be used to specify attributes.
Path columnParent-child columnsimport pandas as pd\n\nfrom bigtree import dataframe_to_tree\n\ndata = pd.DataFrame(\n [\n [\"a\", 90],\n [\"a/b\", 65],\n [\"a/c\", 60],\n [\"a/b/d\", 40],\n ],\n columns=[\"path\", \"age\"],\n)\nroot = dataframe_to_tree(data)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
import pandas as pd\n\nfrom bigtree import dataframe_to_tree_by_relation\n\ndata = pd.DataFrame(\n [\n [\"a\", None, 90],\n [\"b\", \"a\", 65],\n [\"c\", \"a\", 60],\n [\"d\", \"b\", 40],\n ],\n columns=[\"child\", \"parent\", \"age\"],\n)\nroot = dataframe_to_tree_by_relation(data)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
Note
If tree is already created, nodes can still be added using path string, dictionary, and pandas DataFrame! Attributes can be added to existing nodes using a dictionary or pandas DataFrame.
"},{"location":"demo/tree/#print-tree","title":"Print Tree","text":"After tree is constructed, it can be viewed by printing to console using show
or hshow
method directly, for vertical and horizontal orientation respectively. Alternatively, the print_tree
or hprint_tree
method can be used.
from bigtree import Node, print_tree, hprint_tree\n\nroot = Node(\"a\", age=90, gender=\"F\")\nb = Node(\"b\", age=65, gender=\"M\", parent=root)\nc = Node(\"c\", age=60, gender=\"M\", parent=root)\nd = Node(\"d\", age=40, gender=\"F\", parent=b)\ne = Node(\"e\", age=35, gender=\"M\", parent=b)\nprint_tree(root) # (1)!\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\nhprint_tree(root) # (2)!\n# \u250c\u2500 d\n# \u250c\u2500 b \u2500\u2524\n# \u2500 a \u2500\u2524 \u2514\u2500 e\n# \u2514\u2500 c\n\n# Print subtree\nprint_tree(root, node_name_or_path=\"b\")\n# b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n\nprint_tree(root, max_depth=2)\n# a\n# \u251c\u2500\u2500 b\n# \u2514\u2500\u2500 c\n\n# Print attributes\nprint_tree(root, attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u251c\u2500\u2500 d [age=40]\n# \u2502 \u2514\u2500\u2500 e [age=35]\n# \u2514\u2500\u2500 c [age=60]\n\nprint_tree(root, attr_list=[\"age\"], attr_bracket=[\"*(\", \")\"])\n# a *(age=90)\n# \u251c\u2500\u2500 b *(age=65)\n# \u2502 \u251c\u2500\u2500 d *(age=40)\n# \u2502 \u2514\u2500\u2500 e *(age=35)\n# \u2514\u2500\u2500 c *(age=60)\n\nprint_tree(root, all_attrs=True)\n# a [age=90, gender=F]\n# \u251c\u2500\u2500 b [age=65, gender=M]\n# \u2502 \u251c\u2500\u2500 d [age=40, gender=F]\n# \u2502 \u2514\u2500\u2500 e [age=35, gender=M]\n# \u2514\u2500\u2500 c [age=60, gender=M]\n\n# Available styles\nprint_tree(root, style=\"ansi\")\n# a\n# |-- b\n# | |-- d\n# | `-- e\n# `-- c\n\nprint_tree(root, style=\"ascii\")\n# a\n# |-- b\n# | |-- d\n# | +-- e\n# +-- c\n\nprint_tree(root, style=\"const\")\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\nprint_tree(root, style=\"const_bold\")\n# a\n# \u2523\u2501\u2501 b\n# \u2503 \u2523\u2501\u2501 d\n# \u2503 \u2517\u2501\u2501 e\n# \u2517\u2501\u2501 c\n\nprint_tree(root, style=\"rounded\")\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2570\u2500\u2500 e\n# \u2570\u2500\u2500 c\n\nprint_tree(root, style=\"double\")\n# a\n# \u2560\u2550\u2550 b\n# \u2551 \u2560\u2550\u2550 d\n# \u2551 \u255a\u2550\u2550 e\n# \u255a\u2550\u2550 c\n\nprint_tree(\n root,\n style=\"custom\",\n custom_style=(\"\u2502 \", \"\u251c\u2192 \", \"\u2570\u2192 \"),\n)\n# a\n# \u251c\u2192 b\n# \u2502 \u251c\u2192 d\n# \u2502 \u2570\u2192 e\n# \u2570\u2192 c\n
root.show()
can be usedroot.hshow()
can be usedNote that using BaseNode
or Node
as superclass inherits the default class attributes (properties) and operations (methods).
from bigtree import str_to_tree\n\n# Initialize tree\ntree_str = \"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u251c\u2500\u2500 e\n\u2502 \u2514\u2500\u2500 f\n\u2502 \u251c\u2500\u2500 h\n\u2502 \u2514\u2500\u2500 i\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 g\n\"\"\"\nroot = str_to_tree(tree_str)\n\n# Accessing children\nnode_b = root[\"b\"]\nnode_e = root[\"b\"][\"e\"]\n
Below are the tables of attributes available to BaseNode
and Node
classes.
root.is_root
True Check if leaf node root.is_leaf
False Check depth of node node_b.depth
2 Check depth of tree node_b.max_depth
4 Get root of tree node_b.root
Node(/a, ) Get node path node_b.node_path
(Node(/a, ), Node(/a/b, )) Get node name (only for Node
) node_b.node_name
'b' Get node path name (only for Node
) node_b.path_name
'/a/b' Attributes wrt structure Code Returns Get child/children root.children
(Node(/a/b, ), Node(/a/c, )) Get parent node_e.parent
Node(/a/b, ) Get siblings node_e.siblings
(Node(/a/b/d, ), Node(/a/b/f, )) Get left sibling node_e.left_sibling
Node(/a/b/d, ) Get right sibling node_e.right_sibling
Node(/a/b/f, ) Get ancestors (lazy evaluation) list(node_e.ancestors)
[Node(/a/b, ), Node(/a, )] Get descendants (lazy evaluation) list(node_b.descendants)
[Node(/a/b/d, ), Node(/a/b/e, ), Node(/a/b/f, ), Node(/a/b/f/h, ), Node(/a/b/f/i, )] Get leaves (lazy evaluation) list(node_b.leaves)
[Node(/a/b/d, ), Node(/a/b/e, ), Node(/a/b/f/h, ), Node(/a/b/f/i, )] Below is the table of operations available to BaseNode
and Node
classes.
Node
) root.show()
None Visualize tree (horizontally) (only for Node
) root.hshow()
None Get node information root.describe(exclude_prefix=\"_\")
[('name', 'a')] Find path from one node to another root.go_to(node_e)
[Node(/a, ), Node(/a/b, ), Node(/a/b/e, )] Add child to node root.append(Node(\"j\"))
None Add multiple children to node root.extend([Node(\"k\"), Node(\"l\")])
None Set attribute(s) root.set_attrs({\"description\": \"root-tag\"})
None Get attribute root.get_attr(\"description\")
'root-tag' Copy tree root.copy()
None Sort children root.sort(key=lambda node: node.node_name, reverse=True)
None"},{"location":"demo/tree/#traverse-tree","title":"Traverse Tree","text":"Tree can be traversed using the following traversal methods.
from bigtree import (\n Node,\n levelorder_iter,\n levelordergroup_iter,\n postorder_iter,\n preorder_iter,\n zigzag_iter,\n zigzaggroup_iter,\n)\n\nroot = Node(\"a\")\nb = Node(\"b\", parent=root)\nc = Node(\"c\", parent=root)\nd = Node(\"d\", parent=b)\ne = Node(\"e\", parent=b)\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\n[node.name for node in preorder_iter(root)]\n# ['a', 'b', 'd', 'e', 'c']\n\n[node.name for node in postorder_iter(root)]\n# ['d', 'e', 'b', 'c', 'a']\n\n[node.name for node in levelorder_iter(root)]\n# ['a', 'b', 'c', 'd', 'e']\n\n[[node.name for node in node_group] for node_group in levelordergroup_iter(root)]\n# [['a'], ['b', 'c'], ['d', 'e']]\n\n[node.name for node in zigzag_iter(root)]\n# ['a', 'c', 'b', 'd', 'e']\n\n[[node.name for node in node_group] for node_group in zigzaggroup_iter(root)]\n# [['a'], ['c', 'b'], ['d', 'e']]\n
"},{"location":"demo/tree/#modify-tree","title":"Modify Tree","text":"Nodes can be shifted (with or without replacement) or copied (without replacement) from one path to another, this changes the tree in-place. Nodes can also be copied (with or without replacement) between two different trees.
Shift nodesfrom bigtree import list_to_tree, shift_nodes, shift_and_replace_nodes\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\nshift_nodes(\n tree=root,\n from_paths=[\"photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (1)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (2)\n\nshift_and_replace_nodes(\n tree=root,\n from_paths=[\"Downloads/Files\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\"],\n)\nroot.show()\n# Downloads\n# \u2514\u2500\u2500 Pictures\n# \u2514\u2500\u2500 Files (3)\n# \u2514\u2500\u2500 file1.doc\n
Downloads/Pictures/photo1.jpg
Downloads/Files/file1.doc
, this creates intermediate Node Files
as wellphoto1.jpg
with Files
folderfrom bigtree import list_to_tree, copy_nodes\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\ncopy_nodes(\n tree=root,\n from_paths=[\"photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (1)\n# \u251c\u2500\u2500 photo1.jpg (2)\n# \u251c\u2500\u2500 file1.doc (4)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (3)\n
Downloads/Pictures/photo1.jpg
photo1.jpg
still remainsDownloads/Files/file1.doc
, this creates intermediate Node Files
as wellfile1.doc
still remainsfrom bigtree import (\n Node,\n copy_nodes_from_tree_to_tree,\n copy_and_replace_nodes_from_tree_to_tree,\n list_to_tree,\n)\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\nroot_other = Node(\"Documents\")\ncopy_nodes_from_tree_to_tree(\n from_tree=root,\n to_tree=root_other,\n from_paths=[\"Downloads/Pictures\", \"photo1.jpg\", \"file1.doc\"],\n to_paths=[\n \"Documents/Pictures\",\n \"Documents/Pictures/photo1.jpg\",\n \"Documents/Files/file1.doc\",\n ],\n)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures (1)\n# \u2502 \u2514\u2500\u2500 photo1.jpg (2)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (3)\n\nroot_other = Node(\"Documents\")\npicture_folder = Node(\"Pictures\", parent=root_other)\nphoto2 = Node(\"photo2.jpg\", parent=picture_folder)\nfile2 = Node(\"file2.doc\", parent=root_other)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo2.jpg\n# \u2514\u2500\u2500 file2.doc\n\ncopy_and_replace_nodes_from_tree_to_tree(\n from_tree=root,\n to_tree=root_other,\n from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Documents/Pictures/photo2.jpg\", \"Documents/file2.doc\"],\n)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (4)\n# \u2514\u2500\u2500 file1.doc (5)\n
Documents/Pictures
Documents/Pictures/photo1.jpg
Documents/Files/file1.doc
, this creates intermediate Node Files
as wellDocuments/Pictures/photo2.jpg
with photo1.jpg
Documents/file2.doc
with file1.doc
One or multiple nodes can be searched based on name, path, attribute value, or user-defined condition. It is also possible to search for one or more child node(s) based on attributes, this search will be faster as it does not require traversing the whole tree to find the node(s).
Find single nodeFind multiple nodesFind child nodesfrom bigtree import Node, find, find_name, find_path, find_relative_path, find_full_path, find_attr\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"d\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 d [age=40]\n\nfind(root, lambda node: node.age == 60)\n# Node(/a/c, age=60)\n\nfind_name(root, \"d\")\n# Node(/a/c/d, age=40)\n\nfind_relative_path(c, \"../b\") # relative path\n# (Node(/a/b, age=65),)\n\nfind_path(root, \"/c/d\") # partial path\n# Node(/a/c/d, age=40)\n\nfind_full_path(root, \"a/c/d\") # full path\n# Node(/a/c/d, age=40)\n\nfind_attr(root, \"age\", 40)\n# Node(/a/c/d, age=40)\n
from bigtree import Node, findall, find_names, find_relative_path, find_paths, find_attrs\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"c\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 c [age=40]\n\nfindall(root, lambda node: node.age >= 65)\n# (Node(/a, age=90), Node(/a/b, age=65))\n\nfind_names(root, \"c\")\n# (Node(/a/c, age=60), Node(/a/c/c, age=40))\n\nfind_relative_path(c, \"../*\") # relative path\n# (Node(/a/b, age=65), Node(/a/c, age=60))\n\nfind_paths(root, \"/c\") # partial path\n# (Node(/a/c, age=60), Node(/a/c/c, age=40))\n\nfind_attrs(root, \"age\", 40)\n# (Node(/a/c/c, age=40),)\n
from bigtree import Node, find_children, find_child, find_child_by_name\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"c\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 c [age=40]\n\nfind_children(root, lambda node: node.age >= 60)\n# (Node(/a/b, age=65), Node(/a/c, age=60))\n\nfind_child(root, lambda node: node.name == \"c\")\n# Node(/a/c, age=60)\n\nfind_child_by_name(root, \"c\")\n# Node(/a/c, age=60)\n\nfind_child_by_name(c, \"c\")\n# Node(/a/c/c, age=40)\n
"},{"location":"demo/tree/#helper-utility","title":"Helper Utility","text":"There following are helper functions for
"},{"location":"demo/tree/#1-cloning-tree-to-another-node-type","title":"1. Cloning tree to another Node type","text":"from bigtree import BaseNode, Node, clone_tree\n\n# Cloning tree from `BaseNode` to `Node` type\nroot = BaseNode(name=\"a\")\nb = BaseNode(name=\"b\", parent=root)\nclone_tree(root, Node)\n# Node(/a, )\n
"},{"location":"demo/tree/#2-getting-subtree-smaller-tree-with-different-root","title":"2. Getting subtree (smaller tree with different root)","text":"from bigtree import str_to_tree, get_subtree\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Getting subtree with root b\nroot_subtree = get_subtree(root, \"b\")\nroot_subtree.show()\n# b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n
"},{"location":"demo/tree/#3-pruning-tree-smaller-tree-with-same-root","title":"3. Pruning tree (smaller tree with same root)","text":"from bigtree import str_to_tree, prune_tree\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Prune tree to only path a/b\nroot_pruned = prune_tree(root, \"a/b\")\nroot_pruned.show()\n# a\n# \u2514\u2500\u2500 b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n\n# Prune tree to exactly path a/b\nroot_pruned = prune_tree(root, \"a/b\", exact=True)\nroot_pruned.show()\n# a\n# \u2514\u2500\u2500 b\n
"},{"location":"demo/tree/#4-getting-difference-between-two-trees","title":"4. Getting difference between two trees","text":"from bigtree import str_to_tree, get_tree_diff\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Get difference between two trees\nroot_other = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 g\n\"\"\")\n\ntree_diff = get_tree_diff(root, root_other)\ntree_diff.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 e (-)\n# \u2514\u2500\u2500 c\n# \u251c\u2500\u2500 f (-)\n# \u2514\u2500\u2500 g (+)\n\ntree_diff = get_tree_diff(root, root_other, only_diff=False)\ntree_diff.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e (-)\n# \u2514\u2500\u2500 c\n# \u251c\u2500\u2500 f (-)\n# \u2514\u2500\u2500 g (+)\n
"},{"location":"demo/tree/#export-tree","title":"Export Tree","text":"Tree can be exported to other data types:
from bigtree import Node\n\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"d\", age=40, parent=b)\ne = Node(\"e\", age=35, parent=b)\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n
Newick string notationDictionary (flat structure)Dictionary (recursive structure)pandas DataFrameDotPillowMermaid Flowchart from bigtree import tree_to_newick\n\ntree_to_newick(root)\n# '((d,e)b,c)a'\n\ntree_to_newick(root, attr_list=[\"age\"])\n# '((d[&&NHX:age=40],e[&&NHX:age=35])b[&&NHX:age=65],c[&&NHX:age=60])a[&&NHX:age=90]'\n
from bigtree import tree_to_dict\n\ntree_to_dict(\n root,\n name_key=\"name\",\n parent_key=\"parent\",\n attr_dict={\"age\": \"person age\"}\n)\n# {\n# '/a': {'name': 'a', 'parent': None, 'person age': 90},\n# '/a/b': {'name': 'b', 'parent': 'a', 'person age': 65},\n# '/a/b/d': {'name': 'd', 'parent': 'b', 'person age': 40},\n# '/a/b/e': {'name': 'e', 'parent': 'b', 'person age': 35},\n# '/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}\n# }\n
from bigtree import tree_to_nested_dict\n\ntree_to_nested_dict(root, all_attrs=True)\n# {\n# 'name': 'a',\n# 'age': 90,\n# 'children': [\n# {\n# 'name': 'b',\n# 'age': 65,\n# 'children': [\n# {\n# 'name': 'd',\n# 'age': 40\n# },\n# {\n# 'name': 'e',\n# 'age': 35\n# }\n# ]\n# },\n# {\n# 'name': 'c',\n# 'age': 60\n# }\n# ]\n# }\n
from bigtree import tree_to_dataframe\n\ntree_to_dataframe(\n root,\n name_col=\"name\",\n parent_col=\"parent\",\n path_col=\"path\",\n attr_dict={\"age\": \"person age\"}\n)\n# path name parent person age\n# 0 /a a None 90\n# 1 /a/b b a 65\n# 2 /a/b/d d b 40\n# 3 /a/b/e e b 35\n# 4 /a/c c a 60\n
from bigtree import tree_to_dot\n\ngraph = tree_to_dot(root, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/dot.png\")\n
from bigtree import tree_to_pillow\n\npillow_image = tree_to_pillow(root)\npillow_image.save(\"assets/demo/pillow.png\")\n
from bigtree import tree_to_mermaid\n\nmermaid_md = tree_to_mermaid(root)\nprint(mermaid_md)\n
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0(\"a\") --> 0-0(\"b\")\n0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0(\"a\") --> 0-1(\"c\")\nclassDef default stroke-width:1
There are existing implementations of workflows to showcase how bigtree
can be used!
There are functions to:
from bigtree import AppToDo\n\napp = AppToDo(\"To Do App\")\napp.add_item(item_name=\"Homework 1\", list_name=\"School\")\napp.add_item(item_name=[\"Milk\", \"Bread\"], list_name=\"Groceries\", description=\"Urgent\")\napp.add_item(item_name=\"Cook\")\napp.show()\n# To Do App\n# \u251c\u2500\u2500 School\n# \u2502 \u2514\u2500\u2500 Homework 1\n# \u251c\u2500\u2500 Groceries\n# \u2502 \u251c\u2500\u2500 Milk [description=Urgent]\n# \u2502 \u2514\u2500\u2500 Bread [description=Urgent]\n# \u2514\u2500\u2500 General\n# \u2514\u2500\u2500 Cook\n\napp.save(\"list.json\")\napp2 = AppToDo.load(\"list.json\")\n
"},{"location":"demo/workflow/#calendar-application","title":"Calendar Application","text":"There are functions to:
import datetime as dt\nfrom bigtree import Calendar\n\ncalendar = Calendar(\"My Calendar\")\ncalendar.add_event(\"Gym\", \"2023-01-01 18:00\")\ncalendar.add_event(\"Dinner\", \"2023-01-01\", date_format=\"%Y-%m-%d\", budget=20)\ncalendar.add_event(\"Gym\", \"2023-01-02 18:00\")\ncalendar.show()\n# My Calendar\n# 2023-01-01 00:00:00 - Dinner (budget: 20)\n# 2023-01-01 18:00:00 - Gym\n# 2023-01-02 18:00:00 - Gym\n\ncalendar.find_event(\"Gym\")\n# 2023-01-01 18:00:00 - Gym\n# 2023-01-02 18:00:00 - Gym\n\ncalendar.delete_event(\"Gym\", dt.date(2023, 1, 1))\ncalendar.show()\n# My Calendar\n# 2023-01-01 00:00:00 - Dinner (budget: 20)\n# 2023-01-02 18:00:00 - Gym\n\ndata_calendar = calendar.to_dataframe()\ndata_calendar\n# path name date time budget\n# 0 /My Calendar/2023/01/01/Dinner Dinner 2023-01-01 00:00:00 20.0\n# 1 /My Calendar/2023/01/02/Gym Gym 2023-01-02 18:00:00 NaN\n
"},{"location":"others/","title":"\ud83d\udca1 Tips and Tricks","text":""},{"location":"others/list_dir/","title":"List Directory","text":"To list directories recursively using bigtree, we can use the glob
built-in Python package to extract a list of paths.
import glob\nfrom bigtree import list_to_tree, print_tree\n\n# Get all directories recursively\npath_list = []\nfor f in glob.glob(\"./**/*.py\", recursive=True):\n path_list.append(f)\n\n# Construct tree\nroot = list_to_tree(path_list)\n\n# View tree\nprint_tree(root, max_depth=3)\n
"},{"location":"others/merging_trees/","title":"Merging Trees","text":"To merge two separate trees into one, we can use the tree modify module.
In this example, we are merging two trees that have similar node Pictures
. Children of node Pictures
from both trees are retained as long as merge_children=True
is set. If only children of the other tree are desired, set overriding=True
instead.
from bigtree import Node, copy_nodes_from_tree_to_tree\n\n# Construct trees\ndownloads_folder = Node(\"Downloads\")\npictures_folder = Node(\"Pictures\", parent=downloads_folder)\nphoto1 = Node(\"photo1.jpg\", parent=pictures_folder)\nfile1 = Node(\"file1.doc\", parent=downloads_folder)\n\ndocuments_folder = Node(\"Documents\")\npictures_folder = Node(\"Pictures\", parent=documents_folder)\nphoto2 = Node(\"photo2.jpg\", parent=pictures_folder)\n\n# Validate tree structure\ndownloads_folder.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\ndocuments_folder.show()\n# Documents\n# \u2514\u2500\u2500 Pictures\n# \u2514\u2500\u2500 photo2.jpg\n\n# Merge trees\ncopy_nodes_from_tree_to_tree(\n from_tree=documents_folder,\n to_tree=downloads_folder,\n from_paths=[\"Documents/Pictures\"],\n to_paths=[\"Downloads/Pictures\"],\n merge_children=True, # set overriding=True to override existing children\n)\n\n# Validate tree structure\ndownloads_folder.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u251c\u2500\u2500 photo1.jpg\n# \u2502 \u2514\u2500\u2500 photo2.jpg\n# \u2514\u2500\u2500 file1.doc\n
"},{"location":"others/nodes/","title":"Extending Nodes","text":"Nodes can be extended from BaseNode
or Node
class to have extended functionalities or add pre-/post-assign checks. - For example, Node
class extends BaseNode
and added the name
functionality with pre-assign checks to ensure no duplicate path names.
from bigtree import Node, print_tree\n\n\nclass PopulationNode(Node):\n\n def __init__(self, name: str, population: int = 0, **kwargs):\n super().__init__(name, **kwargs)\n self._population = population\n\n @property\n def population(self):\n if self.is_leaf:\n return self._population\n return sum([child.population for child in self.children])\n\n @property\n def percentage(self):\n if self.is_root:\n return 1\n return round(self.population / self.root.population, 2)\n\n\nroot = PopulationNode(\"World\")\nb1 = PopulationNode(\"Country A\", parent=root)\nc1 = PopulationNode(\"State A1\", 100, parent=b1)\nc2 = PopulationNode(\"State A2\", 50, parent=b1)\nb2 = PopulationNode(\"Country B\", 200, parent=root)\nb3 = PopulationNode(\"Country C\", 100, parent=root)\n\nprint_tree(root, attr_list=[\"population\", \"percentage\"])\n# World [population=450, percentage=1]\n# \u251c\u2500\u2500 Country A [population=150, percentage=0.33]\n# \u2502 \u251c\u2500\u2500 State A1 [population=100, percentage=0.22]\n# \u2502 \u2514\u2500\u2500 State A2 [population=50, percentage=0.11]\n# \u251c\u2500\u2500 Country B [population=200, percentage=0.44]\n# \u2514\u2500\u2500 Country C [population=100, percentage=0.22]\n
"},{"location":"others/nodes/#read-only-node-add-pre-post-assign-checks","title":"Read-Only Node (add pre-/post-assign checks)","text":"import pytest\n\nfrom bigtree import Node\nfrom typing import List\n\n\nclass ReadOnlyNode(Node):\n\n def __init__(self, *args, **kwargs):\n self.__readonly = False\n super().__init__(*args, **kwargs)\n self.__readonly = True\n\n def _Node__pre_assign_parent(self, new_parent: Node):\n if self.__readonly:\n raise RuntimeError(\"Nodes cannot be reassigned for ReadOnlyNode\")\n\n def _Node__pre_assign_children(self, new_children: List[Node]):\n if self.__readonly:\n raise RuntimeError(\"Nodes cannot be reassigned for ReadOnlyNode\")\n\n\na = ReadOnlyNode(\"a\")\nb = ReadOnlyNode(\"b\", parent=a)\nc = ReadOnlyNode(\"c\", parent=a)\n\nwith pytest.raises(RuntimeError):\n c.parent = b\n\nwith pytest.raises(RuntimeError):\n a.children = [b, c]\n
"},{"location":"others/remove_checks/","title":"Remove Tree Checks","text":"Note
Available from version 0.16.2 onwards
When constructing trees, there are a few checks done that slow down performance. This slowness will be more apparent with very large trees. The checks are to
These checks are enabled by default. To turn off these checks, you can set environment variable before importing bigtree
.
import os\nos.environ[\"BIGTREE_CONF_ASSERTIONS\"] = \"\"\n\nimport bigtree\n
"},{"location":"others/weighted_trees/","title":"Trees with Weighted Edges","text":"Edge weights should be defined in the child node for the parent-child edge since each node can only have one parent.
We can simply add weight
attribute to the Node
class. However, if we want to visualize the weighted tree, we can create a WeightedNode
class to generate the edge attribute dictionary.
from bigtree import Node, tree_to_dot\n\nclass WeightedNode(Node):\n def __init__(self, name, weight=0, **kwargs):\n super().__init__(name, **kwargs)\n self.weight = weight\n\n @property\n def edge_attr(self):\n \"\"\"Edge attribute for pydot diagram\n Label for edge label, penwidth for edge width\n \"\"\"\n return {\"label\": self.weight, \"penwidth\": self.weight}\n\n# Construct weighted tree\nroot = WeightedNode(\"a\")\nb = WeightedNode(\"b\", parent=root, weight=1)\nc = WeightedNode(\"c\", parent=root, weight=2)\nd = WeightedNode(\"d\", parent=b, weight=3)\n\ngraph = tree_to_dot(root, node_colour=\"gold\", edge_attr=\"edge_attr\")\ngraph.write_png(\"assets/docs/weighted_tree.png\")\n
"},{"location":"resources/","title":"\ud83d\udcf0 Resources","text":""},{"location":"resources/articles/","title":"\ud83d\udcf0 Articles","text":"Integrating trees with Python lists, dictionaries, and pandas DataFrames
Read article
Algorithm to Plot Tree Nodes with Numerical Examples and Python Code
Read article
Tree Implementation and Methods for Python, integrated with Python list, dictionary, and pandas DataFrame.
It is pythonic, making it easy to learn and extendable to many types of workflows.
Install bigtree
with pip
or conda
and get up and running in minutes
Getting started
View demonstration on how to use bigtree
Reference
Articles relating to trees and bigtree
View articles
Do support if you like this project!
Support me
Related Links:
Visit this page for results of pytest-benchmark.
"},{"location":"binarytree/","title":"\ud83c\udf35 Binary Tree","text":"For Binary Tree implementation, there are 3 main components. Binary Node inherits from Node, so the components in Tree implementation are also available in Binary Tree.
"},{"location":"binarytree/#node","title":"\ud83c\udf3f Node","text":"BinaryNode
, Node with binary tree rulesAll notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
"},{"location":"changelog/#unreleased","title":"Unreleased","text":""},{"location":"changelog/#added","title":"Added","text":"docstr-coverage
.docstr-coverage
.hprint_tree
and hyield_tree
to be compatible with BinaryNode
where child nodes can be None type.__getitem__
and __delitem__
magic methods.__contains__
magic method.__iter__
magic method.find_children
, find_child
, and find_child_by_name
.hprint_tree
and hyield_tree
to allow hiding names of intermediate node.newick_to_tree
to handle invalid closing and use of apostrophe.tree_to_newick
to handle special characters by wrapping them in apostrophe.get_subtree
method to retrieve subtree.hprint_tree
and hyield_tree
to print and retrieve results for tree in horizontal orientation.hshow
method to print tree in horizontal orientation to console.newick_to_tree
to convert Newick notation to tree.tree_to_newick
to accept more parameters to parse length and attributes.tree_to_newick
.exact
parameter, default is prune and keep descendants.plot.py
utils file for coverage report.get_tree_diff
enhanced to compare tree attributes by taking in attr_list
parameter, and indicates difference with (~)
.get_tree_diff
compare tree structure by considering all nodes (previously only consider leaf nodes).__getitem__
and __delitem__
magic methods.append
and extend
methods.__contains__
magic method.__iter__
magic method. Results in children setter to only accept list/tuple/set instead of iterable types.tree_to_dot
accepts callable to set node and edge attrs for custom node (backward-compatible).tree_to_mermaid
accepts callable to set node shape attr, edge arrow attr and node attr for custom node (backward-compatible).tree_to_mermaid
to prevent possible path confusion (backward-compatible).shift_and_replace_nodes
and copy_and_replace_nodes_from_tree_to_tree
in README.shift_and_replace_nodes
.copy_and_replace_nodes_from_tree_to_tree
.replace_logic
.tree_to_mermaid
.clone_tree
.yield_tree
and print_tree
.tree_to_pillow
function to reference online font file instead of relative path.pandas
optional dependency.to_dataframe
method is called on empty calendar.prune_path
and max_depth
.get_attr
method to allow default return value.add_path_to_tree
, dataframe_to_tree
, dataframe_to_tree_by_relation
to allow custom node types that takes in constructor arguments.str
type besides int
type.nested_dict_to_tree
to throw TypeError if child_key is not list type.path_name
to allow different node name of different dtypes; map everything to string type.find_relative_path
to find relative path from node.zigzag_iter
and zigzaggroup_iter
Tree traversal methods.path_name
to reduce number of recursive calls to root node for sep
.list_to_tree_by_relation
and dataframe_to_tree_by_relation
method to allow duplicate intermediate nodes (default is false).node_shape
parameter in dag_to_dot
export function for easier way to customize node shape.add_dict_to_tree_by_name
method rename argument from path_attrs
to name_attrs
.tree_to_dot
to handle cases when not all nodes have edge_attr
.dag_to_dot
to perform dictionary copy to prevent style from being overridden for child nodes.dataframe_to_tree
to handle case when path column is not the first column.Iterable
instead of List
for list_to_tree
and list_to_tree_by_relation
methods.sep
.show
method to print tree to console.sep
parameter to constructor instead of using getter and setter methods to set sep
.from_paths
for faster search performance, added with_full_path
parameter.to_paths
to be full path for faster search performance.to_paths
.sep
in paths by performing string replacement at the start.copy=True
.sep
differing in from_paths
and to_paths
which should not throw error.find_child
and find_children
to find single child or multiple children based on user-defined condition.numpy
package, only reject None
attributes when creating tree from DataFrame (previously it rejects [None]
).numpy
package, enhance test cases.find_children
to find_child_by_name
for clarity.mypy
.sep
of tree differing from the sep
in from_paths
and to_paths
.mypy
, added type checks to pre-commit hooks.go_to
method to be consistent with List[List[DAGNode]]
type.yield_tree
if node_name_or_path
is not found.print_tree
checking attributes with hasattr
to handle cases of null or 0 value attributes, add more test cases.node_shape
parameter in tree_to_dot
export function for easier way to customize node shape.go_to
BaseNode method to travel from one node to another node from the same tree.go_to
DAGNode method to travel from one node to another node from the same DAG.merge_leaves
type of modification, enhance documentation to provide more examples and illustrations.str_to_tree
accept prefixes to support unicode characters in node names.str_to_tree
to construct tree from tree string.tree_to_dot
to perform dictionary copy to prevent style from being overridden for child nodes.BNode
to BinaryNode
, and construct method list_to_btree
to list_to_binarytree
.print_tree
output to image using Pillow package.merge_children
argument not working as expected.merge_children
argument not working as expected.dataframe_to_tree_by_relation
unable to find parent node.bgcolor
to bg_colour
.list_to_tree_tuples
to list_to_tree_by_relation
.sep
for nested_dict_to_tree
.bigtree is a tree implementation package for Python. It integrates with Python lists, dictionaries, and pandas DataFrame.
Thank you for taking the time to contribute. Contributing to this package is an excellent opportunity to dive into tree implementations.
"},{"location":"contributing/#set-up","title":"Set Up","text":"First, fork the repository and clone the forked repository.
$ git clone git@github.com:<your-username>/bigtree.git\n
Next, create a virtual environment and activate it.
$ conda create -n bigtree_venv python=3.10\n$ conda activate bigtree_venv\n
To check if it worked,
$ which pip\n/<some directory>/envs/bigtree_venv/bin/pip\n
From the project folder, install the required python packages locally in editable mode and set up pre-commit checks.
$ python -m pip install -e \".[all]\"\n$ python -m pip install pre-commit\n$ pre-commit install\n
"},{"location":"contributing/#developing","title":"Developing","text":"After making your changes, create a new branch, add and commit your changed files. In this example, lets assume the changed file is README.md
. If there are any pre-commit changes and/or comments, do modify, re-add and re-commit your files.
$ git checkout -b chore/update-readme\n$ git add README.md\n$ git commit -m \"chore: updated README\"\n
Push your changes to your created branch and create a pull request from your fork.
$ git push origin chore/update-readme\n
"},{"location":"contributing/#testing-and-documentation","title":"Testing and Documentation","text":"If there are changes related to code, please make sure that the unit tests pass and the code coverage is 100%.
$ python -m pip install pytest coverage\n$ pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=bigtree\n
Make sure your add/update the tests and documentations accordingly.
If there are changes to the docstrings and/or sample codes in the docstring, do run the following lines of code to generate the coverage report and test report for docstrings. Refer to the console log for information on the file location of the reports.
$ python -m pip install hatch\n$ hatch run docs:coverage\n$ hatch run docs:doctest\n
"},{"location":"contributing/#convention-and-standards","title":"Convention and Standards","text":"When creating branches, it is recommended to create them in the format type/action
. For example,
$ git checkout -b feat/add-this\n
When performing commits, it is also recommended to follow conventional commits when writing commit messages.
During pre-commit checks, this project checks and formats code using black
, flake8
, isort
, and mypy
.
For testing, this project uses pytest
and coverage
package for testing of codes, and docstr-coverage
and doctest
package for testing of docstrings.
Please open an issue to discuss important changes before embarking on an implementation.
"},{"location":"dag/","title":"\ud83c\udf34 Directed Acyclic Graph (DAG)","text":"For Directed Acyclic Graph (DAG) implementation, there are 4 main components.
"},{"location":"dag/#node","title":"\ud83c\udf3c Node","text":"DAGNode
, extendable class for constructing Directed Acyclic Graph (DAG)Tree Implementation and Methods for Python, integrated with Python list, dictionary, and pandas DataFrame.
It is pythonic, making it easy to learn and extendable to many types of workflows.
Install bigtree
with pip
or conda
and get up and running in minutes
Getting started
View demonstration on how to use bigtree
Reference
Articles relating to trees and bigtree
View articles
Do support if you like this project!
Support me
Related Links:
There are two ways to install bigtree
, with pip (recommended) or conda.
To install bigtree
, run the following line in command prompt:
If tree needs to use pandas methods, it requires additional dependencies. Run the following line in command prompt:
pip install 'bigtree[pandas]'If tree needs to be exported to image, it requires additional dependencies. Run the following lines in command prompt:
pip install 'bigtree[image]'brew install gprof2dot # for MacOSconda install graphviz # for WindowsAlternatively, install all optional dependencies with the following line in command prompt:
pip install 'bigtree[all]'"},{"location":"install/#installation-with-conda","title":"Installation with conda","text":"To install bigtree
with conda, run the following line in command prompt:
For Tree implementation, there are 9 main components.
"},{"location":"tree/#node","title":"\ud83c\udf3a Node","text":"BaseNode
, extendable classNode
, BaseNode with node name attributeNode
, using parent and children constructorsNode
typeConstruct Binary Tree from a list.
"},{"location":"bigtree/binarytree/construct/#binary-tree-construct-methods","title":"Binary Tree Construct Methods","text":"Construct Binary Tree from Using heapq structure Add node attributes Listlist_to_binarytree
No"},{"location":"bigtree/binarytree/construct/#bigtree.binarytree.construct","title":"bigtree.binarytree.construct","text":""},{"location":"bigtree/binarytree/construct/#bigtree.binarytree.construct.list_to_binarytree","title":"list_to_binarytree","text":"list_to_binarytree(heapq_list, node_type=BinaryNode)\n
Construct tree from a list of numbers (int or float) in heapq format.
Examples:
>>> from bigtree import list_to_binarytree, tree_to_dot\n>>> nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>> root = list_to_binarytree(nums_list)\n>>> root.show()\n1\n\u251c\u2500\u2500 2\n\u2502 \u251c\u2500\u2500 4\n\u2502 \u2502 \u251c\u2500\u2500 8\n\u2502 \u2502 \u2514\u2500\u2500 9\n\u2502 \u2514\u2500\u2500 5\n\u2502 \u2514\u2500\u2500 10\n\u2514\u2500\u2500 3\n \u251c\u2500\u2500 6\n \u2514\u2500\u2500 7\n>>> graph = tree_to_dot(root, node_colour=\"gold\")\n>>> graph.write_png(\"assets/construct_binarytree.png\")\n
Parameters:
Name Type Description Defaultheapq_list
List[int]
list containing integer node names, ordered in heapq fashion
requirednode_type
Type[BinaryNode]
node type of tree to be created, defaults to BinaryNode
BinaryNode
Returns:
Type DescriptionBinaryNode
(BinaryNode)
"},{"location":"bigtree/dag/","title":"\ud83c\udf34 Directed Acyclic Graph (DAG)","text":""},{"location":"bigtree/dag/construct/","title":"\u2728 Construct","text":"Construct Directed Acyclic Graph (DAG) from list, dictionary, and pandas DataFrame.
"},{"location":"bigtree/dag/construct/#dag-construct-methods","title":"DAG Construct Methods","text":"Construct DAG from Using parent-child relation Add node attributes Listlist_to_dag
No Dictionary dict_to_dag
Yes DataFrame dataframe_to_dag
Yes These functions are not standalone functions. Under the hood, they have the following dependency,
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct","title":"bigtree.dag.construct","text":""},{"location":"bigtree/dag/construct/#bigtree.dag.construct.list_to_dag","title":"list_to_dag","text":"list_to_dag(relations, node_type=DAGNode)\n
Construct DAG from list of tuples containing parent-child names. Note that node names must be unique.
Examples:
>>> from bigtree import list_to_dag, dag_iterator\n>>> relations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\n>>> dag = list_to_dag(relations_list)\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultrelations
List[Tuple[str, str]]
list containing tuple of parent-child names
requirednode_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct.dict_to_dag","title":"dict_to_dag","text":"dict_to_dag(\n relation_attrs, parent_key=\"parents\", node_type=DAGNode\n)\n
Construct DAG from nested dictionary, key
: child name, value
: dictionary of parent names, attribute name, and attribute value. Note that node names must be unique.
Examples:
>>> from bigtree import dict_to_dag, dag_iterator\n>>> relation_dict = {\n... \"a\": {\"step\": 1},\n... \"b\": {\"step\": 1},\n... \"c\": {\"parents\": [\"a\", \"b\"], \"step\": 2},\n... \"d\": {\"parents\": [\"a\", \"c\"], \"step\": 2},\n... \"e\": {\"parents\": [\"d\"], \"step\": 3},\n... }\n>>> dag = dict_to_dag(relation_dict, parent_key=\"parents\")\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultrelation_attrs
Dict[str, Any]
dictionary containing node, node parents, and node attribute information, key: child name, value: dictionary of parent names, node attribute, and attribute value
requiredparent_key
str
key of dictionary to retrieve list of parents name, defaults to 'parent'
'parents'
node_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/construct/#bigtree.dag.construct.dataframe_to_dag","title":"dataframe_to_dag","text":"dataframe_to_dag(\n data,\n child_col=\"\",\n parent_col=\"\",\n attribute_cols=[],\n node_type=DAGNode,\n)\n
Construct DAG from pandas DataFrame. Note that node names must be unique.
child_col
and parent_col
specify columns for child name and parent name to construct DAG.attribute_cols
specify columns for node attribute for child name.child_col
takes first column, parent_col
takes second column, and all other columns are attribute_cols
.Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_dag, dag_iterator\n>>> relation_data = pd.DataFrame([\n... [\"a\", None, 1],\n... [\"b\", None, 1],\n... [\"c\", \"a\", 2],\n... [\"c\", \"b\", 2],\n... [\"d\", \"a\", 2],\n... [\"d\", \"c\", 2],\n... [\"e\", \"d\", 3],\n... ],\n... columns=[\"child\", \"parent\", \"step\"]\n... )\n>>> dag = dataframe_to_dag(relation_data)\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)]\n[('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredchild_col
str
column of data containing child name information, defaults to '' if not set, it will take the first column of data
''
parent_col
str
column of data containing parent name information, defaults to '' if not set, it will take the second column of data
''
attribute_cols
List[str]
columns of data containing child node attribute information, if not set, it will take all columns of data except child_col
and parent_col
[]
node_type
Type[DAGNode]
node type of DAG to be created, defaults to DAGNode
DAGNode
Returns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/dag/export/","title":"\ud83d\udd28 Export","text":"Export Directed Acyclic Graph (DAG) to list, dictionary, and pandas DataFrame.
"},{"location":"bigtree/dag/export/#dag-export-methods","title":"DAG Export Methods","text":"Export DAG to Method Extract node attributes Listdag_to_list
No Dictionary dag_to_dict
Yes with attr_dict
or all_attrs
DataFrame dag_to_dataframe
Yes with attr_dict
or all_attrs
Dot (for .dot, .png, .svg, .jpeg, etc.) dag_to_dot
No"},{"location":"bigtree/dag/export/#bigtree.dag.export","title":"bigtree.dag.export","text":""},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_list","title":"dag_to_list","text":"dag_to_list(dag)\n
Export DAG to list of tuples containing parent-child names
Examples:
>>> from bigtree import DAGNode, dag_to_list\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_list(a)\n[('a', 'c'), ('a', 'd'), ('b', 'c'), ('c', 'd'), ('d', 'e')]\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredReturns:
Type DescriptionList[Tuple[str, str]]
(List[Tuple[str, str]])
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dict","title":"dag_to_dict","text":"dag_to_dict(\n dag, parent_key=\"parents\", attr_dict={}, all_attrs=False\n)\n
Export DAG to dictionary.
Exported dictionary will have key as child name, and parent names and node attributes as a nested dictionary.
Examples:
>>> from bigtree import DAGNode, dag_to_dict\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_dict(a, parent_key=\"parent\", attr_dict={\"step\": \"step no.\"})\n{'a': {'step no.': 1}, 'c': {'parent': ['a', 'b'], 'step no.': 2}, 'd': {'parent': ['a', 'c'], 'step no.': 2}, 'b': {'step no.': 1}, 'e': {'parent': ['d'], 'step no.': 3}}\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredparent_key
str
dictionary key for node.parent.node_name
, defaults to parents
'parents'
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 Node
attributes, defaults to False
False
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dataframe","title":"dag_to_dataframe","text":"dag_to_dataframe(\n dag,\n name_col=\"name\",\n parent_col=\"parent\",\n attr_dict={},\n all_attrs=False,\n)\n
Export DAG to pandas DataFrame.
Examples:
>>> from bigtree import DAGNode, dag_to_dataframe\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_to_dataframe(a, name_col=\"name\", parent_col=\"parent\", attr_dict={\"step\": \"step no.\"})\n name parent step no.\n0 a None 1\n1 c a 2\n2 d a 2\n3 b None 1\n4 c b 2\n5 d c 2\n6 e d 3\n
Parameters:
Name Type Description Defaultdag
DAGNode
DAG to be exported
requiredname_col
str
column name for node.node_name
, defaults to 'name'
'name'
parent_col
str
column name for node.parent.node_name
, defaults to 'parent'
'parent'
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 Node
attributes, defaults to False
False
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/dag/export/#bigtree.dag.export.dag_to_dot","title":"dag_to_dot","text":"dag_to_dot(\n dag,\n rankdir=\"TB\",\n bg_colour=\"\",\n node_colour=\"\",\n node_shape=\"\",\n edge_colour=\"\",\n node_attr=\"\",\n edge_attr=\"\",\n)\n
Export DAG or list of DAGs to image. Note that node names must be unique. Possible node attributes include style, fillcolor, shape.
Examples:
>>> from bigtree import DAGNode, dag_to_dot\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> dag_graph = dag_to_dot(a)\n
Display image directly without saving (requires IPython)
>>> from IPython.display import Image, display\n>>> plt = Image(dag_graph.create_png())\n>>> display(plt)\n<IPython.core.display.Image object>\n
Export to image, dot file, etc.
>>> dag_graph.write_png(\"assets/docstr/tree_dag.png\")\n>>> dag_graph.write_dot(\"assets/docstr/tree_dag.dot\")\n
Export to string
>>> dag_graph.to_string()\n'strict digraph G {\\nrankdir=TB;\\nc [label=c];\\na [label=a];\\na -> c;\\nd [label=d];\\na [label=a];\\na -> d;\\nc [label=c];\\nb [label=b];\\nb -> c;\\nd [label=d];\\nc [label=c];\\nc -> d;\\ne [label=e];\\nd [label=d];\\nd -> e;\\n}\\n'\n
Parameters:
Name Type Description Defaultdag
Union[DAGNode, List[DAGNode]]
DAG or list of DAGs to be exported
requiredrankdir
str
set direction of graph layout, defaults to 'TB', can be 'BT, 'LR', 'RL'
'TB'
bg_colour
str
background color of image, defaults to ''
''
node_colour
str
fill colour of nodes, defaults to ''
''
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 ''
''
node_attr
str
node attribute for style, overrides node_colour, defaults to '' Possible node attributes include {\"style\": \"filled\", \"fillcolor\": \"gold\"}
''
edge_attr
str
edge attribute for style, overrides edge_colour, defaults to '' Possible edge attributes include {\"style\": \"bold\", \"label\": \"edge label\", \"color\": \"black\"}
''
Returns:
Type DescriptionDot
(pydot.Dot)
"},{"location":"bigtree/node/","title":"\ud83c\udf3f Node","text":""},{"location":"bigtree/node/basenode/","title":"\ud83c\udf31 BaseNode","text":""},{"location":"bigtree/node/basenode/#bigtree.node.basenode","title":"bigtree.node.basenode","text":""},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode","title":"BaseNode","text":"BaseNode(parent=None, children=None, **kwargs)\n
BaseNode extends any Python class to a tree node. Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other with parent
and children
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
Examples:
>>> from bigtree import Node, print_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65)\n>>> c = Node(\"c\", age=60)\n>>> d = Node(\"d\", age=40)\n>>> root.children = [b, c]\n>>> d.parent = b\n>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u2514\u2500\u2500 d [age=40]\n\u2514\u2500\u2500 c [age=60]\n
>>> from bigtree import Node\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65)\n>>> c = Node(\"c\", age=60)\n>>> d = Node(\"d\", age=40)\n>>> root >> b\n>>> root >> c\n>>> d << b\n>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u2514\u2500\u2500 d [age=40]\n\u2514\u2500\u2500 c [age=60]\n
Directly passing parent
argument.
>>> from bigtree import Node\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n
Directly passing children
argument.
>>> from bigtree import Node\n>>> d = Node(\"d\")\n>>> c = Node(\"c\")\n>>> b = Node(\"b\", children=[d])\n>>> a = Node(\"a\", children=[b, c])\n
BaseNode Creation
Node can be created by instantiating a BaseNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import Node\n>>> root = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
BaseNode Attributes
These are node attributes that have getter and/or setter methods.
Get and set other BaseNode
parent
: Get/set parent nodechildren
: Get/set child nodesGet other BaseNode
ancestors
: Get ancestors of node excluding self, iteratordescendants
: Get descendants of node excluding self, iteratorleaves
: Get all leaf node(s) from self, iteratorsiblings
: Get siblings of selfleft_sibling
: Get sibling left of selfright_sibling
: Get sibling right of selfGet BaseNode
configuration
node_path
: Get tuple of nodes from rootis_root
: Get indicator if self is root nodeis_leaf
: Get indicator if self is leaf noderoot
: Get root node of treedepth
: Get depth of selfmax_depth
: Get maximum depth from root to leaf nodeBaseNode Methods
These are methods available to be performed on BaseNode
.
Constructor methods
from_dict()
: Create BaseNode from dictionaryBaseNode
methods
describe()
: Get node information sorted by attributes, return list of tuplesget_attr(attr_name: str)
: Get value of node attributeset_attrs(attrs: dict)
: Set node attribute name(s) and value(s)go_to(node: Self)
: Get a path from own node to another node from same treeappend(node: Self)
: Add child to nodeextend(nodes: List[Self])
: Add multiple children to nodecopy()
: Deep copy selfsort()
: Sort child nodesproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.parents","title":"parentsproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Self, ...])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/basenode/#bigtree.node.basenode.BaseNode.sort","title":"sort","text":"sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.name
, reverse=True
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node('a')\n>>> c = Node(\"c\", parent=a)\n>>> b = Node(\"b\", parent=a)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 b\n>>> a.sort(key=lambda node: node.name)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
"},{"location":"bigtree/node/binarynode/","title":"\ud83c\udf38 BinaryNode","text":""},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode","title":"bigtree.node.binarynode","text":""},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode","title":"BinaryNode","text":"BinaryNode(\n name=\"\",\n left=None,\n right=None,\n parent=None,\n children=None,\n **kwargs\n)\n
Bases: Node
BinaryNode is an extension of Node, and is able to extend to any Python class for Binary Tree implementation. Nodes can have attributes if they are initialized from BinaryNode
, dictionary, or pandas DataFrame.
BinaryNode can be linked to each other with children
, left
, or right
setter methods. If initialized with children
, it must be length 2, denoting left and right child.
Examples:
>>> from bigtree import BinaryNode, print_tree\n>>> a = BinaryNode(1)\n>>> b = BinaryNode(2)\n>>> c = BinaryNode(3)\n>>> d = BinaryNode(4)\n>>> a.children = [b, c]\n>>> b.right = d\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 2\n\u2502 \u2514\u2500\u2500 4\n\u2514\u2500\u2500 3\n
Directly passing left
, right
, or children
argument.
>>> from bigtree import BinaryNode\n>>> d = BinaryNode(4)\n>>> c = BinaryNode(3)\n>>> b = BinaryNode(2, right=d)\n>>> a = BinaryNode(1, children=[b, c])\n
BinaryNode Creation
Node can be created by instantiating a BinaryNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import BinaryNode\n>>> a = BinaryNode.from_dict({\"name\": \"1\"})\n>>> a\nBinaryNode(name=1, val=1)\n
BinaryNode Attributes
These are node attributes that have getter and/or setter methods.
Get BinaryNode
configuration
left
: Get left childrenright
: Get right childrenproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.sep","title":"sepproperty
writable
","text":"sep\n
Get separator, gets from root node
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.path_name","title":"path_nameproperty
","text":"path_name\n
Get path name, separated by self.sep
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.left","title":"leftproperty
writable
","text":"left\n
Get left children
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.right","title":"rightproperty
writable
","text":"right\n
Get right children
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.parent","title":"parentproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Optional[Self]])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/binarynode/#bigtree.node.binarynode.BinaryNode.show","title":"show","text":"show(**kwargs)\n
Print tree to console, takes in same keyword arguments as print_tree
function
hshow(**kwargs)\n
Print tree in horizontal orientation to console, takes in same keyword arguments as hprint_tree
function
sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.val
, reverse=True
Examples:
>>> from bigtree import BinaryNode, print_tree\n>>> a = BinaryNode(1)\n>>> c = BinaryNode(3, parent=a)\n>>> b = BinaryNode(2, parent=a)\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 3\n\u2514\u2500\u2500 2\n>>> a.sort(key=lambda node: node.val)\n>>> print_tree(a)\n1\n\u251c\u2500\u2500 2\n\u2514\u2500\u2500 3\n
"},{"location":"bigtree/node/dagnode/","title":"\ud83c\udf3c DAGNode","text":""},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode","title":"bigtree.node.dagnode","text":""},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode","title":"DAGNode","text":"DAGNode(name='', parents=None, children=None, **kwargs)\n
Base DAGNode extends any Python class to a DAG node, for DAG implementation. In DAG implementation, a node can have multiple parents.
Parents and children cannot be reassigned once assigned, as Nodes are allowed to have multiple parents and children. If each node only has one parent, use Node
class. DAGNodes can have attributes if they are initialized from DAGNode
or dictionary.
DAGNode can be linked to each other with parents
and children
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> c.parents = [a, b]\n>>> c.children = [d]\n
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> a >> c\n>>> b >> c\n>>> d << c\n
Directly passing parents
argument.
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\", parents=[a, b])\n>>> d = DAGNode(\"d\", parents=[c])\n
Directly passing children
argument.
>>> from bigtree import DAGNode\n>>> d = DAGNode(\"d\")\n>>> c = DAGNode(\"c\", children=[d])\n>>> b = DAGNode(\"b\", children=[c])\n>>> a = DAGNode(\"a\", children=[c])\n
DAGNode Creation
Node can be created by instantiating a DAGNode
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import DAGNode\n>>> a = DAGNode.from_dict({\"name\": \"a\", \"age\": 90})\n
DAGNode Attributes
These are node attributes that have getter and/or setter methods.
Get and set other DAGNode
parents
: Get/set parent nodeschildren
: Get/set child nodesGet other DAGNode
ancestors
: Get ancestors of node excluding self, iteratordescendants
: Get descendants of node excluding self, iteratorsiblings
: Get siblings of selfGet DAGNode
configuration
node_name
: Get node name, without accessing name
directlyis_root
: Get indicator if self is root nodeis_leaf
: Get indicator if self is leaf nodeDAGNode Methods
These are methods available to be performed on DAGNode
.
Constructor methods
from_dict()
: Create DAGNode from dictionaryDAGNode
methods
describe()
: Get node information sorted by attributes, return list of tuplesget_attr(attr_name: str)
: Get value of node attributeset_attrs(attrs: dict)
: Set node attribute name(s) and value(s)go_to(node: Self)
: Get a path from own node to another node from same DAGcopy()
: Deep copy selfproperty
writable
","text":"parent\n
Do not allow parent
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.parents","title":"parentsproperty
writable
","text":"parents\n
Get parent nodes
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionDAGNode
(DAGNode)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.dagnode import DAGNode\n>>> a = DAGNode('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nDAGNode(a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.go_to","title":"go_to","text":"go_to(node)\n
Get list of possible paths from current node to specified node from same tree
Examples:
>>> from bigtree import DAGNode\n>>> a = DAGNode(\"a\")\n>>> b = DAGNode(\"b\")\n>>> c = DAGNode(\"c\")\n>>> d = DAGNode(\"d\")\n>>> a >> c\n>>> b >> c\n>>> c >> d\n>>> a >> d\n>>> a.go_to(c)\n[[DAGNode(a, ), DAGNode(c, )]]\n>>> a.go_to(d)\n[[DAGNode(a, ), DAGNode(c, ), DAGNode(d, )], [DAGNode(a, ), DAGNode(d, )]]\n>>> a.go_to(b)\nTraceback (most recent call last):\n ...\nbigtree.utils.exceptions.TreeError: It is not possible to go to DAGNode(b, )\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionList[List[T]]
(List[List[Self]])
"},{"location":"bigtree/node/dagnode/#bigtree.node.dagnode.DAGNode.copy","title":"copy","text":"copy()\n
Deep copy self; clone DAGNode
Examples:
>>> from bigtree.node.dagnode import DAGNode\n>>> a = DAGNode('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/","title":"\ud83c\udf3a Node","text":""},{"location":"bigtree/node/node/#bigtree.node.node","title":"bigtree.node.node","text":""},{"location":"bigtree/node/node/#bigtree.node.node.Node","title":"Node","text":"Node(name='', sep='/', **kwargs)\n
Bases: BaseNode
Node is an extension of BaseNode, and is able to extend to any Python class. Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other with parent
and children
setter methods.
Examples:
>>> from bigtree import Node\n>>> a = Node(\"a\")\n>>> b = Node(\"b\")\n>>> c = Node(\"c\")\n>>> d = Node(\"d\")\n>>> b.parent = a\n>>> b.children = [c, d]\n
Directly passing parent
argument.
>>> from bigtree import Node\n>>> a = Node(\"a\")\n>>> b = Node(\"b\", parent=a)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n
Directly passing children
argument.
>>> from bigtree import Node\n>>> d = Node(\"d\")\n>>> c = Node(\"c\")\n>>> b = Node(\"b\", children=[c, d])\n>>> a = Node(\"a\", children=[b])\n
Node Creation
Node can be created by instantiating a Node
class or by using a dictionary. If node is created with dictionary, all keys of dictionary will be stored as class attributes.
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Node Attributes
These are node attributes that have getter and/or setter methods.
Get and set Node
configuration
sep
: Get/set separator for path nameGet Node
configuration
node_name
: Get node name, without accessing name
directlypath_name
: Get path name from root, separated by sep
Node Methods
These are methods available to be performed on Node
.
Node
methods
show()
: Print tree to consolehshow()
: Print tree in horizontal orientation to consoleproperty
writable
","text":"parent\n
Get parent node
Returns:
Type DescriptionOptional[T]
(Optional[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.children","title":"childrendeletable
property
writable
","text":"children\n
Get child nodes
Returns:
Type DescriptionTuple[T, ...]
(Tuple[Self, ...])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.parents","title":"parentsproperty
writable
","text":"parents\n
Do not allow parents
attribute to be accessed
Raises:
Type DescriptionAttributeError
No such attribute
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.ancestors","title":"ancestorsproperty
","text":"ancestors\n
Get iterator to yield all ancestors of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.descendants","title":"descendantsproperty
","text":"descendants\n
Get iterator to yield all descendants of self, does not include self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.leaves","title":"leavesproperty
","text":"leaves\n
Get iterator to yield all leaf nodes from self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.siblings","title":"siblingsproperty
","text":"siblings\n
Get siblings of self
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.left_sibling","title":"left_siblingproperty
","text":"left_sibling\n
Get sibling left of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.right_sibling","title":"right_siblingproperty
","text":"right_sibling\n
Get sibling right of self
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.node_path","title":"node_pathproperty
","text":"node_path\n
Get tuple of nodes starting from root
Returns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.is_root","title":"is_rootproperty
","text":"is_root\n
Get indicator if self is root node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.is_leaf","title":"is_leafproperty
","text":"is_leaf\n
Get indicator if self is leaf node
Returns:
Type Descriptionbool
(bool)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.root","title":"rootproperty
","text":"root\n
Get root node of tree
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.depth","title":"depthproperty
","text":"depth\n
Get depth of self, indexing starts from 1
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.max_depth","title":"max_depthproperty
","text":"max_depth\n
Get maximum depth from root to leaf node
Returns:
Type Descriptionint
(int)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.sep","title":"sepproperty
writable
","text":"sep\n
Get separator, gets from root node
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.node_name","title":"node_nameproperty
","text":"node_name\n
Get node name
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.path_name","title":"path_nameproperty
","text":"path_name\n
Get path name, separated by self.sep
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.from_dict","title":"from_dictclassmethod
","text":"from_dict(input_dict)\n
Construct node from dictionary, all keys of dictionary will be stored as class attributes Input dictionary must have key name
if not Node
will not have any name
Examples:
>>> from bigtree import Node\n>>> a = Node.from_dict({\"name\": \"a\", \"age\": 90})\n
Parameters:
Name Type Description Defaultinput_dict
Dict[str, Any]
dictionary with node information, key: attribute name, value: attribute value
requiredReturns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.describe","title":"describe","text":"describe(exclude_attributes=[], exclude_prefix='')\n
Get node information sorted by attribute name, returns list of tuples
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.describe()\n[('_BaseNode__children', []), ('_BaseNode__parent', None), ('_sep', '/'), ('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\")\n[('age', 90), ('name', 'a')]\n>>> a.describe(exclude_prefix=\"_\", exclude_attributes=[\"name\"])\n[('age', 90)]\n
Parameters:
Name Type Description Defaultexclude_attributes
List[str]
list of attributes to exclude
[]
exclude_prefix
str
prefix of attributes to exclude
''
Returns:
Type DescriptionList[Tuple[str, Any]]
(List[Tuple[str, Any]])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.get_attr","title":"get_attr","text":"get_attr(attr_name, default_value=None)\n
Get value of node attribute Returns default value if attribute name does not exist
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a', age=90)\n>>> a.get_attr(\"age\")\n90\n
Parameters:
Name Type Description Defaultattr_name
str
attribute name
requireddefault_value
Any
default value if attribute does not exist, defaults to None
None
Returns:
Type DescriptionAny
(Any)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.set_attrs","title":"set_attrs","text":"set_attrs(attrs)\n
Set node attributes
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a.set_attrs({\"age\": 90})\n>>> a\nNode(/a, age=90)\n
Parameters:
Name Type Description Defaultattrs
Dict[str, Any]
attribute dictionary, key: attribute name, value: attribute value
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.go_to","title":"go_to","text":"go_to(node)\n
Get path from current node to specified node from same tree
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node(name=\"a\")\n>>> b = Node(name=\"b\", parent=a)\n>>> c = Node(name=\"c\", parent=a)\n>>> d = Node(name=\"d\", parent=b)\n>>> e = Node(name=\"e\", parent=b)\n>>> f = Node(name=\"f\", parent=c)\n>>> g = Node(name=\"g\", parent=e)\n>>> h = Node(name=\"h\", parent=e)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n>>> d.go_to(d)\n[Node(/a/b/d, )]\n>>> d.go_to(g)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a/b/e, ), Node(/a/b/e/g, )]\n>>> d.go_to(f)\n[Node(/a/b/d, ), Node(/a/b, ), Node(/a, ), Node(/a/c, ), Node(/a/c/f, )]\n
Parameters:
Name Type Description Defaultnode
Self
node to travel to from current node, inclusive of start and end node
requiredReturns:
Type DescriptionIterable[T]
(Iterable[Self])
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.append","title":"append","text":"append(other)\n
Add other as child of self
Parameters:
Name Type Description Defaultother
Self
other node, child to be added
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.extend","title":"extend","text":"extend(others)\n
Add others as children of self
Parameters:
Name Type Description Defaultothers
Self
other nodes, children to be added
required"},{"location":"bigtree/node/node/#bigtree.node.node.Node.copy","title":"copy","text":"copy()\n
Deep copy self; clone self
Examples:
>>> from bigtree.node.node import Node\n>>> a = Node('a')\n>>> a_copy = a.copy()\n
Returns:
Type DescriptionT
(Self)
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.sort","title":"sort","text":"sort(**kwargs)\n
Sort children, possible keyword arguments include key=lambda node: node.name
, reverse=True
Examples:
>>> from bigtree import Node, print_tree\n>>> a = Node('a')\n>>> c = Node(\"c\", parent=a)\n>>> b = Node(\"b\", parent=a)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 b\n>>> a.sort(key=lambda node: node.name)\n>>> print_tree(a)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
"},{"location":"bigtree/node/node/#bigtree.node.node.Node.show","title":"show","text":"show(**kwargs)\n
Print tree to console, takes in same keyword arguments as print_tree
function
hshow(**kwargs)\n
Print tree in horizontal orientation to console, takes in same keyword arguments as hprint_tree
function
Construct Tree from list, dictionary, and pandas DataFrame.
To decide which method to use, consider your data type and data values.
Construct tree from Using full path Using parent-child relation Using notation Add node attributes Stringstr_to_tree
NA newick_to_tree
No (for str_to_tree
)Yes (for newick_to_tree
) List list_to_tree
list_to_tree_by_relation
NA No Dictionary dict_to_tree
nested_dict_to_tree
NA Yes DataFrame dataframe_to_tree
dataframe_to_tree_by_relation
NA Yes"},{"location":"bigtree/tree/construct/#tree-add-attributes-methods","title":"Tree Add Attributes Methods","text":"To add attributes to an existing tree,
Add attributes from Using full path Using node name Stringadd_path_to_tree
NA Dictionary add_dict_to_tree_by_path
add_dict_to_tree_by_name
DataFrame add_dataframe_to_tree_by_path
add_dataframe_to_tree_by_name
Note
If attributes are added to existing tree using full path, paths that previously did not exist will be added. If attributes are added to existing tree using node name, names that previously did not exist will not be created.
These functions are not standalone functions. Under the hood, they have the following dependency,
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct","title":"bigtree.tree.construct","text":""},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_path_to_tree","title":"add_path_to_tree","text":"add_path_to_tree(\n tree,\n path,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_attrs={},\n)\n
Add nodes and attributes to existing tree in-place, return node of path added. Adds to existing tree from list of path strings.
Path should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import add_path_to_tree, Node\n>>> root = Node(\"a\")\n>>> add_path_to_tree(root, \"a/b/c\")\nNode(/a/b/c, )\n>>> root.show()\na\n\u2514\u2500\u2500 b\n \u2514\u2500\u2500 c\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredpath
str
path to be added to tree
requiredsep
str
path separator for input path
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_attrs
Dict[str, Any]
attributes to add to node, key: attribute name, value: attribute value, optional
{}
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dict_to_tree_by_path","title":"add_dict_to_tree_by_path","text":"add_dict_to_tree_by_path(\n tree, path_attrs, sep=\"/\", duplicate_name_allowed=True\n)\n
Add nodes and attributes to tree in-place, return root of tree. Adds to existing tree from nested dictionary, key
: path, value
: dict of attribute name and attribute value.
Path should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import Node, add_dict_to_tree_by_path\n>>> root = Node(\"a\")\n>>> path_dict = {\n... \"a\": {\"age\": 90},\n... \"a/b\": {\"age\": 65},\n... \"a/c\": {\"age\": 60},\n... \"a/b/d\": {\"age\": 40},\n... \"a/b/e\": {\"age\": 35},\n... \"a/c/f\": {\"age\": 38},\n... \"a/b/e/g\": {\"age\": 10},\n... \"a/b/e/h\": {\"age\": 6},\n... }\n>>> root = add_dict_to_tree_by_path(root, path_dict)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredpath_attrs
Dict[str, Dict[str, Any]]
dictionary containing node path and attribute information, key: node path, value: dict of node attribute name and attribute value
requiredsep
str
path separator for input path_attrs
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dict_to_tree_by_name","title":"add_dict_to_tree_by_name","text":"add_dict_to_tree_by_name(\n tree, name_attrs, join_type=\"left\"\n)\n
Add attributes to tree, return new root of tree. Adds to existing tree from nested dictionary, key
: name, value
: dict of attribute name and attribute value.
Function can return all existing tree nodes or only tree nodes that are in the input dictionary keys depending on join type. Input dictionary keys that are not existing node names will be ignored. Note that if multiple nodes have the same name, attributes will be added to all nodes sharing the same name.
Examples:
>>> from bigtree import Node, add_dict_to_tree_by_name\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> name_dict = {\n... \"a\": {\"age\": 90},\n... \"b\": {\"age\": 65},\n... }\n>>> root = add_dict_to_tree_by_name(root, name_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requiredname_attrs
Dict[str, Dict[str, Any]]
dictionary containing node name and attribute information, key: node name, value: dict of node attribute name and attribute value
requiredjoin_type
str
join type with attribute, default of 'left' takes existing tree nodes, if join_type is set to 'inner' it will only take tree nodes that are in name_attrs
key and drop others
'left'
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dataframe_to_tree_by_path","title":"add_dataframe_to_tree_by_path","text":"add_dataframe_to_tree_by_path(\n tree,\n data,\n path_col=\"\",\n attribute_cols=[],\n sep=\"/\",\n duplicate_name_allowed=True,\n)\n
Add nodes and attributes to tree in-place, return root of tree.
path_col
and attribute_cols
specify columns for node path and attributes to add to existing tree. If columns are not specified, path_col
takes first column and all other columns are attribute_cols
Path in path column should contain Node
name, separated by sep
.
sep
is for the input path
and can differ from existing tree.Path in path column can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> import pandas as pd\n>>> from bigtree import add_dataframe_to_tree_by_path, Node\n>>> root = Node(\"a\")\n>>> path_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"a/b\", 65],\n... [\"a/c\", 60],\n... [\"a/b/d\", 40],\n... [\"a/b/e\", 35],\n... [\"a/c/f\", 38],\n... [\"a/b/e/g\", 10],\n... [\"a/b/e/h\", 6],\n... ],\n... columns=[\"PATH\", \"age\"]\n... )\n>>> root = add_dataframe_to_tree_by_path(root, path_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requireddata
DataFrame
data containing node path and attribute information
requiredpath_col
str
column of data containing path_name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
sep
str
path separator for input path_col
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.add_dataframe_to_tree_by_name","title":"add_dataframe_to_tree_by_name","text":"add_dataframe_to_tree_by_name(\n tree,\n data,\n name_col=\"\",\n attribute_cols=[],\n join_type=\"left\",\n)\n
Add attributes to tree, return new root of tree.
name_col
and attribute_cols
specify columns for node name and attributes to add to existing tree. If columns are not specified, the first column will be taken as name column and all other columns as attributes.
Function can return all existing tree nodes or only tree nodes that are in the input data node names. Input data node names that are not existing node names will be ignored. Note that if multiple nodes have the same name, attributes will be added to all nodes sharing same name.
Examples:
>>> import pandas as pd\n>>> from bigtree import add_dataframe_to_tree_by_name, Node\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> name_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"b\", 65],\n... ],\n... columns=[\"NAME\", \"age\"]\n... )\n>>> root = add_dataframe_to_tree_by_name(root, name_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requireddata
DataFrame
data containing node name and attribute information
requiredname_col
str
column of data containing name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
column(s) of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
join_type
str
join type with attribute, default of 'left' takes existing tree nodes, if join_type is set to 'inner' it will only take tree nodes with attributes and drop the other nodes
'left'
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.str_to_tree","title":"str_to_tree","text":"str_to_tree(\n tree_string, tree_prefix_list=[], node_type=Node\n)\n
Construct tree from tree string
Examples:
>>> from bigtree import str_to_tree\n>>> tree_str = 'a\\n\u251c\u2500\u2500 b\\n\u2502 \u251c\u2500\u2500 d\\n\u2502 \u2514\u2500\u2500 e\\n\u2502 \u251c\u2500\u2500 g\\n\u2502 \u2514\u2500\u2500 h\\n\u2514\u2500\u2500 c\\n \u2514\u2500\u2500 f'\n>>> root = str_to_tree(tree_str, tree_prefix_list=[\"\u251c\u2500\u2500\", \"\u2514\u2500\u2500\"])\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaulttree_string
str
String to construct tree
requiredtree_prefix_list
List[str]
List of prefix to mark the end of tree branch/stem and start of node name, optional. If not specified, it will infer unicode characters and whitespace as prefix.
[]
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.list_to_tree","title":"list_to_tree","text":"list_to_tree(\n paths,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from list of path strings.
Path should contain Node
name, separated by sep
.
Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import list_to_tree\n>>> path_list = [\"a/b\", \"a/c\", \"a/b/d\", \"a/b/e\", \"a/c/f\", \"a/b/e/g\", \"a/b/e/h\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaultpaths
Iterable[str]
list containing path strings
requiredsep
str
path separator for input paths
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.list_to_tree_by_relation","title":"list_to_tree_by_relation","text":"list_to_tree_by_relation(\n relations, allow_duplicates=False, node_type=Node\n)\n
Construct tree from list of tuple containing parent-child names.
Since tree is created from parent-child names, only names of leaf nodes may be repeated. Error will be thrown if names of intermediate nodes are repeated as there will be confusion. This error can be ignored by setting allow_duplicates
to be True.
Examples:
>>> from bigtree import list_to_tree_by_relation\n>>> relations_list = [(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\"), (\"b\", \"e\"), (\"c\", \"f\"), (\"e\", \"g\"), (\"e\", \"h\")]\n>>> root = list_to_tree_by_relation(relations_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
Parameters:
Name Type Description Defaultrelations
Iterable[Tuple[str, str]]
list containing tuple containing parent-child names
requiredallow_duplicates
bool
allow duplicate intermediate nodes such that child node will be tagged to multiple parent nodes, defaults to False
False
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dict_to_tree","title":"dict_to_tree","text":"dict_to_tree(\n path_attrs,\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from nested dictionary using path, key
: path, value
: dict of attribute name and attribute value.
Path should contain Node
name, separated by sep
.
Path can start from root node name
, or start with sep
.
All paths should start from the same root node.
Examples:
>>> from bigtree import dict_to_tree\n>>> path_dict = {\n... \"a\": {\"age\": 90},\n... \"a/b\": {\"age\": 65},\n... \"a/c\": {\"age\": 60},\n... \"a/b/d\": {\"age\": 40},\n... \"a/b/e\": {\"age\": 35},\n... \"a/c/f\": {\"age\": 38},\n... \"a/b/e/g\": {\"age\": 10},\n... \"a/b/e/h\": {\"age\": 6},\n... }\n>>> root = dict_to_tree(path_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultpath_attrs
Dict[str, Any]
dictionary containing path and node attribute information, key: path, value: dict of tree attribute and attribute value
requiredsep
str
path separator of input path_attrs
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.nested_dict_to_tree","title":"nested_dict_to_tree","text":"nested_dict_to_tree(\n node_attrs,\n name_key=\"name\",\n child_key=\"children\",\n node_type=Node,\n)\n
Construct tree from nested recursive dictionary.
key
: name_key
, child_key
, or any attributes key.value
of name_key
(str): node name.value
of child_key
(List[Dict[str, Any]]): list of dict containing name_key
and child_key
(recursive).Examples:
>>> from bigtree import nested_dict_to_tree\n>>> path_dict = {\n... \"name\": \"a\",\n... \"age\": 90,\n... \"children\": [\n... {\"name\": \"b\",\n... \"age\": 65,\n... \"children\": [\n... {\"name\": \"d\", \"age\": 40},\n... {\"name\": \"e\", \"age\": 35, \"children\": [\n... {\"name\": \"g\", \"age\": 10},\n... ]},\n... ]},\n... ],\n... }\n>>> root = nested_dict_to_tree(path_dict)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u2514\u2500\u2500 b [age=65]\n \u251c\u2500\u2500 d [age=40]\n \u2514\u2500\u2500 e [age=35]\n \u2514\u2500\u2500 g [age=10]\n
Parameters:
Name Type Description Defaultnode_attrs
Dict[str, Any]
dictionary containing node, children, and node attribute information, key: name_key
and child_key
value of name_key
(str): node name value of child_key
(List[Dict[str, Any]]): list of dict containing name_key
and child_key
(recursive)
name_key
str
key of node name, value is type str
'name'
child_key
str
key of child list, value is type list
'children'
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dataframe_to_tree","title":"dataframe_to_tree","text":"dataframe_to_tree(\n data,\n path_col=\"\",\n attribute_cols=[],\n sep=\"/\",\n duplicate_name_allowed=True,\n node_type=Node,\n)\n
Construct tree from pandas DataFrame using path, return root of tree.
path_col
and attribute_cols
specify columns for node path and attributes to construct tree. If columns are not specified, path_col
takes first column and all other columns are attribute_cols
.
Path in path column can start from root node name
, or start with sep
.
Path in path column should contain Node
name, separated by sep
.
All paths should start from the same root node.
Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_tree\n>>> path_data = pd.DataFrame([\n... [\"a\", 90],\n... [\"a/b\", 65],\n... [\"a/c\", 60],\n... [\"a/b/d\", 40],\n... [\"a/b/e\", 35],\n... [\"a/c/f\", 38],\n... [\"a/b/e/g\", 10],\n... [\"a/b/e/h\", 6],\n... ],\n... columns=[\"PATH\", \"age\"]\n... )\n>>> root = dataframe_to_tree(path_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredpath_col
str
column of data containing path_name
information, if not set, it will take the first column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except path_col
[]
sep
str
path separator of input path_col
and created tree, defaults to /
'/'
duplicate_name_allowed
bool
indicator if nodes with duplicate Node
name is allowed, defaults to True
True
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.dataframe_to_tree_by_relation","title":"dataframe_to_tree_by_relation","text":"dataframe_to_tree_by_relation(\n data,\n child_col=\"\",\n parent_col=\"\",\n attribute_cols=[],\n allow_duplicates=False,\n node_type=Node,\n)\n
Construct tree from pandas DataFrame using parent and child names, return root of tree.
Since tree is created from parent-child names, only names of leaf nodes may be repeated. Error will be thrown if names of intermediate nodes are repeated as there will be confusion. This error can be ignored by setting allow_duplicates
to be True.
child_col
and parent_col
specify columns for child name and parent name to construct tree. attribute_cols
specify columns for node attribute for child name. If columns are not specified, child_col
takes first column, parent_col
takes second column, and all other columns are attribute_cols
.
Examples:
>>> import pandas as pd\n>>> from bigtree import dataframe_to_tree_by_relation\n>>> relation_data = pd.DataFrame([\n... [\"a\", None, 90],\n... [\"b\", \"a\", 65],\n... [\"c\", \"a\", 60],\n... [\"d\", \"b\", 40],\n... [\"e\", \"b\", 35],\n... [\"f\", \"c\", 38],\n... [\"g\", \"e\", 10],\n... [\"h\", \"e\", 6],\n... ],\n... columns=[\"child\", \"parent\", \"age\"]\n... )\n>>> root = dataframe_to_tree_by_relation(relation_data)\n>>> root.show(attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2502 \u251c\u2500\u2500 g [age=10]\n\u2502 \u2514\u2500\u2500 h [age=6]\n\u2514\u2500\u2500 c [age=60]\n \u2514\u2500\u2500 f [age=38]\n
Parameters:
Name Type Description Defaultdata
DataFrame
data containing path and node attribute information
requiredchild_col
str
column of data containing child name information, defaults to None if not set, it will take the first column of data
''
parent_col
str
column of data containing parent name information, defaults to None if not set, it will take the second column of data
''
attribute_cols
List[str]
columns of data containing node attribute information, if not set, it will take all columns of data except child_col
and parent_col
[]
allow_duplicates
bool
allow duplicate intermediate nodes such that child node will be tagged to multiple parent nodes, defaults to False
False
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/construct/#bigtree.tree.construct.newick_to_tree","title":"newick_to_tree","text":"newick_to_tree(\n tree_string,\n length_attr=\"length\",\n attr_prefix=\"&&NHX:\",\n node_type=Node,\n)\n
Construct tree from Newick notation, return root of tree.
In the Newick Notation (or New Hampshire Notation)
(child1,child2,child3)parent
.((grandchild1)child1,(grandchild2,grandchild3)child2)parent
.(child1:0.5,child2:0.1)parent
.(child1:0.5[S:human],child2:0.1[S:human])parent[S:parent]
.Variations supported
[
, ]
, (
, )
, :
, ,
) in node name, attribute name, and attribute values if they are enclosed in single quotes i.e., '(name:!)'.nodeN
with N representing a number.Examples:
>>> from bigtree import newick_to_tree\n>>> root = newick_to_tree(\"((d,e)b,c)a\")\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> root = newick_to_tree(\"((d:40,e:35)b:65,c:60)a\", length_attr=\"age\")\n>>> root.show(attr_list=[\"age\"])\na\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
>>> root = newick_to_tree(\n... \"((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]\",\n... length_attr=\"age\",\n... )\n>>> root.show(all_attrs=True)\na [species=human]\n\u251c\u2500\u2500 b [age=65, species=human]\n\u2502 \u251c\u2500\u2500 d [age=40, species=human]\n\u2502 \u2514\u2500\u2500 e [age=35, species=human]\n\u2514\u2500\u2500 c [age=60, species=human]\n
Parameters:
Name Type Description Defaulttree_string
str
Newick notation to construct tree
requiredlength_attr
str
attribute name to store node length, optional, defaults to 'length'
'length'
attr_prefix
str
prefix before all attributes, within square bracket, used to detect attributes, defaults to \"&&NHX:\"
'&&NHX:'
node_type
Type[Node]
node type of tree to be created, defaults to Node
Node
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/export/","title":"\ud83d\udd28 Export","text":""},{"location":"bigtree/tree/export/#tree-export-methods","title":"Tree Export Methods","text":"Export Tree to list, dictionary, and pandas DataFrame.
Export Tree to Method Command Line / Othersprint_tree
, yield_tree
, hprint_tree
, hyield_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_mermaid
Mermaid Markdown (for .md) tree_to_mermaid
"},{"location":"bigtree/tree/export/#tree-export-customizations","title":"Tree Export Customizations","text":"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 Othersprint_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."},{"location":"bigtree/tree/export/#bigtree.tree.export","title":"bigtree.tree.export","text":""},{"location":"bigtree/tree/export/#bigtree.tree.export.print_tree","title":"print_tree","text":"print_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n all_attrs=False,\n attr_list=[],\n attr_omit_null=False,\n attr_bracket=[\"[\", \"]\"],\n style=\"const\",\n custom_style=[],\n)\n
Print tree to console, starting from tree
.
node_name_or_path
max_depth
attr_name_filter
and all_attrs
attr_omit_null
attr_bracket
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 charactersExamples:
Printing tree
>>> from bigtree import Node, print_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> print_tree(root)\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
Printing Sub-tree
>>> print_tree(root, node_name_or_path=\"b\")\nb\n\u251c\u2500\u2500 d\n\u2514\u2500\u2500 e\n
>>> print_tree(root, max_depth=2)\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
Printing Attributes
>>> print_tree(root, attr_list=[\"age\"])\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
>>> print_tree(root, attr_list=[\"age\"], attr_bracket=[\"*(\", \")\"])\na *(age=90)\n\u251c\u2500\u2500 b *(age=65)\n\u2502 \u251c\u2500\u2500 d *(age=40)\n\u2502 \u2514\u2500\u2500 e *(age=35)\n\u2514\u2500\u2500 c *(age=60)\n
Available Styles
>>> print_tree(root, style=\"ansi\")\na\n|-- b\n| |-- d\n| `-- e\n`-- c\n
>>> print_tree(root, style=\"ascii\")\na\n|-- b\n| |-- d\n| +-- e\n+-- c\n
>>> print_tree(root, style=\"const\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> print_tree(root, style=\"const_bold\")\na\n\u2523\u2501\u2501 b\n\u2503 \u2523\u2501\u2501 d\n\u2503 \u2517\u2501\u2501 e\n\u2517\u2501\u2501 c\n
>>> print_tree(root, style=\"rounded\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2570\u2500\u2500 e\n\u2570\u2500\u2500 c\n
>>> print_tree(root, style=\"double\")\na\n\u2560\u2550\u2550 b\n\u2551 \u2560\u2550\u2550 d\n\u2551 \u255a\u2550\u2550 e\n\u255a\u2550\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
all_attrs
bool
indicator to show all attributes, defaults to False, overrides attr_list
and attr_omit_null
False
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
False
attr_bracket
List[str]
open and close bracket for all_attrs
or attr_list
['[', ']']
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of stem, branch and final stem, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.yield_tree","title":"yield_tree","text":"yield_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n style=\"const\",\n custom_style=[],\n)\n
Generator method for customizing printing of tree, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Yield tree
>>> from bigtree import Node, yield_tree\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> for branch, stem, node in yield_tree(root):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
Yield Sub-tree
>>> for branch, stem, node in yield_tree(root, node_name_or_path=\"b\"):\n... print(f\"{branch}{stem}{node.node_name}\")\nb\n\u251c\u2500\u2500 d\n\u2514\u2500\u2500 e\n
>>> for branch, stem, node in yield_tree(root, max_depth=2):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 c\n
Available Styles
>>> for branch, stem, node in yield_tree(root, style=\"ansi\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n|-- b\n| |-- d\n| `-- e\n`-- c\n
>>> for branch, stem, node in yield_tree(root, style=\"ascii\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n|-- b\n| |-- d\n| +-- e\n+-- c\n
>>> for branch, stem, node in yield_tree(root, style=\"const\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> for branch, stem, node in yield_tree(root, style=\"const_bold\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u2523\u2501\u2501 b\n\u2503 \u2523\u2501\u2501 d\n\u2503 \u2517\u2501\u2501 e\n\u2517\u2501\u2501 c\n
>>> for branch, stem, node in yield_tree(root, style=\"rounded\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2570\u2500\u2500 e\n\u2570\u2500\u2500 c\n
>>> for branch, stem, node in yield_tree(root, style=\"double\"):\n... print(f\"{branch}{stem}{node.node_name}\")\na\n\u2560\u2550\u2550 b\n\u2551 \u2560\u2550\u2550 d\n\u2551 \u255a\u2550\u2550 e\n\u255a\u2550\u2550 c\n
Printing Attributes
>>> for branch, stem, node in yield_tree(root, style=\"const\"):\n... print(f\"{branch}{stem}{node.node_name} [age={node.age}]\")\na [age=90]\n\u251c\u2500\u2500 b [age=65]\n\u2502 \u251c\u2500\u2500 d [age=40]\n\u2502 \u2514\u2500\u2500 e [age=35]\n\u2514\u2500\u2500 c [age=60]\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
style
str
style of print, defaults to const
'const'
custom_style
Iterable[str]
style of stem, branch and final stem, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.hprint_tree","title":"hprint_tree","text":"hprint_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n intermediate_node_name=True,\n style=\"const\",\n custom_style=[],\n)\n
Print tree in horizontal orientation to console, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Printing tree
>>> from bigtree import Node, hprint_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> hprint_tree(root)\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path=\"b\")\n \u250c\u2500 d\n\u2500 b \u2500\u2524\n \u2514\u2500 e\n
>>> hprint_tree(root, max_depth=2)\n \u250c\u2500 b\n\u2500 a \u2500\u2524\n \u2514\u2500 c\n
Available Styles
>>> hprint_tree(root, style=\"ansi\")\n /- d\n /- b -+\n- a -+ \\- e\n \\- c\n
>>> hprint_tree(root, style=\"ascii\")\n +- d\n +- b -+\n- a -+ +- e\n +- c\n
>>> hprint_tree(root, style=\"const\")\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
>>> hprint_tree(root, style=\"const_bold\")\n \u250f\u2501 d\n \u250f\u2501 b \u2501\u252b\n\u2501 a \u2501\u252b \u2517\u2501 e\n \u2517\u2501 c\n
>>> hprint_tree(root, style=\"rounded\")\n \u256d\u2500 d\n \u256d\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2570\u2500 e\n \u2570\u2500 c\n
>>> hprint_tree(root, style=\"double\")\n \u2554\u2550 d\n \u2554\u2550 b \u2550\u2563\n\u2550 a \u2550\u2563 \u255a\u2550 e\n \u255a\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
intermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
True
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of icons, used when style
is set to 'custom'
[]
"},{"location":"bigtree/tree/export/#bigtree.tree.export.hyield_tree","title":"hyield_tree","text":"hyield_tree(\n tree,\n node_name_or_path=\"\",\n max_depth=0,\n intermediate_node_name=True,\n style=\"const\",\n custom_style=[],\n)\n
Yield tree in horizontal orientation to console, starting from tree
.
node_name_or_path
max_depth
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 charactersExamples:
Printing tree
>>> from bigtree import Node, hyield_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=root)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> result = hyield_tree(root)\n>>> print(\"\\n\".join(result))\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
Printing Sub-tree
>>> hprint_tree(root, node_name_or_path=\"b\")\n \u250c\u2500 d\n\u2500 b \u2500\u2524\n \u2514\u2500 e\n
>>> hprint_tree(root, max_depth=2)\n \u250c\u2500 b\n\u2500 a \u2500\u2524\n \u2514\u2500 c\n
Available Styles
>>> hprint_tree(root, style=\"ansi\")\n /- d\n /- b -+\n- a -+ \\- e\n \\- c\n
>>> hprint_tree(root, style=\"ascii\")\n +- d\n +- b -+\n- a -+ +- e\n +- c\n
>>> hprint_tree(root, style=\"const\")\n \u250c\u2500 d\n \u250c\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2514\u2500 e\n \u2514\u2500 c\n
>>> hprint_tree(root, style=\"const_bold\")\n \u250f\u2501 d\n \u250f\u2501 b \u2501\u252b\n\u2501 a \u2501\u252b \u2517\u2501 e\n \u2517\u2501 c\n
>>> hprint_tree(root, style=\"rounded\")\n \u256d\u2500 d\n \u256d\u2500 b \u2500\u2524\n\u2500 a \u2500\u2524 \u2570\u2500 e\n \u2570\u2500 c\n
>>> hprint_tree(root, style=\"double\")\n \u2554\u2550 d\n \u2554\u2550 b \u2550\u2563\n\u2550 a \u2550\u2563 \u255a\u2550 e\n \u255a\u2550 c\n
Parameters:
Name Type Description Defaulttree
Node
tree to print
requirednode_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
0
intermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
True
style
str
style of print, defaults to const style
'const'
custom_style
Iterable[str]
style of icons, used when style
is set to 'custom'
[]
Returns:
Type DescriptionList[str]
(List[str])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_newick","title":"tree_to_newick","text":"tree_to_newick(\n tree,\n intermediate_node_name=True,\n length_attr=\"\",\n length_sep=NewickCharacter.SEP,\n attr_list=[],\n attr_prefix=\"&&NHX:\",\n attr_sep=NewickCharacter.SEP,\n)\n
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]
.
:
.&&NHX:
.:
.Examples:
>>> from bigtree import Node, tree_to_newick\n>>> root = Node(\"a\", species=\"human\")\n>>> b = Node(\"b\", age=65, species=\"human\", parent=root)\n>>> c = Node(\"c\", age=60, species=\"human\", parent=root)\n>>> d = Node(\"d\", age=40, species=\"human\", parent=b)\n>>> e = Node(\"e\", age=35, species=\"human\", parent=b)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n
>>> tree_to_newick(root)\n'((d,e)b,c)a'\n
>>> tree_to_newick(root, length_attr=\"age\")\n'((d:40,e:35)b:65,c:60)a'\n
>>> tree_to_newick(root, length_attr=\"age\", attr_list=[\"species\"])\n'((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]'\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredintermediate_node_name
bool
indicator if intermediate nodes have node names, defaults to True
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 \":\"
SEP
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:\"
'&&NHX:'
attr_sep
str
separator between attributes, within square brackets, used if attr_list is non-empty, defaults to \":\"
SEP
Returns:
Type Descriptionstr
(str)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dict","title":"tree_to_dict","text":"tree_to_dict(\n tree,\n name_key=\"name\",\n parent_key=\"\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n skip_depth=0,\n leaf_only=False,\n)\n
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.
Examples:
>>> from bigtree import Node, tree_to_dict\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_dict(root, name_key=\"name\", parent_key=\"parent\", attr_dict={\"age\": \"person age\"})\n{'/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}}\n
For a subset of a tree
>>> tree_to_dict(c, name_key=\"name\", parent_key=\"parent\", attr_dict={\"age\": \"person age\"})\n{'/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredname_key
str
dictionary key for node.node_name
, defaults to 'name'
'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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
skip_depth
int
number of initial depths to skip, optional
0
leaf_only
bool
indicator to retrieve only information from leaf nodes
False
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_nested_dict","title":"tree_to_nested_dict","text":"tree_to_nested_dict(\n tree,\n name_key=\"name\",\n child_key=\"children\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n)\n
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.
Examples:
>>> from bigtree import Node, tree_to_nested_dict\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_nested_dict(root, all_attrs=True)\n{'name': 'a', 'age': 90, 'children': [{'name': 'b', 'age': 65, 'children': [{'name': 'd', 'age': 40}, {'name': 'e', 'age': 35}]}, {'name': 'c', 'age': 60}]}\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredname_key
str
dictionary key for node.node_name
, defaults to 'name'
'name'
child_key
str
dictionary key for list of children, optional
'children'
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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
Returns:
Type DescriptionDict[str, Any]
(Dict[str, Any])
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dataframe","title":"tree_to_dataframe","text":"tree_to_dataframe(\n tree,\n path_col=\"path\",\n name_col=\"name\",\n parent_col=\"\",\n attr_dict={},\n all_attrs=False,\n max_depth=0,\n skip_depth=0,\n leaf_only=False,\n)\n
Export tree to pandas DataFrame.
All descendants from tree
will be exported, tree
can be the root node or child node of tree.
Examples:
>>> from bigtree import Node, tree_to_dataframe\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> tree_to_dataframe(root, name_col=\"name\", parent_col=\"parent\", path_col=\"path\", attr_dict={\"age\": \"person age\"})\n path name parent person age\n0 /a a None 90\n1 /a/b b a 65\n2 /a/b/d d b 40\n3 /a/b/e e b 35\n4 /a/c c a 60\n
For a subset of a tree.
>>> tree_to_dataframe(b, name_col=\"name\", parent_col=\"parent\", path_col=\"path\", attr_dict={\"age\": \"person age\"})\n path name parent person age\n0 /a/b b a 65\n1 /a/b/d d b 40\n2 /a/b/e e b 35\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredpath_col
str
column name for node.path_name
, defaults to 'path'
'path'
name_col
str
column name for node.node_name
, defaults to 'name'
'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 Node
attributes, overrides attr_dict
, defaults to False
False
max_depth
int
maximum depth to export tree, optional
0
skip_depth
int
number of initial depths to skip, optional
0
leaf_only
bool
indicator to retrieve only information from leaf nodes
False
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_dot","title":"tree_to_dot","text":"tree_to_dot(\n tree,\n directed=True,\n rankdir=\"TB\",\n bg_colour=\"\",\n node_colour=\"\",\n node_shape=\"\",\n edge_colour=\"\",\n node_attr=\"\",\n edge_attr=\"\",\n)\n
Export tree or list of trees to image. Possible node attributes include style, fillcolor, shape.
Examples:
>>> from bigtree import Node, tree_to_dot\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> graph = tree_to_dot(root)\n
Display image directly without saving (requires IPython)
>>> from IPython.display import Image, display\n>>> plt = Image(graph.create_png())\n>>> display(plt)\n<IPython.core.display.Image object>\n
Export to image, dot file, etc.
>>> graph.write_png(\"assets/docstr/tree.png\")\n>>> graph.write_dot(\"assets/docstr/tree.dot\")\n
Export to string
>>> graph.to_string()\n'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'\n
Defining node and edge attributes (using node attribute)
>>> class CustomNode(Node):\n... def __init__(self, name, node_shape=\"\", edge_label=\"\", **kwargs):\n... super().__init__(name, **kwargs)\n... self.node_shape = node_shape\n... self.edge_label = edge_label\n...\n... @property\n... def edge_attr(self):\n... if self.edge_label:\n... return {\"label\": self.edge_label}\n... return {}\n...\n... @property\n... def node_attr(self):\n... if self.node_shape:\n... return {\"shape\": self.node_shape}\n... return {}\n>>>\n>>>\n>>> root = CustomNode(\"a\", node_shape=\"circle\")\n>>> b = CustomNode(\"b\", edge_label=\"child\", parent=root)\n>>> c = CustomNode(\"c\", edge_label=\"child\", parent=root)\n>>> d = CustomNode(\"d\", node_shape=\"square\", edge_label=\"child\", parent=b)\n>>> e = CustomNode(\"e\", node_shape=\"square\", edge_label=\"child\", parent=b)\n>>> graph = tree_to_dot(root, node_colour=\"gold\", node_shape=\"diamond\", node_attr=\"node_attr\", edge_attr=\"edge_attr\")\n>>> graph.write_png(\"assets/export_tree_dot.png\")\n
Alternative way to define node and edge attributes (using callable function)
>>> def get_node_attribute(node: Node):\n... if node.is_leaf:\n... return {\"shape\": \"square\"}\n... return {\"shape\": \"circle\"}\n>>>\n>>>\n>>> root = CustomNode(\"a\")\n>>> b = CustomNode(\"b\", parent=root)\n>>> c = CustomNode(\"c\", parent=root)\n>>> d = CustomNode(\"d\", parent=b)\n>>> e = CustomNode(\"e\", parent=b)\n>>> graph = tree_to_dot(root, node_colour=\"gold\", node_attr=get_node_attribute)\n>>> graph.write_png(\"assets/export_tree_dot_callable.png\")\n
Parameters:
Name Type Description Defaulttree
Node / List[Node]
tree or list of trees to be exported
requireddirected
bool
indicator whether graph should be directed or undirected, defaults to True
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)
'TB'
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 Node
attribute 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 Node
attribute 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:
Type DescriptionDot
(pydot.Dot)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_pillow","title":"tree_to_pillow","text":"tree_to_pillow(\n tree,\n width=0,\n height=0,\n start_pos=(10, 10),\n font_family=\"\",\n font_size=12,\n font_colour=\"black\",\n bg_colour=\"white\",\n **kwargs\n)\n
Export tree to image (JPG, PNG). Image will be similar format as print_tree
, accepts additional keyword arguments as input to yield_tree
.
Examples:
>>> from bigtree import Node, tree_to_pillow\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=b)\n>>> e = Node(\"e\", age=35, parent=b)\n>>> pillow_image = tree_to_pillow(root)\n
Export to image (PNG, JPG) file, etc.
>>> pillow_image.save(\"assets/docstr/tree_pillow.png\")\n>>> pillow_image.save(\"assets/docstr/tree_pillow.jpg\")\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredwidth
int
width of image, optional as width of image is calculated automatically
0
height
int
height of image, optional as height of image is calculated automatically
0
start_pos
Tuple[int, int]
start position of text, (x-offset, y-offset), defaults to (10, 10)
(10, 10)
font_family
str
file path of font family, requires .ttf file, defaults to DejaVuSans
''
font_size
int
font size, defaults to 12
12
font_colour
Union[Tuple[int, int, int], str]
font colour, accepts tuple of RGB values or string, defaults to black
'black'
bg_colour
Union[Tuple[int, int, int], str]
background of image, accepts tuple of RGB values or string, defaults to white
'white'
Returns:
Type DescriptionImage
(PIL.Image.Image)
"},{"location":"bigtree/tree/export/#bigtree.tree.export.tree_to_mermaid","title":"tree_to_mermaid","text":"tree_to_mermaid(\n tree,\n title=\"\",\n rankdir=\"TB\",\n line_shape=\"basis\",\n node_colour=\"\",\n node_border_colour=\"\",\n node_border_width=1,\n node_shape=\"rounded_edge\",\n node_shape_attr=\"\",\n edge_arrow=\"normal\",\n edge_arrow_attr=\"\",\n edge_label=\"\",\n node_attr=\"\",\n **kwargs\n)\n
Export tree to mermaid Markdown text. Accepts additional keyword arguments as input to yield_tree
.
title
rankdir
line_shape
node_colour
node_border_colour
node_border_width
node_shape
edge_arrow
node_attr
node_attr
node_attr
node_shape_attr
edge_arrow_attr
edge_label
Accepted Parameter Values
Possible rankdirTB
: top-to-bottomBT
: bottom-to-topLR
: left-to-rightRL
: right-to-leftbasis
bumpX
: used in LR or RL directionbumpY
cardinal
: undirectedcatmullRom
: undirectedlinear
:monotoneX
: used in LR or RL directionmonotoneY
natural
step
: used in LR or RL directionstepAfter
stepBefore
: used in LR or RL directionrounded_edge
: rectangular with rounded edgesstadium
: (_) shape, rectangular with rounded endssubroutine
: ||_|| shape, rectangular with additional line at the endscylindrical
: database nodecircle
: circularasymmetric
: >_| shaperhombus
: decision nodehexagon
: <_> shapeparallelogram
: /_/ shapeparallelogram_alt
: \\_\\ shape, inverted parallelogramtrapezoid
: /_\\ shapetrapezoid_alt
: \\_/ shape, inverted trapezoiddouble_circle
normal
: directed arrow, shaded arrowheadbold
: bold directed arrowdotted
: dotted directed arrowopen
: line, undirected arrowbold_open
: bold linedotted_open
: dotted lineinvisible
: no linecircle
: directed arrow with filled circle arrowheadcross
: directed arrow with cross arrowheaddouble_normal
: bidirectional directed arrowdouble_circle
: bidirectional directed arrow with filled circle arrowheaddouble_cross
: bidirectional directed arrow with cross arrowheadRefer 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.
Examples:
>>> from bigtree import tree_to_mermaid\n>>> root = Node(\"a\", node_shape=\"rhombus\")\n>>> b = Node(\"b\", edge_arrow=\"bold\", edge_label=\"Child 1\", parent=root)\n>>> c = Node(\"c\", edge_arrow=\"dotted\", edge_label=\"Child 2\", parent=root)\n>>> d = Node(\"d\", node_style=\"fill:yellow, stroke:black\", parent=b)\n>>> e = Node(\"e\", parent=b)\n>>> graph = tree_to_mermaid(root)\n>>> print(graph)\n```mermaid\n%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0(\"a\") --> 0-0(\"b\")\n0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0(\"a\") --> 0-1(\"c\")\nclassDef default stroke-width:1\n```\n
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\")\n>>> print(graph)\n```mermaid\n%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0{\"a\"} ==>|Child 1| 0-0(\"b\")\n0-0:::class0-0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0{\"a\"} -.->|Child 2| 0-1(\"c\")\nclassDef default stroke-width:1\nclassDef class0-0-0 fill:yellow, stroke:black\n```\n
Parameters:
Name Type Description Defaulttree
Node
tree to be exported
requiredtitle
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)
'TB'
line_shape
str
line shape or curvature, defaults to 'basis'
'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
1
node_shape
str
node shape, sets the shape of every node, defaults to 'rounded_edge'
'rounded_edge'
node_shape_attr
str | Callable
If string type, it refers to Node
attribute 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 None
''
edge_arrow
str
edge arrow style from parent to itself, sets the arrow style of every edge, defaults to 'normal'
'normal'
edge_arrow_attr
str | Callable
If string type, it refers to Node
attribute 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 None
''
edge_label
str
Node
attribute for edge label from parent to itself, defaults to None
''
node_attr
str | Callable
If string type, it refers to Node
attribute 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:
Type Descriptionstr
(str)
"},{"location":"bigtree/tree/helper/","title":"\ud83d\udd27 Helper","text":"Helper functions that can come in handy.
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper","title":"bigtree.tree.helper","text":""},{"location":"bigtree/tree/helper/#bigtree.tree.helper.clone_tree","title":"clone_tree","text":"clone_tree(tree, node_type)\n
Clone tree to another Node
type. If the same type is needed, simply do a tree.copy().
Examples:
>>> from bigtree import BaseNode, Node, clone_tree\n>>> root = BaseNode(name=\"a\")\n>>> b = BaseNode(name=\"b\", parent=root)\n>>> clone_tree(root, Node)\nNode(/a, )\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to be cloned, must inherit from BaseNode
requirednode_type
Type[BaseNode]
type of cloned tree
requiredReturns:
Type DescriptionBaseNodeT
(BaseNode)
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.get_subtree","title":"get_subtree","text":"get_subtree(tree, node_name_or_path='', max_depth=0)\n
Get subtree based on node name or node path, and/or maximum depth of tree.
Examples:
>>> from bigtree import Node, get_subtree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=root)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 c\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Get subtree
>>> root_subtree = get_subtree(root, \"b\")\n>>> root_subtree.show()\nb\n\u251c\u2500\u2500 c\n\u2514\u2500\u2500 d\n
Parameters:
Name Type Description Defaulttree
Node
existing tree
requirednode_name_or_path
str
node name or path to get subtree, defaults to None
''
max_depth
int
maximum depth of subtree, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.prune_tree","title":"prune_tree","text":"prune_tree(\n tree, prune_path=\"\", exact=False, sep=\"/\", max_depth=0\n)\n
Prune tree by path or depth, returns the root of a copy of the original tree.
For pruning by prune_path
,
exact=True
, all descendants of prune path will be removed.For pruning by max_depth
,
max_depth
will be removed.Path should contain Node
name, separated by sep
.
Examples:
>>> from bigtree import Node, prune_tree\n>>> root = Node(\"a\")\n>>> b = Node(\"b\", parent=root)\n>>> c = Node(\"c\", parent=b)\n>>> d = Node(\"d\", parent=b)\n>>> e = Node(\"e\", parent=root)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 c\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Prune (default is keep descendants)
>>> root_pruned = prune_tree(root, \"a/b\")\n>>> root_pruned.show()\na\n\u2514\u2500\u2500 b\n \u251c\u2500\u2500 c\n \u2514\u2500\u2500 d\n
Prune exact path
>>> root_pruned = prune_tree(root, \"a/b\", exact=True)\n>>> root_pruned.show()\na\n\u2514\u2500\u2500 b\n
Prune multiple paths
>>> root_pruned = prune_tree(root, [\"a/b/d\", \"a/e\"])\n>>> root_pruned.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 e\n
Prune by depth
>>> root_pruned = prune_tree(root, max_depth=2)\n>>> root_pruned.show()\na\n\u251c\u2500\u2500 b\n\u2514\u2500\u2500 e\n
Parameters:
Name Type Description Defaulttree
Union[BinaryNode, Node]
existing tree
requiredprune_path
List[str] | str
prune path(s), all siblings along the prune path(s) will be removed
''
exact
bool
prune path(s) to be exactly the path, defaults to False (descendants of the path are retained)
False
sep
str
path separator of prune_path
'/'
max_depth
int
maximum depth of pruned tree, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionUnion[BinaryNodeT, NodeT]
(Union[BinaryNode, Node])
"},{"location":"bigtree/tree/helper/#bigtree.tree.helper.get_tree_diff","title":"get_tree_diff","text":"get_tree_diff(\n tree, other_tree, only_diff=True, attr_list=[]\n)\n
Get difference of tree
to other_tree
, changes are relative to tree
.
Compares the difference in tree structure (default), but can also compare tree attributes using attr_list
. Function can return only the differences (default), or all original tree nodes and differences.
Comparing tree structure:
tree
.other_tree
but not tree
.tree
but not other_tree
.Examples:
>>> # Create original tree\n>>> from bigtree import Node, get_tree_diff, list_to_tree\n>>> root = list_to_tree([\"Downloads/Pictures/photo1.jpg\", \"Downloads/file1.doc\", \"Downloads/photo2.jpg\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 photo2.jpg\n
>>> # Create other tree\n>>> root_other = list_to_tree([\"Downloads/Pictures/photo1.jpg\", \"Downloads/Pictures/photo2.jpg\", \"Downloads/file1.doc\"])\n>>> root_other.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> # Get tree differences\n>>> tree_diff = get_tree_diff(root, root_other)\n>>> tree_diff.show()\nDownloads\n\u251c\u2500\u2500 photo2.jpg (-)\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg (+)\n
>>> tree_diff = get_tree_diff(root, root_other, only_diff=False)\n>>> tree_diff.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg (+)\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 photo2.jpg (-)\n
Comparing tree attributes
attr_list
.tree
, value in other_tree
]>>> # Create original tree\n>>> root = Node(\"Downloads\")\n>>> picture_folder = Node(\"Pictures\", parent=root)\n>>> photo2 = Node(\"photo1.jpg\", tags=\"photo1\", parent=picture_folder)\n>>> file1 = Node(\"file1.doc\", tags=\"file1\", parent=root)\n>>> root.show(attr_list=[\"tags\"])\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg [tags=photo1]\n\u2514\u2500\u2500 file1.doc [tags=file1]\n
>>> # Create other tree\n>>> root_other = Node(\"Downloads\")\n>>> picture_folder = Node(\"Pictures\", parent=root_other)\n>>> photo1 = Node(\"photo1.jpg\", tags=\"photo1-edited\", parent=picture_folder)\n>>> photo2 = Node(\"photo2.jpg\", tags=\"photo2-new\", parent=picture_folder)\n>>> file1 = Node(\"file1.doc\", tags=\"file1\", parent=root_other)\n>>> root_other.show(attr_list=[\"tags\"])\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg [tags=photo1-edited]\n\u2502 \u2514\u2500\u2500 photo2.jpg [tags=photo2-new]\n\u2514\u2500\u2500 file1.doc [tags=file1]\n
>>> # Get tree differences\n>>> tree_diff = get_tree_diff(root, root_other, attr_list=[\"tags\"])\n>>> tree_diff.show(attr_list=[\"tags\"])\nDownloads\n\u2514\u2500\u2500 Pictures\n \u251c\u2500\u2500 photo1.jpg (~) [tags=('photo1', 'photo1-edited')]\n \u2514\u2500\u2500 photo2.jpg (+)\n
Parameters:
Name Type Description Defaulttree
Node
tree to be compared against
requiredother_tree
Node
tree to be compared with
requiredonly_diff
bool
indicator to show all nodes or only nodes that are different (+/-), defaults to True
True
attr_list
List[str]
tree attributes to check for difference, defaults to empty list
[]
Returns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/tree/modify/","title":"\ud83d\udcdd Modify","text":"There are two types of modification available
from_paths
(list of paths) and to_paths
(list of paths).from_paths
(list of paths) and to_paths
(list of paths).In non-replacing scenario, there are several configurations available for customization.
Configuration Description Default Valuecopy
Indicates whether it is to shift the nodes, or copy the nodes False (nodes are shifted, not copied) to_tree
Indicates whether shifting/copying is within the same tree, or between different trees None (nodes are shifted/copied within the same tree) skippable
Skip shifting/copying of nodes if from_path cannot be found False (from-node must be found) overriding
Override existing node if it exists False (to-node must not exist) merge_children
Shift/copy children of from-node and remove intermediate parent node False (children are not merged) merge_leaves
Shift/copy leaves of from-node and remove all intermediate nodes False (leaves are not merged) delete_children
Shift/copy node only and delete its children False (nodes are shifted/copied together with children) In replacing scenario, all the configurations are also available except overriding
, merge_children
, and merge_leaves
as it is doing a one-to-one replacement. It is by default overriding, and there is nothing to merge.
Note
merge_children
and merge_leaves
cannot be simultaneously set to True
.
Note
Error will always be thrown if multiple from-nodes are found, paths in from_paths
must be unique.
There are several ways you can mix and match the tree modification methods. If you know all the parameters to choose, feel free to use copy_or_shift_logic
or replace_logic
methods as they are the most customizable. All other methods calls these 2 methods directly.
shift_nodes
Copy Same tree No copy_nodes
Copy Between two trees No copy_nodes_from_tree_to_tree
Any Any No copy_or_shift_logic
Shift Same tree Yes shift_and_replace_nodes
Copy Between two trees Yes copy_and_replace_nodes_from_tree_to_tree
Any Any Yes replace_logic
"},{"location":"bigtree/tree/modify/#tree-modification-illustration","title":"Tree Modification Illustration","text":""},{"location":"bigtree/tree/modify/#sample-tree-modification-shift-copy-delete","title":"Sample Tree Modification (Shift, Copy, Delete)","text":"Setting Sample path in from_paths
Sample path in to_paths
Description Default \"/a/c\" \"/a/b/c\" Shift/copy node c
Default \"/c\" \"/a/b/c\" Shift/copy node c
Default \"c\" \"/a/b/c\" Shift/copy node c
Default \"/a/e\" None Delete node e
skippable \"/a/c\" \"/a/b/c\" Shift/copy node c
, skip if \"/a/c\" cannot be found"},{"location":"bigtree/tree/modify/#sample-tree-modification-advanced","title":"Sample Tree Modification (Advanced)","text":"Setting Sample path in from_paths
Sample path in to_paths
Description overriding \"a/b/c\" \"a/d/c\" Shift/copy node c
, override if \"a/d/c\" exists merge_children \"a/b/c\" \"a/d/c\" If path not present: Shift/copy children of node c
to be children of node d
, removing node c
If path present: Shift/copy children of node c
to be merged with existing \"a/d/c\" children merge_children + overriding \"a/b/c\" \"a/d/c\" If path not present: Behaves like merge_childrenIf path present: Behaves like overriding merge_leaves \"a/b/c\" \"a/d/c\" If path not present: Shift/copy leaves of node c
to be children of node d
If path present: Shift/copy leaves of node c
to be merged with existing \"a/d/c\" children - merge_leaves + overriding \"a/b/c\" \"a/d/c\" If path not present: Behaves like merge_leavesIf path present: Behaves like overriding, but original node c
remains delete_children \"a/b\" \"a/d/b\" Shift/copy node b
only without any node b
children"},{"location":"bigtree/tree/modify/#bigtree.tree.modify","title":"bigtree.tree.modify","text":""},{"location":"bigtree/tree/modify/#bigtree.tree.modify.shift_nodes","title":"shift_nodes","text":"shift_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Shift nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
from_paths
, note that copy
must be set to False.If merge_children=True
,
to_path
is not present, it shifts children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it shifts leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained, original non-leaf nodes in from_path
are retained.Examples:
>>> from bigtree import list_to_tree, str_to_tree, shift_nodes\n>>> root = list_to_tree([\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... tree=root,\n... from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n... to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
To delete node,
>>> root = list_to_tree([\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(root, [\"Downloads/photo1.jpg\"], [None])\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 file1.doc\n
In overriding case,
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg\n
>>> shift_nodes(root, [\"Downloads/Misc/Pictures\"], [\"Downloads/Pictures\"], overriding=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In merge_children=True
case, child nodes are shifted instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_children=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> shift_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_leaves=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 Applications\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 dummy\n\u2502 \u2514\u2500\u2500 Files\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 file1.doc\n
In delete_children=True
case, only the node is shifted without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo1.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
>>> shift_nodes(root, [\"Applications\"], [\"Downloads/Applications\"], delete_children=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Applications\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to shift node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_nodes","title":"copy_nodes","text":"copy_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
If merge_children=True
,
to_path
is not present, it copies children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.Examples:
>>> from bigtree import list_to_tree, str_to_tree, copy_nodes\n>>> root = list_to_tree([\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"])\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u251c\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... tree=root,\n... from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n... to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 photo1.jpg\n\u251c\u2500\u2500 file1.doc\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In overriding case,
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo2.jpg\n
>>> copy_nodes(root, [\"Downloads/Misc/Pictures\"], [\"Downloads/Pictures\"], overriding=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In merge_children=True
case, child nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_children=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 Files\\n\"\n... \" \u2514\u2500\u2500 file1.doc\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 Files\n \u2514\u2500\u2500 file1.doc\n
>>> copy_nodes(\n... root,\n... [\"Downloads/Misc/Pictures\", \"Applications\", \"Downloads/dummy\"],\n... [\"Downloads/Pictures\", \"Downloads/Applications\", \"Downloads/dummy\"],\n... merge_leaves=True,\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u251c\u2500\u2500 Pictures\n\u2502 \u2502 \u2514\u2500\u2500 photo2.jpg\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo1.jpg\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u251c\u2500\u2500 dummy\n\u2502 \u2514\u2500\u2500 Files\n\u2502 \u2514\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 file1.doc\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Misc\\n\"\n... \"\u2502 \u2514\u2500\u2500 Applications\\n\"\n... \"\u2502 \u2514\u2500\u2500 Chrome.exe\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo1.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
>>> copy_nodes(root, [\"Applications\"], [\"Downloads/Applications\"], delete_children=True)\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Misc\n\u2502 \u2514\u2500\u2500 Applications\n\u2502 \u2514\u2500\u2500 Chrome.exe\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Applications\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.shift_and_replace_nodes","title":"shift_and_replace_nodes","text":"shift_and_replace_nodes(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n delete_children=False,\n with_full_path=False,\n)\n
Shift nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Examples:
>>> from bigtree import str_to_tree, shift_and_replace_nodes\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n
>>> shift_and_replace_nodes(root, [\"Downloads/Pictures\"], [\"Downloads/Misc/dummy\"])\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo1.jpg\n
In delete_children=True
case, only the node is shifted without its accompanying children/descendants.
>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n
>>> shift_and_replace_nodes(root, [\"Downloads/Pictures\"], [\"Downloads/Misc/dummy\"], delete_children=True)\n>>> root.show()\nDownloads\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 Pictures\n
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to shift node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_nodes_from_tree_to_tree","title":"copy_nodes_from_tree_to_tree","text":"copy_nodes_from_tree_to_tree(\n from_tree,\n to_tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
If merge_children=True
,
to_path
is not present, it copies children of from_path
to_path
is present, and overriding=False
, original and new children are mergedto_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.If merge_leaves=True
,
to_path
is not present, it copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained.Examples:
>>> from bigtree import Node, str_to_tree, copy_nodes_from_tree_to_tree\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 file1.doc\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
>>> root_other = Node(\"Documents\")\n>>> copy_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures\", \"Documents/New Misc/Misc\"],\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 New Misc\n \u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In overriding case,
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... overriding=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In merge_children=True
case, child nodes are copied instead of the parent node.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... merge_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo3.jpg\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In merge_leaves=True
case, leaf nodes are copied instead of the parent node.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u2514\u2500\u2500 Pictures\\n\"\n... \" \u2514\u2500\u2500 photo3.jpg\"\n... )\n>>> root_other.show()\nDocuments\n\u2514\u2500\u2500 Pictures\n \u2514\u2500\u2500 photo3.jpg\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... merge_leaves=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2502 \u251c\u2500\u2500 photo3.jpg\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 photo2.jpg\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root_other = Node(\"Documents\")\n>>> root_other.show()\nDocuments\n
>>> copy_nodes_from_tree_to_tree(\n... root,\n... root_other,\n... [\"Downloads/Pictures\", \"Downloads/Misc\"],\n... [\"Documents/Pictures\", \"Documents/Misc\"],\n... delete_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures\n\u2514\u2500\u2500 Misc\n
Parameters:
Name Type Description Defaultfrom_tree
Node
tree to copy nodes from
requiredto_tree
Node
tree to copy nodes to
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_and_replace_nodes_from_tree_to_tree","title":"copy_and_replace_nodes_from_tree_to_tree","text":"copy_and_replace_nodes_from_tree_to_tree(\n from_tree,\n to_tree,\n from_paths,\n to_paths,\n sep=\"/\",\n skippable=False,\n delete_children=False,\n with_full_path=False,\n)\n
Copy nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Examples:
>>> from bigtree import str_to_tree, copy_and_replace_nodes_from_tree_to_tree\n>>> root = str_to_tree(\n... \"Downloads\\n\"\n... \"\u251c\u2500\u2500 file1.doc\\n\"\n... \"\u251c\u2500\u2500 Pictures\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo1.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc\\n\"\n... \" \u2514\u2500\u2500 dummy\\n\"\n... \" \u2514\u2500\u2500 photo2.jpg\"\n... )\n>>> root.show()\nDownloads\n\u251c\u2500\u2500 file1.doc\n\u251c\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u251c\u2500\u2500 Pictures2\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc2\"\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 Misc2\n
>>> copy_and_replace_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures2/photo2.jpg\", \"Documents/Misc2\"],\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 Pictures\n\u2502 \u2514\u2500\u2500 photo1.jpg\n\u2514\u2500\u2500 Misc\n \u2514\u2500\u2500 dummy\n \u2514\u2500\u2500 photo2.jpg\n
In delete_children=True
case, only the node is copied without its accompanying children/descendants.
>>> root_other = str_to_tree(\n... \"Documents\\n\"\n... \"\u251c\u2500\u2500 Pictures2\\n\"\n... \"\u2502 \u2514\u2500\u2500 photo2.jpg\\n\"\n... \"\u2514\u2500\u2500 Misc2\"\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 photo2.jpg\n\u2514\u2500\u2500 Misc2\n
>>> copy_and_replace_nodes_from_tree_to_tree(\n... from_tree=root,\n... to_tree=root_other,\n... from_paths=[\"Downloads/Pictures\", \"Downloads/Misc\"],\n... to_paths=[\"Documents/Pictures2/photo2.jpg\", \"Documents/Misc2\"],\n... delete_children=True,\n... )\n>>> root_other.show()\nDocuments\n\u251c\u2500\u2500 Pictures2\n\u2502 \u2514\u2500\u2500 Pictures\n\u2514\u2500\u2500 Misc\n
Parameters:
Name Type Description Defaultfrom_tree
Node
tree to copy nodes from
requiredto_tree
Node
tree to copy nodes to
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to copy node only without children, defaults to False
False
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.copy_or_shift_logic","title":"copy_or_shift_logic","text":"copy_or_shift_logic(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n copy=False,\n skippable=False,\n overriding=False,\n merge_children=False,\n merge_leaves=False,\n delete_children=False,\n to_tree=None,\n with_full_path=False,\n)\n
Shift or copy nodes from from_paths
to to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
from_paths
, note that copy
must be set to False.If merge_children=True
,
to_path
is not present, it shifts/copies children of from_path
.to_path
is present, and overriding=False
, original and new children are merged.to_path
is present and overriding=True
, it behaves like overriding and only new children are retained.If merge_leaves=True
,
to_path
is not present, it shifts/copies leaves of from_path
.to_path
is present, and overriding=False
, original children and leaves are merged.to_path
is present and overriding=True
, it behaves like overriding and only new leaves are retained, original non-leaf nodes in from_path
are retained.Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
copy
bool
indicator to copy node, defaults to False
False
skippable
bool
indicator to skip if from path is not found, defaults to False
False
overriding
bool
indicator to override existing to path if there is clashes, defaults to False
False
merge_children
bool
indicator to merge children and remove intermediate parent node, defaults to False
False
merge_leaves
bool
indicator to merge leaf nodes and remove intermediate parent node(s), defaults to False
False
delete_children
bool
indicator to shift/copy node only without children, defaults to False
False
to_tree
Node
tree to copy to, defaults to None
None
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/modify/#bigtree.tree.modify.replace_logic","title":"replace_logic","text":"replace_logic(\n tree,\n from_paths,\n to_paths,\n sep=\"/\",\n copy=False,\n skippable=False,\n delete_children=False,\n to_tree=None,\n with_full_path=False,\n)\n
Shift or copy nodes from from_paths
to replace to_paths
in-place.
For paths in from_paths
and to_paths
,
For paths in from_paths
,
with_full_path=True
, path name must be full path.For paths in to_paths
,
Parameters:
Name Type Description Defaulttree
Node
tree to modify
requiredfrom_paths
List[str]
original paths to shift nodes from
requiredto_paths
List[str]
new paths to shift nodes to
requiredsep
str
path separator for input paths, applies to from_path
and to_path
'/'
copy
bool
indicator to copy node, defaults to False
False
skippable
bool
indicator to skip if from path is not found, defaults to False
False
delete_children
bool
indicator to shift/copy node only without children, defaults to False
False
to_tree
Node
tree to copy to, defaults to None
None
with_full_path
bool
indicator to shift/copy node with full path in from_paths
, results in faster search, defaults to False
False
"},{"location":"bigtree/tree/search/","title":"\ud83d\udd0d Search","text":"Search methods for Trees.
Search by One node One or more nodes General methodfind
, find_child
findall
, find_children
Node name find_name
, find_child_by_name
find_names
Node path find_path
, find_full_path
, find_relative_path
find_paths
, find_relative_path
Node attributes find_attr
find_attrs
"},{"location":"bigtree/tree/search/#bigtree.tree.search","title":"bigtree.tree.search","text":""},{"location":"bigtree/tree/search/#bigtree.tree.search.findall","title":"findall","text":"findall(\n tree, condition, max_depth=0, min_count=0, max_count=0\n)\n
Search tree for nodes matching condition (callable function).
Examples:
>>> from bigtree import Node, findall\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> findall(root, lambda node: node.age > 62)\n(Node(/a, age=90), Node(/a/b, age=65))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
max_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
min_count
int
checks for minimum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
max_count
int
checks for maximum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
Returns:
Type DescriptionTuple[T, ...]
(Tuple[BaseNode, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find","title":"find","text":"find(tree, condition, max_depth=0)\n
Search tree for single node matching condition (callable function).
Examples:
>>> from bigtree import Node, find\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find(root, lambda node: node.age == 65)\nNode(/a/b, age=65)\n>>> find(root, lambda node: node.age > 5)\nTraceback (most recent call last):\n ...\nbigtree.utils.exceptions.SearchError: Expected less than 1 element(s), found 4 elements\n(Node(/a, age=90), Node(/a/b, age=65), Node(/a/c, age=60), Node(/a/c/d, age=40))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
max_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionT
(BaseNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_name","title":"find_name","text":"find_name(tree, name, max_depth=0)\n
Search tree for single node matching name attribute.
Examples:
>>> from bigtree import Node, find_name\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_name(root, \"c\")\nNode(/a/c, age=60)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredname
str
value to match for name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_names","title":"find_names","text":"find_names(tree, name, max_depth=0)\n
Search tree for multiple node(s) matching name attribute.
Examples:
>>> from bigtree import Node, find_names\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"b\", age=40, parent=c)\n>>> find_names(root, \"c\")\n(Node(/a/c, age=60),)\n>>> find_names(root, \"b\")\n(Node(/a/b, age=65), Node(/a/c/b, age=40))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredname
str
value to match for name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[NodeT]
(Iterable[Node])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_relative_path","title":"find_relative_path","text":"find_relative_path(tree, path_name)\n
Search tree for single node matching relative path attribute.
Examples:
>>> from bigtree import Node, find_relative_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_relative_path(d, \"..\")\n(Node(/a/c, age=60),)\n>>> find_relative_path(d, \"../../b\")\n(Node(/a/b, age=65),)\n>>> find_relative_path(d, \"../../*\")\n(Node(/a/b, age=65), Node(/a/c, age=60))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (relative path) of path_name attribute
requiredReturns:
Type DescriptionIterable[NodeT]
(Iterable[Node])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_full_path","title":"find_full_path","text":"find_full_path(tree, path_name)\n
Search tree for single node matching path attribute.
find_path
but faster.Examples:
>>> from bigtree import Node, find_full_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_full_path(root, \"/a/c/d\")\nNode(/a/c/d, age=40)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) of path_name attribute
requiredReturns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_path","title":"find_path","text":"find_path(tree, path_name)\n
Search tree for single node matching path attribute.
Examples:
>>> from bigtree import Node, find_path\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_path(root, \"c\")\nNode(/a/c, age=60)\n>>> find_path(root, \"/c\")\nNode(/a/c, age=60)\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) or trailing part (partial path) of path_name attribute
requiredReturns:
Type DescriptionNodeT
(Node)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_paths","title":"find_paths","text":"find_paths(tree, path_name)\n
Search tree for multiple nodes matching path attribute.
Examples:
>>> from bigtree import Node, find_paths\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"c\", age=40, parent=c)\n>>> find_paths(root, \"/a/c\")\n(Node(/a/c, age=60),)\n>>> find_paths(root, \"/c\")\n(Node(/a/c, age=60), Node(/a/c/c, age=40))\n
Parameters:
Name Type Description Defaulttree
Node
tree to search
requiredpath_name
str
value to match (full path) or trailing part (partial path) of path_name attribute
requiredReturns:
Type DescriptionTuple[NodeT, ...]
(Tuple[Node, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_attr","title":"find_attr","text":"find_attr(tree, attr_name, attr_value, max_depth=0)\n
Search tree for single node matching custom attribute.
Examples:
>>> from bigtree import Node, find_attr\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_attr(root, \"age\", 65)\nNode(/a/b, age=65)\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredattr_name
str
attribute name to perform matching
requiredattr_value
Any
value to match for attr_name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionBaseNode
(BaseNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_attrs","title":"find_attrs","text":"find_attrs(tree, attr_name, attr_value, max_depth=0)\n
Search tree for node(s) matching custom attribute.
Examples:
>>> from bigtree import Node, find_attrs\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=65, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_attrs(root, \"age\", 65)\n(Node(/a/b, age=65), Node(/a/c, age=65))\n
Parameters:
Name Type Description Defaulttree
BaseNode
tree to search
requiredattr_name
str
attribute name to perform matching
requiredattr_value
Any
value to match for attr_name attribute
requiredmax_depth
int
maximum depth to search for, based on the depth
attribute, defaults to None
0
Returns:
Type DescriptionTuple[BaseNode, ...]
(Tuple[BaseNode, ...])
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_children","title":"find_children","text":"find_children(tree, condition, min_count=0, max_count=0)\n
Search children for nodes matching condition (callable function).
Examples:
>>> from bigtree import Node, find_children\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_children(root, lambda node: node.age > 30)\n(Node(/a/b, age=65), Node(/a/c, age=60))\n
Parameters:
Name Type Description Defaulttree
BaseNode / DAGNode
tree to search for its children
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
min_count
int
checks for minimum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
max_count
int
checks for maximum number of occurrences, raise SearchError if the number of results do not meet min_count, defaults to None
0
Returns:
Type DescriptionTuple[Union[T, DAGNodeT], ...]
(BaseNode/DAGNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_child","title":"find_child","text":"find_child(tree, condition)\n
Search children for single node matching condition (callable function).
Examples:
>>> from bigtree import Node, find_child\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_child(root, lambda node: node.age > 62)\nNode(/a/b, age=65)\n
Parameters:
Name Type Description Defaulttree
BaseNode / DAGNode
tree to search for its child
requiredcondition
Callable
function that takes in node as argument, returns node if condition evaluates to True
Returns:
Type DescriptionUnion[T, DAGNodeT]
(BaseNode/DAGNode)
"},{"location":"bigtree/tree/search/#bigtree.tree.search.find_child_by_name","title":"find_child_by_name","text":"find_child_by_name(tree, name)\n
Search tree for single node matching name attribute.
Examples:
>>> from bigtree import Node, find_child_by_name\n>>> root = Node(\"a\", age=90)\n>>> b = Node(\"b\", age=65, parent=root)\n>>> c = Node(\"c\", age=60, parent=root)\n>>> d = Node(\"d\", age=40, parent=c)\n>>> find_child_by_name(root, \"c\")\nNode(/a/c, age=60)\n>>> find_child_by_name(c, \"d\")\nNode(/a/c/d, age=40)\n
Parameters:
Name Type Description Defaulttree
Node / DAGNode
tree to search, parent node
requiredname
str
value to match for name attribute, child node
requiredReturns:
Type DescriptionUnion[NodeT, DAGNodeT]
(Node/DAGNode)
"},{"location":"bigtree/utils/","title":"\ud83d\udd27 Utils","text":""},{"location":"bigtree/utils/iterators/","title":"\u27b0 Iterators","text":"Iterator methods for Trees and DAGs.
"},{"location":"bigtree/utils/iterators/#iterator-methods","title":"Iterator Methods","text":"Data Structure Algorithm Description Binary Tree In-order Traversal Depth-First Search, LNR Tree Pre-order Traversal Depth-First Search, NLR Tree Post-Order Traversal Depth-First Search, LRN Tree Level-Order Traversal Breadth-First Search Tree ZigZag Traversal Breadth-First Search Tree ZigZag Group Traversal Breadth-First Search DAG General Depth-First Search"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators","title":"bigtree.utils.iterators","text":""},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.inorder_iter","title":"inorder_iter","text":"inorder_iter(tree, filter_condition=None, max_depth=0)\n
Iterate through all children of a tree.
In-Order Iteration Algorithm, LNR 1. Recursively traverse the current node's left subtree. 2. Visit the current node. 3. Recursively traverse the current node's right subtree.
Examples:
>>> from bigtree import BinaryNode, list_to_binarytree, inorder_iter\n>>> num_list = [1, 2, 3, 4, 5, 6, 7, 8]\n>>> root = list_to_binarytree(num_list)\n>>> root.show()\n1\n\u251c\u2500\u2500 2\n\u2502 \u251c\u2500\u2500 4\n\u2502 \u2502 \u2514\u2500\u2500 8\n\u2502 \u2514\u2500\u2500 5\n\u2514\u2500\u2500 3\n \u251c\u2500\u2500 6\n \u2514\u2500\u2500 7\n
>>> [node.node_name for node in inorder_iter(root)]\n['8', '4', '2', '5', '1', '6', '3', '7']\n
>>> [node.node_name for node in inorder_iter(root, filter_condition=lambda x: x.node_name in [\"1\", \"4\", \"3\", \"6\", \"7\"])]\n['4', '1', '6', '3', '7']\n
>>> [node.node_name for node in inorder_iter(root, max_depth=3)]\n['4', '2', '5', '1', '6', '3', '7']\n
Parameters:
Name Type Description Defaulttree
BinaryNode
input tree
requiredfilter_condition
Optional[Callable[[BinaryNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[BinaryNodeT]
(Iterable[BinaryNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.preorder_iter","title":"preorder_iter","text":"preorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Pre-Order Iteration Algorithm, NLR 1. Visit the current node. 2. Recursively traverse the current node's left subtree. 3. Recursively traverse the current node's right subtree.
It is topologically sorted because a parent node is processed before its child nodes.
Examples:
>>> from bigtree import Node, list_to_tree, preorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in preorder_iter(root)]\n['a', 'b', 'd', 'e', 'g', 'h', 'c', 'f']\n
>>> [node.node_name for node in preorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'g', 'f']\n
>>> [node.node_name for node in preorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'b', 'd', 'c', 'f']\n
>>> [node.node_name for node in preorder_iter(root, max_depth=3)]\n['a', 'b', 'd', 'e', 'c', 'f']\n
Parameters:
Name Type Description Defaulttree
Union[BaseNode, DAGNode]
input tree
requiredfilter_condition
Optional[Callable[[T], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[T], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[T]
(Union[Iterable[BaseNode], Iterable[DAGNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.postorder_iter","title":"postorder_iter","text":"postorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Post-Order Iteration Algorithm, LRN 1. Recursively traverse the current node's left subtree. 2. Recursively traverse the current node's right subtree. 3. Visit the current node.
Examples:
>>> from bigtree import Node, list_to_tree, postorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in postorder_iter(root)]\n['d', 'g', 'h', 'e', 'b', 'f', 'c', 'a']\n
>>> [node.node_name for node in postorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['d', 'g', 'e', 'f', 'a']\n
>>> [node.node_name for node in postorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['d', 'b', 'f', 'c', 'a']\n
>>> [node.node_name for node in postorder_iter(root, max_depth=3)]\n['d', 'e', 'b', 'f', 'c', 'a']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, optional
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.levelorder_iter","title":"levelorder_iter","text":"levelorder_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Level-Order Iteration Algorithm 1. Recursively traverse the nodes on same level.
Examples:
>>> from bigtree import Node, list_to_tree, levelorder_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in levelorder_iter(root)]\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n
>>> [node.node_name for node in levelorder_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'f', 'g']\n
>>> [node.node_name for node in levelorder_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'b', 'c', 'd', 'f']\n
>>> [node.node_name for node in levelorder_iter(root, max_depth=3)]\n['a', 'b', 'c', 'd', 'e', 'f']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.levelordergroup_iter","title":"levelordergroup_iter","text":"levelordergroup_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
Level-Order Group Iteration Algorithm 1. Recursively traverse the nodes on same level, returns nodes level by level in a nested list.
Examples:
>>> from bigtree import Node, list_to_tree, levelordergroup_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root)]\n[['a'], ['b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n[['a'], [], ['d', 'e', 'f'], ['g']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n[['a'], ['b', 'c'], ['d', 'f']]\n
>>> [[node.node_name for node in group] for group in levelordergroup_iter(root, max_depth=3)]\n[['a'], ['b', 'c'], ['d', 'e', 'f']]\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[Iterable[BaseNodeT]]
(Iterable[Iterable[BaseNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.zigzag_iter","title":"zigzag_iter","text":"zigzag_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
ZigZag Iteration Algorithm 1. Recursively traverse the nodes on same level, in a zigzag manner across different levels.
Examples:
>>> from bigtree import Node, list_to_tree, zigzag_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [node.node_name for node in zigzag_iter(root)]\n['a', 'c', 'b', 'd', 'e', 'f', 'h', 'g']\n
>>> [node.node_name for node in zigzag_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n['a', 'd', 'e', 'f', 'g']\n
>>> [node.node_name for node in zigzag_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n['a', 'c', 'b', 'd', 'f']\n
>>> [node.node_name for node in zigzag_iter(root, max_depth=3)]\n['a', 'c', 'b', 'd', 'e', 'f']\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[BaseNodeT]
(Iterable[BaseNode])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.zigzaggroup_iter","title":"zigzaggroup_iter","text":"zigzaggroup_iter(\n tree,\n filter_condition=None,\n stop_condition=None,\n max_depth=0,\n)\n
Iterate through all children of a tree.
ZigZag Group Iteration Algorithm 1. Recursively traverse the nodes on same level, in a zigzag manner across different levels, returns nodes level by level in a nested list.
Examples:
>>> from bigtree import Node, list_to_tree, zigzaggroup_iter\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root)]\n[['a'], ['c', 'b'], ['d', 'e', 'f'], ['h', 'g']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, filter_condition=lambda x: x.node_name in [\"a\", \"d\", \"e\", \"f\", \"g\"])]\n[['a'], [], ['d', 'e', 'f'], ['g']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, stop_condition=lambda x: x.node_name == \"e\")]\n[['a'], ['c', 'b'], ['d', 'f']]\n
>>> [[node.node_name for node in group] for group in zigzaggroup_iter(root, max_depth=3)]\n[['a'], ['c', 'b'], ['d', 'e', 'f']]\n
Parameters:
Name Type Description Defaulttree
BaseNode
input tree
requiredfilter_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Return node if condition evaluates to True
None
stop_condition
Optional[Callable[[BaseNode], bool]]
function that takes in node as argument, optional Stops iteration if condition evaluates to True
None
max_depth
int
maximum depth of iteration, based on depth
attribute, defaults to None
0
Returns:
Type DescriptionIterable[Iterable[BaseNodeT]]
(Iterable[Iterable[BaseNode]])
"},{"location":"bigtree/utils/iterators/#bigtree.utils.iterators.dag_iterator","title":"dag_iterator","text":"dag_iterator(dag)\n
Iterate through all nodes of a Directed Acyclic Graph (DAG). Note that node names must be unique. Note that DAG must at least have two nodes to be shown on graph.
Examples:
>>> from bigtree import DAGNode, dag_iterator\n>>> a = DAGNode(\"a\", step=1)\n>>> b = DAGNode(\"b\", step=1)\n>>> c = DAGNode(\"c\", step=2, parents=[a, b])\n>>> d = DAGNode(\"d\", step=2, parents=[a, c])\n>>> e = DAGNode(\"e\", step=3, parents=[d])\n>>> [(parent.node_name, child.node_name) for parent, child in dag_iterator(a)]\n[('a', 'c'), ('a', 'd'), ('b', 'c'), ('c', 'd'), ('d', 'e')]\n
Parameters:
Name Type Description Defaultdag
DAGNode
input dag
requiredReturns:
Type DescriptionIterable[Tuple[DAGNodeT, DAGNodeT]]
(Iterable[Tuple[DAGNode, DAGNode]])
"},{"location":"bigtree/utils/plot/","title":"\ud83d\udcca Plot","text":"Plotting methods for Trees.
"},{"location":"bigtree/utils/plot/#bigtree.utils.plot","title":"bigtree.utils.plot","text":""},{"location":"bigtree/utils/plot/#bigtree.utils.plot.reingold_tilford","title":"reingold_tilford","text":"reingold_tilford(\n tree_node,\n sibling_separation=1.0,\n subtree_separation=1.0,\n level_separation=1.0,\n x_offset=0.0,\n y_offset=0.0,\n)\n
Algorithm for drawing tree structure, retrieves (x, y)
coordinates for a tree structure. Adds x
and y
attributes to every node in the tree. Modifies tree in-place.
This algorithm[1] is an improvement over Reingold Tilford algorithm[2].
According to Reingold Tilford's paper, a tree diagram should satisfy the following aesthetic rules,
Examples:
>>> from bigtree import reingold_tilford, list_to_tree\n>>> path_list = [\"a/b/d\", \"a/b/e/g\", \"a/b/e/h\", \"a/c/f\"]\n>>> root = list_to_tree(path_list)\n>>> root.show()\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n
>>> reingold_tilford(root)\n>>> root.show(attr_list=[\"x\", \"y\"])\na [x=1.25, y=3.0]\n\u251c\u2500\u2500 b [x=0.5, y=2.0]\n\u2502 \u251c\u2500\u2500 d [x=0.0, y=1.0]\n\u2502 \u2514\u2500\u2500 e [x=1.0, y=1.0]\n\u2502 \u251c\u2500\u2500 g [x=0.5, y=0.0]\n\u2502 \u2514\u2500\u2500 h [x=1.5, y=0.0]\n\u2514\u2500\u2500 c [x=2.0, y=2.0]\n \u2514\u2500\u2500 f [x=2.0, y=1.0]\n
References
Parameters:
Name Type Description Defaulttree_node
BaseNode
tree to compute (x, y) coordinate
requiredsibling_separation
float
minimum distance between adjacent siblings of the tree
1.0
subtree_separation
float
minimum distance between adjacent subtrees of the tree
1.0
level_separation
float
fixed distance between adjacent levels of the tree
1.0
x_offset
float
graph offset of x-coordinates
0.0
y_offset
float
graph offset of y-coordinates
0.0
"},{"location":"bigtree/workflows/","title":"\ud83d\udc77 Workflows","text":""},{"location":"bigtree/workflows/app_calendar/","title":"\ud83d\udcc6 Calendar App","text":""},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar","title":"bigtree.workflows.app_calendar","text":""},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar","title":"Calendar","text":"Calendar(name)\n
Calendar Implementation with Big Tree. - Calendar has four levels - year, month, day, and event name (with event attributes)
Examples:
Initializing and Adding Events
>>> from bigtree import Calendar\n>>> calendar = Calendar(\"My Calendar\")\n>>> calendar.add_event(\"Gym\", \"2023-01-01 18:00\")\n>>> calendar.add_event(\"Dinner\", \"2023-01-01\", date_format=\"%Y-%m-%d\", budget=20)\n>>> calendar.add_event(\"Gym\", \"2023-01-02 18:00\")\n>>> calendar.show()\nMy Calendar\n2023-01-01 00:00:00 - Dinner (budget: 20)\n2023-01-01 18:00:00 - Gym\n2023-01-02 18:00:00 - Gym\n
Search for Events
>>> calendar.find_event(\"Gym\")\n2023-01-01 18:00:00 - Gym\n2023-01-02 18:00:00 - Gym\n
Removing Events
>>> import datetime as dt\n>>> calendar.delete_event(\"Gym\", dt.date(2023, 1, 1))\n>>> calendar.show()\nMy Calendar\n2023-01-01 00:00:00 - Dinner (budget: 20)\n2023-01-02 18:00:00 - Gym\n
Export Calendar
>>> calendar.to_dataframe()\n path name date time budget\n0 /My Calendar/2023/01/01/Dinner Dinner 2023-01-01 00:00:00 20.0\n1 /My Calendar/2023/01/02/Gym Gym 2023-01-02 18:00:00 NaN\n
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.add_event","title":"add_event","text":"add_event(\n event_name,\n event_datetime,\n date_format=\"%Y-%m-%d %H:%M\",\n **kwargs\n)\n
Add event to calendar
Parameters:
Name Type Description Defaultevent_name
str
event name to be added
requiredevent_datetime
Union[str, datetime]
event date and time
requireddate_format
str
specify datetime format if event_datetime is str
'%Y-%m-%d %H:%M'
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.delete_event","title":"delete_event","text":"delete_event(event_name, event_date=None)\n
Delete event from calendar
Parameters:
Name Type Description Defaultevent_name
str
event name to be deleted
requiredevent_date
date
event date to be deleted
None
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.find_event","title":"find_event","text":"find_event(event_name)\n
Find event by name, prints result to console
Parameters:
Name Type Description Defaultevent_name
str
event name
required"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.show","title":"show","text":"show()\n
Show calendar, prints result to console
"},{"location":"bigtree/workflows/app_calendar/#bigtree.workflows.app_calendar.Calendar.to_dataframe","title":"to_dataframe","text":"to_dataframe()\n
Export calendar to DataFrame
Returns:
Type DescriptionDataFrame
(pd.DataFrame)
"},{"location":"bigtree/workflows/app_todo/","title":"\u2714\ufe0f To Do App","text":""},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo","title":"bigtree.workflows.app_todo","text":""},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo","title":"AppToDo","text":"AppToDo(app_name='')\n
To-Do List Implementation with Big Tree. - To-Do List has three levels - app name, list name, and item name. - If list name is not given, item will be assigned to a General
list.
Examples:
Initializing and Adding Items
>>> from bigtree import AppToDo\n>>> app = AppToDo(\"To Do App\")\n>>> app.add_item(item_name=\"Homework 1\", list_name=\"School\")\n>>> app.add_item(item_name=[\"Milk\", \"Bread\"], list_name=\"Groceries\", description=\"Urgent\")\n>>> app.add_item(item_name=\"Cook\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u251c\u2500\u2500 Groceries\n\u2502 \u251c\u2500\u2500 Milk [description=Urgent]\n\u2502 \u2514\u2500\u2500 Bread [description=Urgent]\n\u2514\u2500\u2500 General\n \u2514\u2500\u2500 Cook\n
Reorder List and Item
>>> app.prioritize_list(list_name=\"General\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Milk [description=Urgent]\n \u2514\u2500\u2500 Bread [description=Urgent]\n
>>> app.prioritize_item(item_name=\"Bread\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u251c\u2500\u2500 School\n\u2502 \u2514\u2500\u2500 Homework 1\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Removing Items
>>> app.remove_item(\"Homework 1\")\n>>> app.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Exporting and Importing List
>>> app.save(\"assets/docstr/list.json\")\n>>> app2 = AppToDo.load(\"assets/docstr/list.json\")\n>>> app2.show()\nTo Do App\n\u251c\u2500\u2500 General\n\u2502 \u2514\u2500\u2500 Cook\n\u2514\u2500\u2500 Groceries\n \u251c\u2500\u2500 Bread [description=Urgent]\n \u2514\u2500\u2500 Milk [description=Urgent]\n
Initialize To-Do app
Parameters:
Name Type Description Defaultapp_name
str
name of to-do app, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.add_list","title":"add_list","text":"add_list(list_name, **kwargs)\n
Add list to app
If list is present, return list node, else a new list will be created
Parameters:
Name Type Description Defaultlist_name
str
name of list
requiredReturns:
Type DescriptionNode
(Node)
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.prioritize_list","title":"prioritize_list","text":"prioritize_list(list_name)\n
Prioritize list in app, shift it to be the first list
Parameters:
Name Type Description Defaultlist_name
str
name of list
required"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.add_item","title":"add_item","text":"add_item(item_name, list_name='', **kwargs)\n
Add items to list
Parameters:
Name Type Description Defaultitem_name
str / List[str]
items to be added
requiredlist_name
str
list to add items to, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.remove_item","title":"remove_item","text":"remove_item(item_name, list_name='')\n
Remove items from list
Parameters:
Name Type Description Defaultitem_name
str / List[str]
items to be added
requiredlist_name
str
list to add items to, optional
''
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.prioritize_item","title":"prioritize_item","text":"prioritize_item(item_name)\n
Prioritize item in list, shift it to be the first item in list
Parameters:
Name Type Description Defaultitem_name
str
name of item
required"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.show","title":"show","text":"show(**kwargs)\n
Print tree to console
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.load","title":"loadstaticmethod
","text":"load(json_path)\n
Load To-Do app from json
Parameters:
Name Type Description Defaultjson_path
str
json load path
requiredReturns:
Type DescriptionAppToDo
(Self)
"},{"location":"bigtree/workflows/app_todo/#bigtree.workflows.app_todo.AppToDo.save","title":"save","text":"save(json_path)\n
Save To-Do app as json
Parameters:
Name Type Description Defaultjson_path
str
json save path
required"},{"location":"demo/","title":"\ud83d\udccb Demonstration","text":""},{"location":"demo/binarytree/","title":"\ud83d\udccb Binary Tree Demonstration","text":"Compared to nodes in tree, nodes in Binary Tree are only allowed maximum of 2 children. Since BinaryNode extends from Node, construct, traverse, search, export methods from Node are applicable to Binary Tree as well.
"},{"location":"demo/binarytree/#construct-binary-tree","title":"Construct Binary Tree","text":""},{"location":"demo/binarytree/#1-from-binarynode","title":"1. From BinaryNode","text":"BinaryNode can be linked to each other with parent
, children
, left
, and right
setter methods, or using bitshift operator with the convention parent_node >> child_node
or child_node << parent_node
.
from bigtree import BinaryNode, tree_to_dot\n\ne = BinaryNode(5)\nd = BinaryNode(4)\nc = BinaryNode(3)\nb = BinaryNode(2, left=d, right=e)\na = BinaryNode(1, children=[b, c])\nf = BinaryNode(6, parent=c)\ng = BinaryNode(7, parent=c)\nh = BinaryNode(8, parent=d)\n\ngraph = tree_to_dot(a, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/binarytree.png\")\n
"},{"location":"demo/binarytree/#2-from-list","title":"2. From list","text":"Construct nodes only, list has similar format as heapq
list.
from bigtree import list_to_binarytree\n\nnums_list = [1, 2, 3, 4, 5, 6, 7, 8]\nroot = list_to_binarytree(nums_list)\nroot.show()\n# 1\n# \u251c\u2500\u2500 2\n# \u2502 \u251c\u2500\u2500 4\n# \u2502 \u2502 \u2514\u2500\u2500 8\n# \u2502 \u2514\u2500\u2500 5\n# \u2514\u2500\u2500 3\n# \u251c\u2500\u2500 6\n# \u2514\u2500\u2500 7\n
"},{"location":"demo/binarytree/#traverse-binary-tree","title":"Traverse Binary Tree","text":"In addition to the traversal methods in the usual tree, binary tree includes in-order traversal method.
from bigtree import (\n inorder_iter,\n levelorder_iter,\n levelordergroup_iter,\n list_to_binarytree,\n postorder_iter,\n preorder_iter,\n zigzag_iter,\n zigzaggroup_iter,\n)\n\nnums_list = [1, 2, 3, 4, 5, 6, 7, 8]\nroot = list_to_binarytree(nums_list)\nroot.show()\n# 1\n# \u251c\u2500\u2500 2\n# \u2502 \u251c\u2500\u2500 4\n# \u2502 \u2502 \u2514\u2500\u2500 8\n# \u2502 \u2514\u2500\u2500 5\n# \u2514\u2500\u2500 3\n# \u251c\u2500\u2500 6\n# \u2514\u2500\u2500 7\n\n[node.name for node in inorder_iter(root)]\n# ['8', '4', '2', '5', '1', '6', '3', '7']\n\n[node.name for node in preorder_iter(root)]\n# ['1', '2', '4', '8', '5', '3', '6', '7']\n\n[node.name for node in postorder_iter(root)]\n# ['8', '4', '5', '2', '6', '7', '3', '1']\n\n[node.name for node in levelorder_iter(root)]\n# ['1', '2', '3', '4', '5', '6', '7', '8']\n\n[[node.name for node in node_group] for node_group in levelordergroup_iter(root)]\n# [['1'], ['2', '3'], ['4', '5', '6', '7'], ['8']]\n\n[node.name for node in zigzag_iter(root)]\n# ['1', '3', '2', '4', '5', '6', '7', '8']\n\n[[node.name for node in node_group] for node_group in zigzaggroup_iter(root)]\n# [['1'], ['3', '2'], ['4', '5', '6', '7'], ['8']]\n
"},{"location":"demo/dag/","title":"\ud83d\udccb DAG Demonstration","text":"Compared to nodes in tree, nodes in DAG are able to have multiple parents.
"},{"location":"demo/dag/#construct-dag","title":"Construct DAG","text":""},{"location":"demo/dag/#1-from-dagnode","title":"1. From DAGNode","text":"DAGNodes can be linked to each other in the following ways:
parents
and children
setter methodsparents
or children
argumentparent_node >> child_node
or child_node << parent_node
from bigtree import DAGNode, dag_to_dot\n\na = DAGNode(\"a\")\nb = DAGNode(\"b\")\nc = DAGNode(\"c\", parents=[a, b])\nd = DAGNode(\"d\", parents=[a, c])\ne = DAGNode(\"e\", parents=[d])\nf = DAGNode(\"f\", parents=[c, d])\nh = DAGNode(\"h\")\ng = DAGNode(\"g\", parents=[c], children=[h])\n\ngraph = dag_to_dot(a, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/dag.png\")\n
"},{"location":"demo/dag/#2-from-list","title":"2. From list","text":"Construct nodes only, list contains parent-child tuples.
from bigtree import list_to_dag, dag_iterator\n\nrelations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\ndag = list_to_dag(relations_list)\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#3-from-nested-dictionary","title":"3. From nested dictionary","text":"Construct nodes with attributes, key
: child name, value
: dict of parent name, child node attributes.
from bigtree import dict_to_dag, dag_iterator\n\nrelation_dict = {\n \"a\": {\"step\": 1},\n \"b\": {\"step\": 1},\n \"c\": {\"parents\": [\"a\", \"b\"], \"step\": 2},\n \"d\": {\"parents\": [\"a\", \"c\"], \"step\": 2},\n \"e\": {\"parents\": [\"d\"], \"step\": 3},\n}\ndag = dict_to_dag(relation_dict, parent_key=\"parents\")\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#4-from-pandas-dataframe","title":"4. From pandas DataFrame","text":"Construct nodes with attributes, pandas DataFrame contains child column, parent column, and attribute columns.
import pandas as pd\nfrom bigtree import dataframe_to_dag, dag_iterator\n\npath_data = pd.DataFrame(\n [\n [\"a\", None, 1],\n [\"b\", None, 1],\n [\"c\", \"a\", 2],\n [\"c\", \"b\", 2],\n [\"d\", \"a\", 2],\n [\"d\", \"c\", 2],\n [\"e\", \"d\", 3],\n ],\n columns=[\"child\", \"parent\", \"step\"],\n)\ndag = dataframe_to_dag(path_data)\n\nprint([(parent.node_name, child.node_name) for parent, child in dag_iterator(dag)])\n# [('a', 'd'), ('c', 'd'), ('d', 'e'), ('a', 'c'), ('b', 'c')]\n
"},{"location":"demo/dag/#dag-attributes-and-operations","title":"DAG Attributes and Operations","text":"Note that using DAGNode
as superclass inherits the default class attributes (properties) and operations (methods).
from bigtree import list_to_dag\n\nrelations_list = [(\"a\", \"c\"), (\"a\", \"d\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\")]\ndag = list_to_dag(relations_list)\ndag\n# DAGNode(d, )\n\n# Accessing children\nnode_e = dag[\"e\"]\nnode_a = dag.parents[0]\n
Below are the tables of attributes available to DAGNode
class.
node_a.is_root
True Check if leaf node dag.is_leaf
False Get node name (only for Node
) dag.node_name
'd' Attributes wrt structure Code Returns Get child/children node_a.children
(DAGNode(c, ), DAGNode(d, )) Get parents dag.parents
(DAGNode(a, ), DAGNode(c, )) Get siblings dag.siblings
(DAGNode(c, ),) Get ancestors dag.ancestors
[DAGNode(a, ), DAGNode(b, ), DAGNode(c, )] Get descendants dag.descendants
[DAGNode(e, )] Below is the table of operations available to DAGNode
class.
dag.describe(exclude_prefix=\"_\")
[('name', 'd')] Find path(s) from one node to another node_a.go_to(dag)
[[DAGNode(a, ), DAGNode(c, ), DAGNode(d, description=dag-tag)], [DAGNode(a, ), DAGNode(d, description=dag-tag)]] Set attribute(s) dag.set_attrs({\"description\": \"dag-tag\"})
None Get attribute dag.get_attr(\"description\")
'dag-tag' Copy DAG dag.copy()
None"},{"location":"demo/tree/","title":"\ud83d\udccb Tree Demonstration","text":"Here are some codes to get started.
"},{"location":"demo/tree/#construct-tree","title":"Construct Tree","text":"Nodes can have attributes if they are initialized from Node
, dictionary, or pandas DataFrame.
Nodes can be linked to each other in the following ways:
parent
and children
setter methodsparent
or children
argumentparent >> child
or child << parent
.append(child)
or .extend([child1, child2])
methodsparent
and children
setter methodsparent
or children
argumentBitshift operatorappend
and extend
from bigtree import Node, tree_to_dot\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot.children = [b, c]\nd.parent = b\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n\nroot.hshow()\n# \u250c\u2500 b \u2500\u2500\u2500 d\n# \u2500 a \u2500\u2524\n# \u2514\u2500 c\n\ngraph = tree_to_dot(root, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/tree.png\")\n
from bigtree import Node\n\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\", parent=b)\nroot = Node(\"a\", children=[b, c])\n
from bigtree import Node\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot >> b\nroot >> c\nd << b\n
from bigtree import Node\n\nroot = Node(\"a\")\nb = Node(\"b\")\nc = Node(\"c\")\nd = Node(\"d\")\n\nroot.extend([b, c])\nb.append(d)\n
"},{"location":"demo/tree/#2-from-str","title":"2. From str","text":"Construct nodes only. Newick string notation supports parsing attributes.
Tree stringNewick stringfrom bigtree import str_to_tree\n\ntree_str = \"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2502 \u251c\u2500\u2500 g\n\u2502 \u2514\u2500\u2500 h\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\"\nroot = str_to_tree(tree_str)\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2502 \u251c\u2500\u2500 g\n# \u2502 \u2514\u2500\u2500 h\n# \u2514\u2500\u2500 c\n# \u2514\u2500\u2500 f\n
from bigtree import newick_to_tree\n\nnewick_str = \"((d,(g,h)e)b,(f)c)a\"\nroot = newick_to_tree(newick_str)\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2502 \u251c\u2500\u2500 g\n# \u2502 \u2514\u2500\u2500 h\n# \u2514\u2500\u2500 c\n# \u2514\u2500\u2500 f\n
"},{"location":"demo/tree/#3-from-list","title":"3. From list","text":"Construct nodes only. List can contain either full paths or tuples of parent-child names.
Full pathsParent-child namesfrom bigtree import list_to_tree\n\nroot = list_to_tree([\"a/b/d\", \"a/c\"])\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n
from bigtree import list_to_tree_by_relation\n\nroot = list_to_tree_by_relation([(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\")])\n\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 d\n# \u2514\u2500\u2500 c\n
"},{"location":"demo/tree/#4-from-nested-dictionary","title":"4. From nested dictionary","text":"Construct nodes with attributes. Dictionary can be in a flat structure where key
is path and value
is dictionary of node attribute names and values, or in a recursive structure where key
is node attribute names and value
is node attribute values, and list of children (recursive).
from bigtree import dict_to_tree\n\npath_dict = {\n \"a\": {\"age\": 90},\n \"a/b\": {\"age\": 65},\n \"a/c\": {\"age\": 60},\n \"a/b/d\": {\"age\": 40},\n}\nroot = dict_to_tree(path_dict)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
from bigtree import nested_dict_to_tree\n\npath_dict = {\n \"name\": \"a\",\n \"age\": 90,\n \"children\": [\n {\n \"name\": \"b\",\n \"age\": 65,\n \"children\": [\n {\"name\": \"d\", \"age\": 40},\n ],\n },\n {\"name\": \"c\", \"age\": 60},\n ],\n}\nroot = nested_dict_to_tree(path_dict)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
"},{"location":"demo/tree/#5-from-pandas-dataframe","title":"5. From pandas DataFrame","text":"Construct nodes with attributes. Pandas DataFrame can contain either path column or parent-child columns. Other columns can be used to specify attributes.
Path columnParent-child columnsimport pandas as pd\n\nfrom bigtree import dataframe_to_tree\n\ndata = pd.DataFrame(\n [\n [\"a\", 90],\n [\"a/b\", 65],\n [\"a/c\", 60],\n [\"a/b/d\", 40],\n ],\n columns=[\"path\", \"age\"],\n)\nroot = dataframe_to_tree(data)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
import pandas as pd\n\nfrom bigtree import dataframe_to_tree_by_relation\n\ndata = pd.DataFrame(\n [\n [\"a\", None, 90],\n [\"b\", \"a\", 65],\n [\"c\", \"a\", 60],\n [\"d\", \"b\", 40],\n ],\n columns=[\"child\", \"parent\", \"age\"],\n)\nroot = dataframe_to_tree_by_relation(data)\n\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u2514\u2500\u2500 d [age=40]\n# \u2514\u2500\u2500 c [age=60]\n
Note
If tree is already created, nodes can still be added using path string, dictionary, and pandas DataFrame! Attributes can be added to existing nodes using a dictionary or pandas DataFrame.
"},{"location":"demo/tree/#print-tree","title":"Print Tree","text":"After tree is constructed, it can be viewed by printing to console using show
or hshow
method directly, for vertical and horizontal orientation respectively. Alternatively, the print_tree
or hprint_tree
method can be used.
from bigtree import Node, print_tree, hprint_tree\n\nroot = Node(\"a\", age=90, gender=\"F\")\nb = Node(\"b\", age=65, gender=\"M\", parent=root)\nc = Node(\"c\", age=60, gender=\"M\", parent=root)\nd = Node(\"d\", age=40, gender=\"F\", parent=b)\ne = Node(\"e\", age=35, gender=\"M\", parent=b)\nprint_tree(root) # (1)!\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\nhprint_tree(root) # (2)!\n# \u250c\u2500 d\n# \u250c\u2500 b \u2500\u2524\n# \u2500 a \u2500\u2524 \u2514\u2500 e\n# \u2514\u2500 c\n\n# Print subtree\nprint_tree(root, node_name_or_path=\"b\")\n# b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n\nprint_tree(root, max_depth=2)\n# a\n# \u251c\u2500\u2500 b\n# \u2514\u2500\u2500 c\n\n# Print attributes\nprint_tree(root, attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2502 \u251c\u2500\u2500 d [age=40]\n# \u2502 \u2514\u2500\u2500 e [age=35]\n# \u2514\u2500\u2500 c [age=60]\n\nprint_tree(root, attr_list=[\"age\"], attr_bracket=[\"*(\", \")\"])\n# a *(age=90)\n# \u251c\u2500\u2500 b *(age=65)\n# \u2502 \u251c\u2500\u2500 d *(age=40)\n# \u2502 \u2514\u2500\u2500 e *(age=35)\n# \u2514\u2500\u2500 c *(age=60)\n\nprint_tree(root, all_attrs=True)\n# a [age=90, gender=F]\n# \u251c\u2500\u2500 b [age=65, gender=M]\n# \u2502 \u251c\u2500\u2500 d [age=40, gender=F]\n# \u2502 \u2514\u2500\u2500 e [age=35, gender=M]\n# \u2514\u2500\u2500 c [age=60, gender=M]\n\n# Available styles\nprint_tree(root, style=\"ansi\")\n# a\n# |-- b\n# | |-- d\n# | `-- e\n# `-- c\n\nprint_tree(root, style=\"ascii\")\n# a\n# |-- b\n# | |-- d\n# | +-- e\n# +-- c\n\nprint_tree(root, style=\"const\")\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\nprint_tree(root, style=\"const_bold\")\n# a\n# \u2523\u2501\u2501 b\n# \u2503 \u2523\u2501\u2501 d\n# \u2503 \u2517\u2501\u2501 e\n# \u2517\u2501\u2501 c\n\nprint_tree(root, style=\"rounded\")\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2570\u2500\u2500 e\n# \u2570\u2500\u2500 c\n\nprint_tree(root, style=\"double\")\n# a\n# \u2560\u2550\u2550 b\n# \u2551 \u2560\u2550\u2550 d\n# \u2551 \u255a\u2550\u2550 e\n# \u255a\u2550\u2550 c\n\nprint_tree(\n root,\n style=\"custom\",\n custom_style=(\"\u2502 \", \"\u251c\u2192 \", \"\u2570\u2192 \"),\n)\n# a\n# \u251c\u2192 b\n# \u2502 \u251c\u2192 d\n# \u2502 \u2570\u2192 e\n# \u2570\u2192 c\n
root.show()
can be usedroot.hshow()
can be usedNote that using BaseNode
or Node
as superclass inherits the default class attributes (properties) and operations (methods).
from bigtree import str_to_tree\n\n# Initialize tree\ntree_str = \"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u251c\u2500\u2500 e\n\u2502 \u2514\u2500\u2500 f\n\u2502 \u251c\u2500\u2500 h\n\u2502 \u2514\u2500\u2500 i\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 g\n\"\"\"\nroot = str_to_tree(tree_str)\n\n# Accessing children\nnode_b = root[\"b\"]\nnode_e = root[\"b\"][\"e\"]\n
Below are the tables of attributes available to BaseNode
and Node
classes.
root.is_root
True Check if leaf node root.is_leaf
False Check depth of node node_b.depth
2 Check depth of tree node_b.max_depth
4 Get root of tree node_b.root
Node(/a, ) Get node path node_b.node_path
(Node(/a, ), Node(/a/b, )) Get node name (only for Node
) node_b.node_name
'b' Get node path name (only for Node
) node_b.path_name
'/a/b' Attributes wrt structure Code Returns Get child/children root.children
(Node(/a/b, ), Node(/a/c, )) Get parent node_e.parent
Node(/a/b, ) Get siblings node_e.siblings
(Node(/a/b/d, ), Node(/a/b/f, )) Get left sibling node_e.left_sibling
Node(/a/b/d, ) Get right sibling node_e.right_sibling
Node(/a/b/f, ) Get ancestors (lazy evaluation) list(node_e.ancestors)
[Node(/a/b, ), Node(/a, )] Get descendants (lazy evaluation) list(node_b.descendants)
[Node(/a/b/d, ), Node(/a/b/e, ), Node(/a/b/f, ), Node(/a/b/f/h, ), Node(/a/b/f/i, )] Get leaves (lazy evaluation) list(node_b.leaves)
[Node(/a/b/d, ), Node(/a/b/e, ), Node(/a/b/f/h, ), Node(/a/b/f/i, )] Below is the table of operations available to BaseNode
and Node
classes.
Node
) root.show()
None Visualize tree (horizontally) (only for Node
) root.hshow()
None Get node information root.describe(exclude_prefix=\"_\")
[('name', 'a')] Find path from one node to another root.go_to(node_e)
[Node(/a, ), Node(/a/b, ), Node(/a/b/e, )] Add child to node root.append(Node(\"j\"))
None Add multiple children to node root.extend([Node(\"k\"), Node(\"l\")])
None Set attribute(s) root.set_attrs({\"description\": \"root-tag\"})
None Get attribute root.get_attr(\"description\")
'root-tag' Copy tree root.copy()
None Sort children root.sort(key=lambda node: node.node_name, reverse=True)
None"},{"location":"demo/tree/#traverse-tree","title":"Traverse Tree","text":"Tree can be traversed using the following traversal methods.
from bigtree import (\n Node,\n levelorder_iter,\n levelordergroup_iter,\n postorder_iter,\n preorder_iter,\n zigzag_iter,\n zigzaggroup_iter,\n)\n\nroot = Node(\"a\")\nb = Node(\"b\", parent=root)\nc = Node(\"c\", parent=root)\nd = Node(\"d\", parent=b)\ne = Node(\"e\", parent=b)\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n\n[node.name for node in preorder_iter(root)]\n# ['a', 'b', 'd', 'e', 'c']\n\n[node.name for node in postorder_iter(root)]\n# ['d', 'e', 'b', 'c', 'a']\n\n[node.name for node in levelorder_iter(root)]\n# ['a', 'b', 'c', 'd', 'e']\n\n[[node.name for node in node_group] for node_group in levelordergroup_iter(root)]\n# [['a'], ['b', 'c'], ['d', 'e']]\n\n[node.name for node in zigzag_iter(root)]\n# ['a', 'c', 'b', 'd', 'e']\n\n[[node.name for node in node_group] for node_group in zigzaggroup_iter(root)]\n# [['a'], ['c', 'b'], ['d', 'e']]\n
"},{"location":"demo/tree/#modify-tree","title":"Modify Tree","text":"Nodes can be shifted (with or without replacement) or copied (without replacement) from one path to another, this changes the tree in-place. Nodes can also be copied (with or without replacement) between two different trees.
Shift nodesfrom bigtree import list_to_tree, shift_nodes, shift_and_replace_nodes\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\nshift_nodes(\n tree=root,\n from_paths=[\"photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (1)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (2)\n\nshift_and_replace_nodes(\n tree=root,\n from_paths=[\"Downloads/Files\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\"],\n)\nroot.show()\n# Downloads\n# \u2514\u2500\u2500 Pictures\n# \u2514\u2500\u2500 Files (3)\n# \u2514\u2500\u2500 file1.doc\n
Downloads/Pictures/photo1.jpg
Downloads/Files/file1.doc
, this creates intermediate Node Files
as wellphoto1.jpg
with Files
folderfrom bigtree import list_to_tree, copy_nodes\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\ncopy_nodes(\n tree=root,\n from_paths=[\"photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Downloads/Pictures/photo1.jpg\", \"Downloads/Files/file1.doc\"],\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (1)\n# \u251c\u2500\u2500 photo1.jpg (2)\n# \u251c\u2500\u2500 file1.doc (4)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (3)\n
Downloads/Pictures/photo1.jpg
photo1.jpg
still remainsDownloads/Files/file1.doc
, this creates intermediate Node Files
as wellfile1.doc
still remainsfrom bigtree import (\n Node,\n copy_nodes_from_tree_to_tree,\n copy_and_replace_nodes_from_tree_to_tree,\n list_to_tree,\n)\n\nroot = list_to_tree(\n [\"Downloads/Pictures\", \"Downloads/photo1.jpg\", \"Downloads/file1.doc\"]\n)\nroot.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u251c\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\nroot_other = Node(\"Documents\")\ncopy_nodes_from_tree_to_tree(\n from_tree=root,\n to_tree=root_other,\n from_paths=[\"Downloads/Pictures\", \"photo1.jpg\", \"file1.doc\"],\n to_paths=[\n \"Documents/Pictures\",\n \"Documents/Pictures/photo1.jpg\",\n \"Documents/Files/file1.doc\",\n ],\n)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures (1)\n# \u2502 \u2514\u2500\u2500 photo1.jpg (2)\n# \u2514\u2500\u2500 Files\n# \u2514\u2500\u2500 file1.doc (3)\n\nroot_other = Node(\"Documents\")\npicture_folder = Node(\"Pictures\", parent=root_other)\nphoto2 = Node(\"photo2.jpg\", parent=picture_folder)\nfile2 = Node(\"file2.doc\", parent=root_other)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo2.jpg\n# \u2514\u2500\u2500 file2.doc\n\ncopy_and_replace_nodes_from_tree_to_tree(\n from_tree=root,\n to_tree=root_other,\n from_paths=[\"Downloads/photo1.jpg\", \"Downloads/file1.doc\"],\n to_paths=[\"Documents/Pictures/photo2.jpg\", \"Documents/file2.doc\"],\n)\nroot_other.show()\n# Documents\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg (4)\n# \u2514\u2500\u2500 file1.doc (5)\n
Documents/Pictures
Documents/Pictures/photo1.jpg
Documents/Files/file1.doc
, this creates intermediate Node Files
as wellDocuments/Pictures/photo2.jpg
with photo1.jpg
Documents/file2.doc
with file1.doc
One or multiple nodes can be searched based on name, path, attribute value, or user-defined condition. It is also possible to search for one or more child node(s) based on attributes, this search will be faster as it does not require traversing the whole tree to find the node(s).
Find single nodeFind multiple nodesFind child nodesfrom bigtree import Node, find, find_name, find_path, find_relative_path, find_full_path, find_attr\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"d\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 d [age=40]\n\nfind(root, lambda node: node.age == 60)\n# Node(/a/c, age=60)\n\nfind_name(root, \"d\")\n# Node(/a/c/d, age=40)\n\nfind_relative_path(c, \"../b\") # relative path\n# (Node(/a/b, age=65),)\n\nfind_path(root, \"/c/d\") # partial path\n# Node(/a/c/d, age=40)\n\nfind_full_path(root, \"a/c/d\") # full path\n# Node(/a/c/d, age=40)\n\nfind_attr(root, \"age\", 40)\n# Node(/a/c/d, age=40)\n
from bigtree import Node, findall, find_names, find_relative_path, find_paths, find_attrs\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"c\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 c [age=40]\n\nfindall(root, lambda node: node.age >= 65)\n# (Node(/a, age=90), Node(/a/b, age=65))\n\nfind_names(root, \"c\")\n# (Node(/a/c, age=60), Node(/a/c/c, age=40))\n\nfind_relative_path(c, \"../*\") # relative path\n# (Node(/a/b, age=65), Node(/a/c, age=60))\n\nfind_paths(root, \"/c\") # partial path\n# (Node(/a/c, age=60), Node(/a/c/c, age=40))\n\nfind_attrs(root, \"age\", 40)\n# (Node(/a/c/c, age=40),)\n
from bigtree import Node, find_children, find_child, find_child_by_name\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"c\", age=40, parent=c)\nroot.show(attr_list=[\"age\"])\n# a [age=90]\n# \u251c\u2500\u2500 b [age=65]\n# \u2514\u2500\u2500 c [age=60]\n# \u2514\u2500\u2500 c [age=40]\n\nfind_children(root, lambda node: node.age >= 60)\n# (Node(/a/b, age=65), Node(/a/c, age=60))\n\nfind_child(root, lambda node: node.name == \"c\")\n# Node(/a/c, age=60)\n\nfind_child_by_name(root, \"c\")\n# Node(/a/c, age=60)\n\nfind_child_by_name(c, \"c\")\n# Node(/a/c/c, age=40)\n
"},{"location":"demo/tree/#helper-utility","title":"Helper Utility","text":"There following are helper functions for
"},{"location":"demo/tree/#1-cloning-tree-to-another-node-type","title":"1. Cloning tree to another Node type","text":"from bigtree import BaseNode, Node, clone_tree\n\n# Cloning tree from `BaseNode` to `Node` type\nroot = BaseNode(name=\"a\")\nb = BaseNode(name=\"b\", parent=root)\nclone_tree(root, Node)\n# Node(/a, )\n
"},{"location":"demo/tree/#2-getting-subtree-smaller-tree-with-different-root","title":"2. Getting subtree (smaller tree with different root)","text":"from bigtree import str_to_tree, get_subtree\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Getting subtree with root b\nroot_subtree = get_subtree(root, \"b\")\nroot_subtree.show()\n# b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n
"},{"location":"demo/tree/#3-pruning-tree-smaller-tree-with-same-root","title":"3. Pruning tree (smaller tree with same root)","text":"from bigtree import str_to_tree, prune_tree\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Prune tree to only path a/b\nroot_pruned = prune_tree(root, \"a/b\")\nroot_pruned.show()\n# a\n# \u2514\u2500\u2500 b\n# \u251c\u2500\u2500 d\n# \u2514\u2500\u2500 e\n\n# Prune tree to exactly path a/b\nroot_pruned = prune_tree(root, \"a/b\", exact=True)\nroot_pruned.show()\n# a\n# \u2514\u2500\u2500 b\n
"},{"location":"demo/tree/#4-getting-difference-between-two-trees","title":"4. Getting difference between two trees","text":"from bigtree import str_to_tree, get_tree_diff\n\nroot = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u251c\u2500\u2500 d\n\u2502 \u2514\u2500\u2500 e\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 f\n\"\"\")\n\n# Get difference between two trees\nroot_other = str_to_tree(\"\"\"\na\n\u251c\u2500\u2500 b\n\u2502 \u2514\u2500\u2500 d\n\u2514\u2500\u2500 c\n \u2514\u2500\u2500 g\n\"\"\")\n\ntree_diff = get_tree_diff(root, root_other)\ntree_diff.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u2514\u2500\u2500 e (-)\n# \u2514\u2500\u2500 c\n# \u251c\u2500\u2500 f (-)\n# \u2514\u2500\u2500 g (+)\n\ntree_diff = get_tree_diff(root, root_other, only_diff=False)\ntree_diff.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e (-)\n# \u2514\u2500\u2500 c\n# \u251c\u2500\u2500 f (-)\n# \u2514\u2500\u2500 g (+)\n
"},{"location":"demo/tree/#export-tree","title":"Export Tree","text":"Tree can be exported to other data types:
from bigtree import Node\n\nroot = Node(\"a\", age=90)\nb = Node(\"b\", age=65, parent=root)\nc = Node(\"c\", age=60, parent=root)\nd = Node(\"d\", age=40, parent=b)\ne = Node(\"e\", age=35, parent=b)\nroot.show()\n# a\n# \u251c\u2500\u2500 b\n# \u2502 \u251c\u2500\u2500 d\n# \u2502 \u2514\u2500\u2500 e\n# \u2514\u2500\u2500 c\n
Newick string notationDictionary (flat structure)Dictionary (recursive structure)pandas DataFrameDotPillowMermaid Flowchart from bigtree import tree_to_newick\n\ntree_to_newick(root)\n# '((d,e)b,c)a'\n\ntree_to_newick(root, attr_list=[\"age\"])\n# '((d[&&NHX:age=40],e[&&NHX:age=35])b[&&NHX:age=65],c[&&NHX:age=60])a[&&NHX:age=90]'\n
from bigtree import tree_to_dict\n\ntree_to_dict(\n root,\n name_key=\"name\",\n parent_key=\"parent\",\n attr_dict={\"age\": \"person age\"}\n)\n# {\n# '/a': {'name': 'a', 'parent': None, 'person age': 90},\n# '/a/b': {'name': 'b', 'parent': 'a', 'person age': 65},\n# '/a/b/d': {'name': 'd', 'parent': 'b', 'person age': 40},\n# '/a/b/e': {'name': 'e', 'parent': 'b', 'person age': 35},\n# '/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}\n# }\n
from bigtree import tree_to_nested_dict\n\ntree_to_nested_dict(root, all_attrs=True)\n# {\n# 'name': 'a',\n# 'age': 90,\n# 'children': [\n# {\n# 'name': 'b',\n# 'age': 65,\n# 'children': [\n# {\n# 'name': 'd',\n# 'age': 40\n# },\n# {\n# 'name': 'e',\n# 'age': 35\n# }\n# ]\n# },\n# {\n# 'name': 'c',\n# 'age': 60\n# }\n# ]\n# }\n
from bigtree import tree_to_dataframe\n\ntree_to_dataframe(\n root,\n name_col=\"name\",\n parent_col=\"parent\",\n path_col=\"path\",\n attr_dict={\"age\": \"person age\"}\n)\n# path name parent person age\n# 0 /a a None 90\n# 1 /a/b b a 65\n# 2 /a/b/d d b 40\n# 3 /a/b/e e b 35\n# 4 /a/c c a 60\n
from bigtree import tree_to_dot\n\ngraph = tree_to_dot(root, node_colour=\"gold\")\ngraph.write_png(\"assets/demo/dot.png\")\n
from bigtree import tree_to_pillow\n\npillow_image = tree_to_pillow(root)\npillow_image.save(\"assets/demo/pillow.png\")\n
from bigtree import tree_to_mermaid\n\nmermaid_md = tree_to_mermaid(root)\nprint(mermaid_md)\n
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%\nflowchart TB\n0(\"a\") --> 0-0(\"b\")\n0-0 --> 0-0-0(\"d\")\n0-0 --> 0-0-1(\"e\")\n0(\"a\") --> 0-1(\"c\")\nclassDef default stroke-width:1
There are existing implementations of workflows to showcase how bigtree
can be used!
There are functions to:
from bigtree import AppToDo\n\napp = AppToDo(\"To Do App\")\napp.add_item(item_name=\"Homework 1\", list_name=\"School\")\napp.add_item(item_name=[\"Milk\", \"Bread\"], list_name=\"Groceries\", description=\"Urgent\")\napp.add_item(item_name=\"Cook\")\napp.show()\n# To Do App\n# \u251c\u2500\u2500 School\n# \u2502 \u2514\u2500\u2500 Homework 1\n# \u251c\u2500\u2500 Groceries\n# \u2502 \u251c\u2500\u2500 Milk [description=Urgent]\n# \u2502 \u2514\u2500\u2500 Bread [description=Urgent]\n# \u2514\u2500\u2500 General\n# \u2514\u2500\u2500 Cook\n\napp.save(\"list.json\")\napp2 = AppToDo.load(\"list.json\")\n
"},{"location":"demo/workflow/#calendar-application","title":"Calendar Application","text":"There are functions to:
import datetime as dt\nfrom bigtree import Calendar\n\ncalendar = Calendar(\"My Calendar\")\ncalendar.add_event(\"Gym\", \"2023-01-01 18:00\")\ncalendar.add_event(\"Dinner\", \"2023-01-01\", date_format=\"%Y-%m-%d\", budget=20)\ncalendar.add_event(\"Gym\", \"2023-01-02 18:00\")\ncalendar.show()\n# My Calendar\n# 2023-01-01 00:00:00 - Dinner (budget: 20)\n# 2023-01-01 18:00:00 - Gym\n# 2023-01-02 18:00:00 - Gym\n\ncalendar.find_event(\"Gym\")\n# 2023-01-01 18:00:00 - Gym\n# 2023-01-02 18:00:00 - Gym\n\ncalendar.delete_event(\"Gym\", dt.date(2023, 1, 1))\ncalendar.show()\n# My Calendar\n# 2023-01-01 00:00:00 - Dinner (budget: 20)\n# 2023-01-02 18:00:00 - Gym\n\ndata_calendar = calendar.to_dataframe()\ndata_calendar\n# path name date time budget\n# 0 /My Calendar/2023/01/01/Dinner Dinner 2023-01-01 00:00:00 20.0\n# 1 /My Calendar/2023/01/02/Gym Gym 2023-01-02 18:00:00 NaN\n
"},{"location":"others/","title":"\ud83d\udca1 Tips and Tricks","text":""},{"location":"others/list_dir/","title":"List Directory","text":"To list directories recursively using bigtree, we can use the glob
built-in Python package to extract a list of paths.
import glob\nfrom bigtree import list_to_tree, print_tree\n\n# Get all directories recursively\npath_list = []\nfor f in glob.glob(\"./**/*.py\", recursive=True):\n path_list.append(f)\n\n# Construct tree\nroot = list_to_tree(path_list)\n\n# View tree\nprint_tree(root, max_depth=3)\n
"},{"location":"others/merging_trees/","title":"Merging Trees","text":"To merge two separate trees into one, we can use the tree modify module.
In this example, we are merging two trees that have similar node Pictures
. Children of node Pictures
from both trees are retained as long as merge_children=True
is set. If only children of the other tree are desired, set overriding=True
instead.
from bigtree import Node, copy_nodes_from_tree_to_tree\n\n# Construct trees\ndownloads_folder = Node(\"Downloads\")\npictures_folder = Node(\"Pictures\", parent=downloads_folder)\nphoto1 = Node(\"photo1.jpg\", parent=pictures_folder)\nfile1 = Node(\"file1.doc\", parent=downloads_folder)\n\ndocuments_folder = Node(\"Documents\")\npictures_folder = Node(\"Pictures\", parent=documents_folder)\nphoto2 = Node(\"photo2.jpg\", parent=pictures_folder)\n\n# Validate tree structure\ndownloads_folder.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u2514\u2500\u2500 photo1.jpg\n# \u2514\u2500\u2500 file1.doc\n\ndocuments_folder.show()\n# Documents\n# \u2514\u2500\u2500 Pictures\n# \u2514\u2500\u2500 photo2.jpg\n\n# Merge trees\ncopy_nodes_from_tree_to_tree(\n from_tree=documents_folder,\n to_tree=downloads_folder,\n from_paths=[\"Documents/Pictures\"],\n to_paths=[\"Downloads/Pictures\"],\n merge_children=True, # set overriding=True to override existing children\n)\n\n# Validate tree structure\ndownloads_folder.show()\n# Downloads\n# \u251c\u2500\u2500 Pictures\n# \u2502 \u251c\u2500\u2500 photo1.jpg\n# \u2502 \u2514\u2500\u2500 photo2.jpg\n# \u2514\u2500\u2500 file1.doc\n
"},{"location":"others/nodes/","title":"Extending Nodes","text":"Nodes can be extended from BaseNode
or Node
class to have extended functionalities or add pre-/post-assign checks. - For example, Node
class extends BaseNode
and added the name
functionality with pre-assign checks to ensure no duplicate path names.
from bigtree import Node, print_tree\n\n\nclass PopulationNode(Node):\n\n def __init__(self, name: str, population: int = 0, **kwargs):\n super().__init__(name, **kwargs)\n self._population = population\n\n @property\n def population(self):\n if self.is_leaf:\n return self._population\n return sum([child.population for child in self.children])\n\n @property\n def percentage(self):\n if self.is_root:\n return 1\n return round(self.population / self.root.population, 2)\n\n\nroot = PopulationNode(\"World\")\nb1 = PopulationNode(\"Country A\", parent=root)\nc1 = PopulationNode(\"State A1\", 100, parent=b1)\nc2 = PopulationNode(\"State A2\", 50, parent=b1)\nb2 = PopulationNode(\"Country B\", 200, parent=root)\nb3 = PopulationNode(\"Country C\", 100, parent=root)\n\nprint_tree(root, attr_list=[\"population\", \"percentage\"])\n# World [population=450, percentage=1]\n# \u251c\u2500\u2500 Country A [population=150, percentage=0.33]\n# \u2502 \u251c\u2500\u2500 State A1 [population=100, percentage=0.22]\n# \u2502 \u2514\u2500\u2500 State A2 [population=50, percentage=0.11]\n# \u251c\u2500\u2500 Country B [population=200, percentage=0.44]\n# \u2514\u2500\u2500 Country C [population=100, percentage=0.22]\n
"},{"location":"others/nodes/#read-only-node-add-pre-post-assign-checks","title":"Read-Only Node (add pre-/post-assign checks)","text":"import pytest\n\nfrom bigtree import Node\nfrom typing import List\n\n\nclass ReadOnlyNode(Node):\n\n def __init__(self, *args, **kwargs):\n self.__readonly = False\n super().__init__(*args, **kwargs)\n self.__readonly = True\n\n def _Node__pre_assign_parent(self, new_parent: Node):\n if self.__readonly:\n raise RuntimeError(\"Nodes cannot be reassigned for ReadOnlyNode\")\n\n def _Node__pre_assign_children(self, new_children: List[Node]):\n if self.__readonly:\n raise RuntimeError(\"Nodes cannot be reassigned for ReadOnlyNode\")\n\n\na = ReadOnlyNode(\"a\")\nb = ReadOnlyNode(\"b\", parent=a)\nc = ReadOnlyNode(\"c\", parent=a)\n\nwith pytest.raises(RuntimeError):\n c.parent = b\n\nwith pytest.raises(RuntimeError):\n a.children = [b, c]\n
"},{"location":"others/remove_checks/","title":"Remove Tree Checks","text":"Note
Available from version 0.16.2 onwards
When constructing trees, there are a few checks done that slow down performance. This slowness will be more apparent with very large trees. The checks are to
These checks are enabled by default. To turn off these checks, you can set environment variable before importing bigtree
.
import os\nos.environ[\"BIGTREE_CONF_ASSERTIONS\"] = \"\"\n\nimport bigtree\n
"},{"location":"others/weighted_trees/","title":"Trees with Weighted Edges","text":"Edge weights should be defined in the child node for the parent-child edge since each node can only have one parent.
We can simply add weight
attribute to the Node
class. However, if we want to visualize the weighted tree, we can create a WeightedNode
class to generate the edge attribute dictionary.
from bigtree import Node, tree_to_dot\n\nclass WeightedNode(Node):\n def __init__(self, name, weight=0, **kwargs):\n super().__init__(name, **kwargs)\n self.weight = weight\n\n @property\n def edge_attr(self):\n \"\"\"Edge attribute for pydot diagram\n Label for edge label, penwidth for edge width\n \"\"\"\n return {\"label\": self.weight, \"penwidth\": self.weight}\n\n# Construct weighted tree\nroot = WeightedNode(\"a\")\nb = WeightedNode(\"b\", parent=root, weight=1)\nc = WeightedNode(\"c\", parent=root, weight=2)\nd = WeightedNode(\"d\", parent=b, weight=3)\n\ngraph = tree_to_dot(root, node_colour=\"gold\", edge_attr=\"edge_attr\")\ngraph.write_png(\"assets/docs/weighted_tree.png\")\n
"},{"location":"resources/","title":"\ud83d\udcf0 Resources","text":""},{"location":"resources/articles/","title":"\ud83d\udcf0 Articles","text":"Integrating trees with Python lists, dictionaries, and pandas DataFrames
Read article
Algorithm to Plot Tree Nodes with Numerical Examples and Python Code
Read article