decision_tree package

Submodules

decision_tree.abc module

decision_tree.collection module

decision_tree.exc module

exception decision_graph.decision_tree.exc.EmptyBlock[source]

Bases: Exception

Raised when a SkippableContextBlock is empty.

exception decision_graph.decision_tree.exc.BreakBlock[source]

Bases: Exception

Base exception for skipping a SkippableContextBlock. Internal use only.

exception decision_graph.decision_tree.exc.NodeError[source]

Bases: Exception

Base exception for node-related errors.

exception decision_graph.decision_tree.exc.TooManyChildren[source]

Bases: NodeError

Raised when a node has too many children or when trying to add a child node exceeding its limits, and other exception situations related to or caused by too many child nodes.

exception decision_graph.decision_tree.exc.TooFewChildren[source]

Bases: NodeError

Raised when a node has too few children.

exception decision_graph.decision_tree.exc.NodeNotFountError[source]

Bases: NodeError

Raised when a specified node cannot be found.

exception decision_graph.decision_tree.exc.NodeValueError[source]

Bases: NodeError

Raised when a node has an invalid value.

exception decision_graph.decision_tree.exc.NodeTypeError[source]

Bases: NodeError

Raised when a node has an invalid type.

exception decision_graph.decision_tree.exc.NodeContextError[source]

Bases: NodeError

Raised when errors occur in the LogicNode context manager protocol.

exception decision_graph.decision_tree.exc.EdgeValueError[source]

Bases: NodeError

Raised when a NodeEdgeCondition has an invalid value.

exception decision_graph.decision_tree.exc.ResolutionError[source]

Bases: NodeError

Raised when an error occurs during resolution.

exception decision_graph.decision_tree.exc.ExpressFalse[source]

Bases: Exception

Custom exception raised when a LogicExpression evaluates to False.

exception decision_graph.decision_tree.exc.ContextsNotFound[source]

Bases: Exception

Raised when required contexts of LogicGroup are not found.

decision_tree.expression module

decision_tree.logic_group module

decision_tree.node module

Module contents

decision_graph.decision_tree.set_logger(logger: Logger)[source]
exception decision_graph.decision_tree.NodeError[source]

Bases: Exception

Base exception for node-related errors.

exception decision_graph.decision_tree.TooManyChildren[source]

Bases: NodeError

Raised when a node has too many children or when trying to add a child node exceeding its limits, and other exception situations related to or caused by too many child nodes.

exception decision_graph.decision_tree.TooFewChildren[source]

Bases: NodeError

Raised when a node has too few children.

exception decision_graph.decision_tree.NodeNotFountError[source]

Bases: NodeError

Raised when a specified node cannot be found.

exception decision_graph.decision_tree.NodeValueError[source]

Bases: NodeError

Raised when a node has an invalid value.

exception decision_graph.decision_tree.EdgeValueError[source]

Bases: NodeError

Raised when a NodeEdgeCondition has an invalid value.

exception decision_graph.decision_tree.ResolutionError[source]

Bases: NodeError

Raised when an error occurs during resolution.

exception decision_graph.decision_tree.ExpressFalse[source]

Bases: Exception

Custom exception raised when a LogicExpression evaluates to False.

exception decision_graph.decision_tree.ContextsNotFound[source]

Bases: Exception

Raised when required contexts of LogicGroup are not found.

class decision_graph.decision_tree.LogicGroup(name, *args, **kwargs)[source]

Bases: object

A minimal context manager to save/restore state from the .contexts dict.

A logic group maintains no status itself; the status should be restored from the outer .contexts dict.

__init__(name: str, parent: Self = None, contexts: dict[str, Any] = None)[source]
break_(scope: LogicGroup = None)[source]
property sub_logics: dict[str, Self]
class decision_graph.decision_tree.SkipContextsBlock[source]

Bases: object

classmethod empty_trace(*args, **kwargs) None[source]
classmethod err_trace(frame, event, arg)[source]
static get_trace()[source]

Safely retrieve the current trace function, prioritizing the PyDev debugger’s trace function.

class decision_graph.decision_tree.LogicExpression(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None)[source]

Bases: SkipContextsBlock

Represents a logical or mathematical expression that supports deferred evaluation.

