Skip to main content

flexible_operations/
flexible_operations.rs

1//! Demonstration of flexible operations with the single Operation trait
2//!
3//! This example shows how the same operation struct can implement the Operation trait
4//! multiple times for different input/output type combinations, enabling flexible
5//! multi-dispatch without needing separate traits or enums.
6//!
7//! Uses two value types: Number and Vector, demonstrating various operation combinations.
8
9use neal::{DerivedNode, Graph, GraphError, InputNode, NodeId, Operation};
10use std::hash::Hash;
11
12// Two value types for demonstration
13#[derive(Clone, PartialEq, Debug, Hash, Default)]
14struct Number(i32);
15
16#[derive(Clone, PartialEq, Debug, Hash, Default)]
17struct Vector(Vec<i32>);
18
19// A single Add operation struct that can handle different type combinations
20struct Add;
21
22// Implementation for Number + Number -> Number
23impl Operation<(Number, Number), Number> for Add {
24    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
25        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
26        let a = inputs[0].as_any().downcast_ref::<Number>().ok_or_else(|| {
27            GraphError::InvalidOperation("Expected Number for first input".into())
28        })?;
29        let b = inputs[1].as_any().downcast_ref::<Number>().ok_or_else(|| {
30            GraphError::InvalidOperation("Expected Number for second input".into())
31        })?;
32        Ok(Number(a.0 + b.0))
33    }
34
35    fn input_count(&self) -> Option<usize> {
36        Some(2)
37    }
38}
39
40// Implementation for Vector + Vector -> Vector
41impl Operation<(Vector, Vector), Vector> for Add {
42    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Vector, GraphError> {
43        <Self as Operation<(Vector, Vector), Vector>>::validate_inputs(self, inputs)?;
44        let a = inputs[0].as_any().downcast_ref::<Vector>().ok_or_else(|| {
45            GraphError::InvalidOperation("Expected Vector for first input".into())
46        })?;
47        let b = inputs[1].as_any().downcast_ref::<Vector>().ok_or_else(|| {
48            GraphError::InvalidOperation("Expected Vector for second input".into())
49        })?;
50
51        if a.0.len() != b.0.len() {
52            return Err(GraphError::InvalidOperation(
53                "Vectors must have same length".into(),
54            ));
55        }
56
57        let result: Vec<i32> = a.0.iter().zip(&b.0).map(|(x, y)| x + y).collect();
58        Ok(Vector(result))
59    }
60
61    fn input_count(&self) -> Option<usize> {
62        Some(2)
63    }
64}
65
66// A multiply operation that can handle different scalar/vector combinations
67struct Multiply;
68
69// Implementation for Number * Number -> Number
70impl Operation<(Number, Number), Number> for Multiply {
71    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
72        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
73        let a = inputs[0].as_any().downcast_ref::<Number>().ok_or_else(|| {
74            GraphError::InvalidOperation("Expected Number for first input".into())
75        })?;
76        let b = inputs[1].as_any().downcast_ref::<Number>().ok_or_else(|| {
77            GraphError::InvalidOperation("Expected Number for second input".into())
78        })?;
79        Ok(Number(a.0 * b.0))
80    }
81
82    fn input_count(&self) -> Option<usize> {
83        Some(2)
84    }
85}
86
87// Implementation for Number * Vector -> Vector (scalar multiplication)
88impl Operation<(Number, Vector), Vector> for Multiply {
89    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Vector, GraphError> {
90        <Self as Operation<(Number, Vector), Vector>>::validate_inputs(self, inputs)?;
91        let scalar = inputs[0].as_any().downcast_ref::<Number>().ok_or_else(|| {
92            GraphError::InvalidOperation("Expected Number for first input".into())
93        })?;
94        let vector = inputs[1].as_any().downcast_ref::<Vector>().ok_or_else(|| {
95            GraphError::InvalidOperation("Expected Vector for second input".into())
96        })?;
97
98        let result: Vec<i32> = vector.0.iter().map(|x| scalar.0 * x).collect();
99        Ok(Vector(result))
100    }
101
102    fn input_count(&self) -> Option<usize> {
103        Some(2)
104    }
105}
106
107fn main() -> Result<(), GraphError> {
108    println!("Flexible Operations Demo");
109    println!("========================");
110
111    let mut graph = Graph::new();
112
113    // Helper functions for creating derived nodes with explicit types
114    fn add_number_op(graph: &mut Graph, deps: Vec<NodeId>) -> neal::NodeHandle<Number> {
115        graph.add_node(DerivedNode::<Number>::new::<(Number, Number), Add>(
116            deps, Add,
117        ))
118    }
119
120    fn add_vector_op(graph: &mut Graph, deps: Vec<NodeId>) -> neal::NodeHandle<Vector> {
121        graph.add_node(DerivedNode::<Vector>::new::<(Vector, Vector), Add>(
122            deps, Add,
123        ))
124    }
125
126    fn multiply_number_op(graph: &mut Graph, deps: Vec<NodeId>) -> neal::NodeHandle<Number> {
127        graph.add_node(DerivedNode::<Number>::new::<(Number, Number), Multiply>(
128            deps, Multiply,
129        ))
130    }
131
132    fn scalar_vector_multiply_op(graph: &mut Graph, deps: Vec<NodeId>) -> neal::NodeHandle<Vector> {
133        graph.add_node(DerivedNode::<Vector>::new::<(Number, Vector), Multiply>(
134            deps, Multiply,
135        ))
136    }
137
138    // Number operations
139    println!("\n1. Number + Number:");
140    let n1 = graph.add_node(InputNode::new(Number(5)));
141    let n2 = graph.add_node(InputNode::new(Number(3)));
142    let sum_numbers = add_number_op(&mut graph, vec![n1.id(), n2.id()]);
143
144    graph.compute()?;
145    let result = graph
146        .get_value::<Number>(sum_numbers.id())
147        .ok_or_else(|| GraphError::InvalidOperation("Failed to get result".into()))?;
148    println!("   {} + {} = {}", 5, 3, result.0);
149
150    // Vector operations
151    println!("\n2. Vector + Vector:");
152    let v1 = graph.add_node(InputNode::new(Vector(vec![1, 2, 3])));
153    let v2 = graph.add_node(InputNode::new(Vector(vec![4, 5, 6])));
154    let sum_vectors = add_vector_op(&mut graph, vec![v1.id(), v2.id()]);
155
156    graph.compute()?;
157    let result = graph
158        .get_value::<Vector>(sum_vectors.id())
159        .ok_or_else(|| GraphError::InvalidOperation("Failed to get result".into()))?;
160    println!("   [1, 2, 3] + [4, 5, 6] = {:?}", result.0);
161
162    // Scalar * Vector operation
163    println!("\n3. Number * Vector:");
164    let scalar = graph.add_node(InputNode::new(Number(2)));
165    let vector = graph.add_node(InputNode::new(Vector(vec![1, 2, 3])));
166    let scaled = scalar_vector_multiply_op(&mut graph, vec![scalar.id(), vector.id()]);
167
168    graph.compute()?;
169    let result = graph
170        .get_value::<Vector>(scaled.id())
171        .ok_or_else(|| GraphError::InvalidOperation("Failed to get result".into()))?;
172    println!("   2 * [1, 2, 3] = {:?}", result.0);
173
174    // Number * Number operation
175    println!("\n4. Number * Number:");
176    let product = multiply_number_op(&mut graph, vec![n1.id(), n2.id()]);
177
178    graph.compute()?;
179    let result = graph
180        .get_value::<Number>(product.id())
181        .ok_or_else(|| GraphError::InvalidOperation("Failed to get result".into()))?;
182    println!("   {} * {} = {}", 5, 3, result.0);
183
184    println!("\nāœ“ All operations completed successfully!");
185    println!(
186        "āœ“ Single Operation trait handles multiple type combinations without wrapper structs!"
187    );
188    println!("āœ“ Same Add struct supports: Number+Number, Vector+Vector");
189    println!("āœ“ Same Multiply struct supports: Number*Number, Number*Vector");
190
191    Ok(())
192}