Reference on kuibit.tree¶
The tree
module provides a data structure to work with trees.
The Tree
describes one node of a tree with a name and a value. The
node has any number of children, which are objects of the type
Tree
themselves. (There is no real distinction on what is a node
and what is a tree.) Given a Tree
, the children can be accessed by
index or by name. Tree
can also be exported to dictionaries or
JSON strings.
Different trees can be combined with the function merge_trees()
,
which acts in the followin way. It takes any number of nodes that share the name
and create a new tree with that name. The children of this new tree are obtained
by combining all the children of the given nodes, and when children have the
same name, the new value is obtained by applying a given function (e.g., summing
up).
Currently, the main use of this structure in kuibit
is for timers.
- class kuibit.tree.Tree(name, value, children=())[source]¶
Represent one node of a tree (and recursively, the tree itself).
- Variables:
name – Name of the node.
value – Value of the node.
children – Tuple with the nodes that are children of this one.
Constructor.
- property is_leaf: bool¶
Return whether the node is a leaf node or not.
- to_dict()[source]¶
Convert the tree into a dictionary.
The conversion happens in the following way: each node is converted into a dictionary with two or three elements: the name, the value, and, if there are children, a list of children. In turn, the children are represented as dictionaries in the same way.
- Return type:
dict
- Returns:
A dictionary representing the node and all its children.
- to_json()[source]¶
Convert the tree into a string with its JSON representation.
- Return type:
str
- Returns:
String containing the JSON representation of the tree.
- property tot_value_leaves: float¶
Return the sum of all the values in all the levas.
If the node has no children, return the value of the node itself.
- Returns:
Cumulative values of the children.
- kuibit.tree.merge_trees(trees, merge_function=<built-in function sum>)[source]¶
Combine multiple trees that start from the same place to a new one.
When multiple nodes are found at the same level with the same name, apply merge_function to the list of values to generate the new value. The default is to sum them up, but another good idea would be to take the mean.
The algorithm that mergers the tree is simple: it combines all the children of any given node (as identified by the name) across the tree. Therefore, the trees are meaningfully merged only if they are already relatively similar one with the other.
- Parameters:
trees (
Iterable
[Tree
]) – List of trees that have to be merged. They have to start from a node with the same name.merge_function (
Callable
[[Iterable
[float
]],float
]) – Function that has to be applied to reduce the various values to a single one.
- Return type:
- Returns:
A new tree with all the nodes from the given trees.