Skip to main content

basic_equation/
basic_equation.rs

1//! Basic equation example: (a + b) * c
2//!
3//! This example demonstrates the new observer-based API:
4//! - Creating a graph with an observer
5//! - Adding input and derived nodes dynamically
6//! - Computing values through the graph
7//! - Updating inputs and seeing changes propagate
8
9use neal::{
10    ComputationStats, DerivedNode, Graph, GraphError, InputNode, NodeId, NodeType, Observer,
11    Operation,
12};
13use std::hash::Hash;
14
15// Simple value type for numbers
16#[derive(Clone, PartialEq, Debug, Hash, Default)]
17struct Number(i32);
18
19// Operations for our Number type
20struct Add;
21impl Operation<(Number, Number), Number> for Add {
22    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
23        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
24        let a = inputs[0]
25            .as_any()
26            .downcast_ref::<Number>()
27            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
28        let b = inputs[1]
29            .as_any()
30            .downcast_ref::<Number>()
31            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
32        Ok(Number(a.0 + b.0))
33    }
34
35    fn input_count(&self) -> Option<usize> {
36        Some(2)
37    }
38}
39
40struct Multiply;
41impl Operation<(Number, Number), Number> for Multiply {
42    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
43        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
44        let a = inputs[0]
45            .as_any()
46            .downcast_ref::<Number>()
47            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
48        let b = inputs[1]
49            .as_any()
50            .downcast_ref::<Number>()
51            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
52        Ok(Number(a.0 * b.0))
53    }
54
55    fn input_count(&self) -> Option<usize> {
56        Some(2)
57    }
58}
59
60// Simple console observer
61struct ConsoleObserver;
62
63impl Observer for ConsoleObserver {
64    fn on_value_changed(&mut self, node_id: NodeId, _old: Option<u64>, _new: u64) {
65        println!("Node {:?} value changed", node_id);
66    }
67
68    fn on_node_added(&mut self, node_id: NodeId, node_type: NodeType) {
69        match node_type {
70            NodeType::Input { value_type } => {
71                println!("Added input node {:?} ({})", node_id, value_type)
72            }
73            NodeType::Derived {
74                input_count,
75                value_type,
76            } => println!(
77                "Added derived node {:?} ({}, {} inputs)",
78                node_id, value_type, input_count
79            ),
80        }
81    }
82
83    fn on_node_removed(&mut self, node_id: NodeId) {
84        println!("Removed node {:?}", node_id);
85    }
86
87    fn on_computation_started(&mut self) {
88        println!("Computation started");
89    }
90
91    fn on_computation_finished(&mut self, stats: ComputationStats) {
92        println!(
93            "Computation finished: {} nodes processed in {:.2}ms",
94            stats.nodes_processed, stats.duration_ms
95        );
96    }
97
98    fn on_error(&mut self, error: &GraphError) {
99        println!("Error: {}", error);
100    }
101
102    fn on_node_computation_started(&mut self, node_id: NodeId) {}
103
104    fn on_node_computation_finished(&mut self, node_id: NodeId, success: bool) {}
105}
106
107fn main() -> Result<(), GraphError> {
108    let mut graph = Graph::with_observer(ConsoleObserver);
109
110    // Create input nodes using new API
111    let a = graph.add_node(InputNode::new(Number(5)));
112    let b = graph.add_node(InputNode::new(Number(3)));
113    let c = graph.add_node(InputNode::new(Number(2)));
114
115    // Create derived nodes: sum = a + b, result = sum * c
116    let sum = graph.add_node(DerivedNode::new(vec![a.id(), b.id()], Add));
117
118    let result = graph.add_node(DerivedNode::new(vec![sum.id(), c.id()], Multiply));
119
120    // Compute and display result
121    graph.compute()?;
122
123    if let Some(value) = result.get_value(&graph) {
124        println!("Result: (5 + 3) * 2 = {}", value.0);
125    }
126
127    // Update input and see change
128    a.set_value(&mut graph, Number(10))?;
129    graph.compute()?;
130
131    if let Some(value) = result.get_value(&graph) {
132        println!("Result: (10 + 3) * 2 = {}", value.0);
133    }
134
135    Ok(())
136}