Skip to main content

coreason_engine/
policy_tree.rs

1// Copyright (c) 2026 CoReason, Inc
2//
3// This software is proprietary and dual-licensed
4// Licensed under the Prosperity Public License 3.0 (the "License")
5// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
6// For details, see the LICENSE file
7// Commercial use beyond a 30-day trial requires a separate license
8//
9// Source Code: <https://github.com/CoReason-AI/coreason-runtime>
10
11use petgraph::graph::{DiGraph, NodeIndex};
12
13use rayon::prelude::*;
14
15/// A node in the Active Inference policy tree representing a state/belief projection
16
17#[derive(Debug, Clone)]
18
19pub struct PolicyNode {
20    pub name: String,
21
22    pub expected_free_energy: f64,
23}
24
25/// Active Inference Policy Search Tree built on petgraph
26
27pub struct PolicySearchTree {
28    pub graph: DiGraph<PolicyNode, ()>,
29}
30
31impl PolicySearchTree {
32    /// Creates an empty policy tree
33
34    pub fn new() -> Self {
35        Self {
36            graph: DiGraph::new(),
37        }
38    }
39
40    /// Adds a policy belief node to the search tree
41
42    pub fn add_node(&mut self, name: &str, efe: f64) -> NodeIndex {
43        self.graph.add_node(PolicyNode {
44            name: name.to_string(),
45
46            expected_free_energy: efe,
47        })
48    }
49
50    /// Connects two belief states representing a temporal action transition
51
52    pub fn add_transition(&mut self, from: NodeIndex, to: NodeIndex) {
53        self.graph.add_edge(from, to, ());
54    }
55
56    /// Evaluates the cumulative Expected Free Energy (EFE) of all nodes in parallel
57
58    /// utilizing Rayon to leverage multi-threaded CPU substrates.
59
60    pub fn evaluate_tree_parallel(&self) -> f64 {
61        let raw_nodes: Vec<&PolicyNode> = self.graph.node_weights().collect();
62
63        raw_nodes
64            .par_iter()
65            .map(|node| node.expected_free_energy)
66            .sum()
67    }
68}