__init__(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

classmethod cast(value: int | float | bool | Exception | Self, dtype: type = None) Self[source]

Convert a static value, callable, or error into a LogicExpression.

Parameters:
  • value (Union[int, float, bool, LogicExpression, Callable, Exception]) – The value to convert. Can be: - A static value (int, float, or bool). - A callable returning a value. - A pre-existing LogicExpression. - An Exception to raise during evaluation.

  • dtype (type, optional) – The expected type of the resulting LogicExpression. If None, it will be inferred from the value.

Returns:

The resulting LogicExpression.

Return type:

LogicExpression

Raises:

TypeError – If the value type is unsupported or dtype is incompatible.

eval(enforce_dtype: bool = False) Any[source]

Evaluate the expression.

class decision_graph.decision_tree.LogicNode(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None)[source]

Bases: LogicExpression

__init__(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

append(expression: LogicNode, edge_condition: Any = None)[source]

Adds a child node to the current node.

Parameters:
  • expression (LogicNode) – The child node.

  • edge_condition (Any, optional) – The condition for branching.

Raises:

ValueError – If no edge condition is provided.

property children: Iterable[tuple[Any, LogicNode]]

Returns an iterable of (edge, node) pairs.

eval_recursively(**kwargs)[source]

Recursively evaluates the decision tree starting from this node.

Keyword Arguments:
  • path (list, optional) – Tracks the decision path during evaluation. Defaults to a new list.

  • default (Any, optional) – Fallback value if no matching condition is found.

Returns:

(final_value, decision_path)
  • final_value (Any): The evaluated result of the tree.

  • decision_path (list): The sequence of nodes traversed during evaluation.

Return type:

tuple

Raises:

ValueError – If no matching condition is found and no default value is provided.

classmethod fill_binary_branch(node: LogicNode, with_action: ActionNode = None)[source]

Ensures the decision tree node has both True and False branches.

Parameters:
  • node (LogicNode) – The node to check.

  • with_action (ActionNode, optional) – A default action node to add if missing.

property last_edge: Any
property last_leaf: LogicNode
property last_leaf_expression: LogicNode
property last_node: LogicNode
property leaves: Iterable[LogicNode]

Recursively finds and returns all leaf nodes (nodes without children).

list_labels() dict[str, list[LogicNode]][source]

Lists all logic groups in the tree and returns a dictionary mapping group names to nodes.

pop(index: int = -1) tuple[Any, LogicNode][source]
replace(original_node: LogicNode, new_node: LogicNode)[source]
select_node(label: str) LogicNode | None[source]

Selects the root node of a logic group and validates that the group is chained.

to_html(with_group=True, dry_run=True, filename='decision_graph.html', **kwargs)[source]

Visualizes the decision tree using PyVis. If dry_run=True, shows structure without highlighting active path. If dry_run=False, evaluates the tree and highlights the decision path. If with_group=True, uses grouped logic view.

classmethod traverse(node: Self, G=None, node_map: dict[int, Self] = None, parent: Self = None, edge_condition: Any = None)[source]

Recursively traverses the decision tree, adding nodes and edges to the graph.

Parameters:
  • node (LogicNode) – The current node being traversed.

  • G (networkx.DiGraph, optional) – The graph being constructed. Defaults to a new graph.

  • node_map (dict, optional) – A dictionary mapping node IDs to LogicNode instances.

  • parent (LogicNode, optional) – The parent node of the current node.

  • edge_condition (Any, optional) – The condition from parent to this node.

class decision_graph.decision_tree.ActionNode(action: Callable[[], Any] | None = None, repr: str = None, auto_connect: bool = True)[source]

Bases: LogicNode

__init__(action: Callable[[], Any] | None = None, repr: str = None, auto_connect: bool = True)[source]

Initialize the LogicExpression.

Parameters:
  • action (Union[Any, Callable[[], Any]]) – The action to execute.

  • repr (str, optional) – A string representation of the expression.

  • auto_connect – auto-connect to the current active decision graph.

append(expression: Self, edge_condition: Any = None)[source]

Adds a child node to the current node.

Parameters:
  • expression (LogicNode) – The child node.

  • edge_condition (Any, optional) – The condition for branching.

Raises:

ValueError – If no edge condition is provided.

eval_recursively(path=None)[source]

Evaluates the decision tree from this node based on the given state. Returns the final action and records the decision path.

class decision_graph.decision_tree.NoAction(auto_connect: bool = True)[source]

Bases: ActionNode

__init__(auto_connect: bool = True)[source]

Initialize the LogicExpression.

Parameters:
  • action (Union[Any, Callable[[], Any]]) – The action to execute.

  • repr (str, optional) – A string representation of the expression.

  • auto_connect – auto-connect to the current active decision graph.

eval(enforce_dtype: bool = False) ActionNode[source]

Evaluate the expression.

class decision_graph.decision_tree.LongAction(sig: int = 1, auto_connect: bool = True)[source]

Bases: ActionNode

__init__(sig: int = 1, auto_connect: bool = True)[source]

Initialize the LogicExpression.

Parameters:
  • action (Union[Any, Callable[[], Any]]) – The action to execute.

  • repr (str, optional) – A string representation of the expression.

  • auto_connect – auto-connect to the current active decision graph.

eval(enforce_dtype: bool = False) ActionNode[source]

Evaluate the expression.

class decision_graph.decision_tree.ShortAction(sig: int = -1, auto_connect: bool = True)[source]

Bases: ActionNode

__init__(sig: int = -1, auto_connect: bool = True)[source]

Initialize the LogicExpression.

Parameters:
  • action (Union[Any, Callable[[], Any]]) – The action to execute.

  • repr (str, optional) – A string representation of the expression.

  • auto_connect – auto-connect to the current active decision graph.

eval(enforce_dtype: bool = False) ActionNode[source]

Evaluate the expression.

class decision_graph.decision_tree.RootLogicNode[source]

Bases: LogicNode

__init__()[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

append(expression: Self, edge_condition: Any = None)[source]

Adds a child node to the current node.

Parameters:
  • expression (LogicNode) – The child node.

  • edge_condition (Any, optional) – The condition for branching.

Raises:

ValueError – If no edge condition is provided.

property child: LogicNode
eval_recursively(**kwargs)[source]

Recursively evaluates the decision tree starting from this node.

Keyword Arguments:
  • path (list, optional) – Tracks the decision path during evaluation. Defaults to a new list.

  • default (Any, optional) – Fallback value if no matching condition is found.

Returns:

(final_value, decision_path)
  • final_value (Any): The evaluated result of the tree.

  • decision_path (list): The sequence of nodes traversed during evaluation.

Return type:

tuple

Raises:

ValueError – If no matching condition is found and no default value is provided.

to_html(with_group=True, dry_run=True, filename='decision_graph.html', **kwargs)[source]

Visualizes the decision tree using PyVis. If dry_run=True, shows structure without highlighting active path. If dry_run=False, evaluates the tree and highlights the decision path. If with_group=True, uses grouped logic view.

class decision_graph.decision_tree.ContextLogicExpression(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None, logic_group: LogicGroup = None)[source]

Bases: ContextLogicExpression, LogicNode

__init__(expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None, logic_group: LogicGroup = None)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

class decision_graph.decision_tree.AttrExpression(attr: str | int, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Bases: AttrExpression, ContextLogicExpression

__init__(attr: str | int, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

class decision_graph.decision_tree.MathExpression(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Bases: MathExpression, ContextLogicExpression

__init__(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

class decision_graph.decision_tree.ComparisonExpression(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Bases: ComparisonExpression, ContextLogicExpression

__init__(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

class decision_graph.decision_tree.LogicalExpression(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Bases: LogicalExpression, ContextLogicExpression

__init__(left: ContextLogicExpression | int | float, op: Operator, right: ContextLogicExpression | int | float = None, dtype: type = None, repr: str = None, logic_group: LogicGroup = None, edge_condition: Any = True)[source]

Initialize the LogicExpression.

Parameters:
  • expression (Union[Any, Callable[[], Any]]) – A callable or static value.

  • dtype (type, optional) – The expected type of the evaluated value (float, int, or bool).

  • repr (str, optional) – A string representation of the expression.

class decision_graph.decision_tree.LogicMapping(name, *args, **kwargs)[source]

Bases: ExpressionCollection

__init__(data: dict, name: str, logic_group: LogicGroup = None)[source]
clear()[source]
reset()[source]
update(data: dict = None, **kwargs)[source]
class decision_graph.decision_tree.LogicGenerator(name, *args, **kwargs)[source]

Bases: ExpressionCollection

__init__(data: list[Any], name: str, logic_group: LogicGroup = None)[source]
append(value)[source]
clear()[source]
remove(value)[source]