Skip to main content

Tree

Struct Tree 

Source
pub struct Tree<T> { /* private fields */ }
Expand description

A tree structure that represents a hierarchical collection of nodes.

The Tree struct is a fundamental data structure in Radiate’s genetic programming system. It provides a way to represent and manipulate tree-based expressions, where each node can have zero or more child nodes. The tree is rooted, meaning it has a single root node from which all other nodes descend.

§Type Parameters

  • T - The type of value stored in each node. This type must implement Clone, PartialEq, and other traits required by the genetic programming operations.

§Fields

  • root - An optional TreeNode<T> that serves as the root of the tree. When None, the tree is considered empty.

§Examples

use radiate_gp::{Tree, TreeNode, Op, Eval};

// Create a simple tree representing the expression (1 + 2) * 3
let tree = Tree::new(
    TreeNode::new(Op::mul())
        .attach(
            TreeNode::new(Op::add())
                .attach(TreeNode::new(Op::constant(1.0)))
                .attach(TreeNode::new(Op::constant(2.0)))
        )
        .attach(TreeNode::new(Op::constant(3.0)))
);

// Evaluate the tree
let result = tree.eval(&[]); // Evaluates to 9.0
assert_eq!(result, 9.0);

§Tree Creation

The struct provides several ways to create trees:

  • new() - Creates a tree with a given root node
  • with_depth() - Creates a tree of specified depth using nodes from a NodeStore
  • default() - Creates an empty tree

§Tree Operations

The struct provides methods for tree manipulation and traversal:

  • root() - Gets a reference to the root node
  • root_mut() - Gets a mutable reference to the root node
  • take_root() - Takes ownership of the root node
  • size() - Returns the total number of nodes in the tree
  • height() - Returns the height of the tree

§Tree Traversal

The struct implements the TreeIterator trait, providing three traversal methods:

  • iter_pre_order() - Traverses the tree in pre-order (root, then children)
  • iter_post_order() - Traverses the tree in post-order (children, then root)
  • iter_breadth_first() - Traverses the tree level by level

§Tree Building

The struct provides a builder pattern for creating trees of specific depths:

use radiate_gp::{Tree, NodeType, Op};

let store = vec![
    (NodeType::Vertex, vec![Op::add(), Op::sub(), Op::mul()]),
    (NodeType::Leaf, vec![Op::constant(1.0), Op::constant(2.0)]),
];

// Create a tree of depth 3
let tree = Tree::with_depth(3, store);
assert_eq!(tree.height(), 3);

§Tree Evaluation

When T implements the Eval trait, the tree can be evaluated with input data:

use radiate_gp::{Tree, TreeNode, Op, Eval};

let tree = Tree::new(
    TreeNode::new(Op::add())
        .attach(TreeNode::new(Op::var(0)))
        .attach(TreeNode::new(Op::constant(2.0)))
);

assert_eq!(tree.eval(&[1.0]), 3.0);
assert_eq!(tree.eval(&[2.0]), 4.0);

§Tree Properties

The tree maintains several important properties:

  • It is always rooted (has a single root node)
  • It is acyclic (no node is its own ancestor)
  • Each node can have zero or more children
  • The tree’s height is the length of the longest path from root to leaf
  • The tree’s size is the total number of nodes

§Implementation Details

The struct implements several traits:

  • Clone - Allows cloning of the entire tree structure
  • PartialEq - Enables equality comparison between trees
  • Default - Provides a way to create an empty tree
  • Debug - Provides debug formatting for the tree
  • AsRef<TreeNode<T>> - Allows treating the tree as a reference to its root node
  • AsMut<TreeNode<T>> - Allows treating the tree as a mutable reference to its root node

§Genetic Programming

The Tree struct is particularly useful in genetic programming as it can represent:

  • Mathematical expressions
  • Program syntax trees
  • Decision trees
  • Other hierarchical structures

Implementations§

Source§

impl<T: Clone + Default> Tree<T>

Source

pub fn with_depth(depth: usize, nodes: impl Into<NodeStore<T>>) -> Self

Create a tree with the given depth, where each node is a random node from the node store. This obeys the rules of the NodeStore’s NodeType’s arity, and will create a tree that is as balanced as possible.

Note that the root node will try to be a NodeType::Root if it is available in the NodeStore, otherwise it will be a NodeType::Vertex. This allows caller’s to specify what the root node is if desired, otherwise it will be a random vertex node from the NodeStore.

§The NodeStore must contain at least one NodeType::Root or one NodeType::Vertex
§Arguments
  • depth - The depth of the tree.
  • nodes - The node store to use for the tree.
§Returns

A tree with the given depth, where each node is a random node from the node store.

Source§

impl<T> Tree<T>

Source

pub fn new(root: impl Into<TreeNode<T>>) -> Self

Source

pub fn root(&self) -> Option<&TreeNode<T>>

Source

pub fn root_mut(&mut self) -> Option<&mut TreeNode<T>>

Source

pub fn take_root(self) -> Option<TreeNode<T>>

Source

pub fn size(&self) -> usize

Source

pub fn height(&self) -> usize

Trait Implementations§

Source§

impl<T> AsMut<TreeNode<T>> for Tree<T>

Source§

fn as_mut(&mut self) -> &mut TreeNode<T>

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<T> AsRef<TreeNode<T>> for Tree<T>

Source§

fn as_ref(&self) -> &TreeNode<T>

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<F> BatchFitnessFunction<Tree<Op<F>>, F> for Regression<F>
where F: OpFloat + Into<Score>,

Source§

fn evaluate(&self, inputs: Vec<Tree<Op<F>>>) -> Vec<F>

Source§

impl<T: Clone> Clone for Tree<T>

Source§

fn clone(&self) -> Tree<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Codec<TreeChromosome<T>, Tree<T>> for TreeCodec<T, Tree<T>>
where T: Clone + PartialEq + Default,

Source§

fn encode(&self) -> Genotype<TreeChromosome<T>>

Source§

fn decode(&self, genotype: &Genotype<TreeChromosome<T>>) -> Tree<T>

Source§

impl<T: Debug> Debug for Tree<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for Tree<T>

Source§

fn default() -> Tree<T>

Returns the “default value” for a type. Read more
Source§

impl<T: OpFloat> Eval<Tree<Op<T>>, Option<AccuracyResult>> for Accuracy<'_, T>

Source§

fn eval(&self, tree: &Tree<Op<T>>) -> Option<AccuracyResult>

Source§

impl<T, V> Eval<[V], V> for Tree<T>
where T: Eval<[V], V>, V: Clone,

Implements the Eval trait for Tree<T> where T is Eval<[V], V>. All this really does is call the eval method on the root node of the Tree. The real work is done in the TreeNode implementation below.

Source§

fn eval(&self, input: &[V]) -> V

Source§

impl<T, V> EvalInto<[V], [V]> for Tree<T>
where T: Eval<[V], V>, V: Clone,

Source§

fn eval_into(&self, input: &[V], buffer: &mut [V])

Source§

impl<T, V> EvalMut<[V], Vec<V>> for Tree<T>
where T: Eval<[V], V>, V: Clone + Default,

Source§

fn eval_mut(&mut self, input: &[V]) -> Vec<V>

Source§

impl<F> FitnessFunction<Tree<Op<F>>, F> for Regression<F>
where F: OpFloat + Into<Score>,

— Trees —

Source§

fn evaluate(&self, input: Tree<Op<F>>) -> F

Source§

impl<T: Debug> Format for Tree<T>

Source§

fn format(&self) -> String

Source§

impl<T: Hash> Hash for Tree<T>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T: PartialEq> PartialEq for Tree<T>

Source§

fn eq(&self, other: &Tree<T>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T: PartialEq> StructuralPartialEq for Tree<T>

Source§

impl<T> ToDot for Tree<T>
where T: Display,

Source§

fn to_dot(&self) -> String

Source§

impl<T> TreeIterator<T> for Tree<T>

Implement the TreeIterator trait for Tree

This allows for traversal of the entire tree in pre-order, post-order, and breadth-first order.

Source§

fn iter_pre_order(&self) -> PreOrderIterator<'_, T>

Source§

fn iter_post_order(&self) -> PostOrderIterator<'_, T>

Source§

fn iter_breadth_first(&self) -> TreeBreadthFirstIterator<'_, T>

Source§

fn apply<F: Fn(&mut TreeNode<T>)>(&mut self, visit_fn: F)

Auto Trait Implementations§

§

impl<T> Freeze for Tree<T>
where Option<TreeNode<T>>: Freeze,

§

impl<T> RefUnwindSafe for Tree<T>

§

impl<T> Send for Tree<T>
where Option<TreeNode<T>>: Send,

§

impl<T> Sync for Tree<T>
where Option<TreeNode<T>>: Sync,

§

impl<T> Unpin for Tree<T>
where Option<TreeNode<T>>: Unpin,

§

impl<T> UnsafeUnpin for Tree<T>

§

impl<T> UnwindSafe for Tree<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<I, O, T> EvalIntoMut<I, O> for T
where T: EvalInto<I, O>, I: ?Sized, O: ?Sized,

Source§

fn eval_into_mut(&mut self, input: &I, buffer: &mut O)

Source§

impl<I, O, T> EvalMut<I, O> for T
where T: Eval<I, O>, I: ?Sized,

Source§

fn eval_mut(&mut self, input: &I) -> O

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.