neal 0.1.0-alpha.1

Simple, naive incremental dependency graphs. Don't use this. Not done.
Documentation
//! Basic equation example: (a + b) * c
//!
//! This example demonstrates the new observer-based API:
//! - Creating a graph with an observer
//! - Adding input and derived nodes dynamically
//! - Computing values through the graph
//! - Updating inputs and seeing changes propagate

use neal::{
    ComputationStats, DerivedNode, Graph, GraphError, InputNode, NodeId, NodeType, Observer,
    Operation,
};
use std::hash::Hash;

// Simple value type for numbers
#[derive(Clone, PartialEq, Debug, Hash, Default)]
struct Number(i32);

// Operations for our Number type
struct Add;
impl Operation<(Number, Number), Number> for Add {
    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
        let a = inputs[0]
            .as_any()
            .downcast_ref::<Number>()
            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
        let b = inputs[1]
            .as_any()
            .downcast_ref::<Number>()
            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
        Ok(Number(a.0 + b.0))
    }

    fn input_count(&self) -> Option<usize> {
        Some(2)
    }
}

struct Multiply;
impl Operation<(Number, Number), Number> for Multiply {
    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
        <Self as Operation<(Number, Number), Number>>::validate_inputs(self, inputs)?;
        let a = inputs[0]
            .as_any()
            .downcast_ref::<Number>()
            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
        let b = inputs[1]
            .as_any()
            .downcast_ref::<Number>()
            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
        Ok(Number(a.0 * b.0))
    }

    fn input_count(&self) -> Option<usize> {
        Some(2)
    }
}

// Simple console observer
struct ConsoleObserver;

impl Observer for ConsoleObserver {
    fn on_value_changed(&mut self, node_id: NodeId, _old: Option<u64>, _new: u64) {
        println!("Node {:?} value changed", node_id);
    }

    fn on_node_added(&mut self, node_id: NodeId, node_type: NodeType) {
        match node_type {
            NodeType::Input { value_type } => {
                println!("Added input node {:?} ({})", node_id, value_type)
            }
            NodeType::Derived {
                input_count,
                value_type,
            } => println!(
                "Added derived node {:?} ({}, {} inputs)",
                node_id, value_type, input_count
            ),
        }
    }

    fn on_node_removed(&mut self, node_id: NodeId) {
        println!("Removed node {:?}", node_id);
    }

    fn on_computation_started(&mut self) {
        println!("Computation started");
    }

    fn on_computation_finished(&mut self, stats: ComputationStats) {
        println!(
            "Computation finished: {} nodes processed in {:.2}ms",
            stats.nodes_processed, stats.duration_ms
        );
    }

    fn on_error(&mut self, error: &GraphError) {
        println!("Error: {}", error);
    }

    fn on_node_computation_started(&mut self, node_id: NodeId) {}

    fn on_node_computation_finished(&mut self, node_id: NodeId, success: bool) {}
}

fn main() -> Result<(), GraphError> {
    let mut graph = Graph::with_observer(ConsoleObserver);

    // Create input nodes using new API
    let a = graph.add_node(InputNode::new(Number(5)));
    let b = graph.add_node(InputNode::new(Number(3)));
    let c = graph.add_node(InputNode::new(Number(2)));

    // Create derived nodes: sum = a + b, result = sum * c
    let sum = graph.add_node(DerivedNode::new(vec![a.id(), b.id()], Add));

    let result = graph.add_node(DerivedNode::new(vec![sum.id(), c.id()], Multiply));

    // Compute and display result
    graph.compute()?;

    if let Some(value) = result.get_value(&graph) {
        println!("Result: (5 + 3) * 2 = {}", value.0);
    }

    // Update input and see change
    a.set_value(&mut graph, Number(10))?;
    graph.compute()?;

    if let Some(value) = result.get_value(&graph) {
        println!("Result: (10 + 3) * 2 = {}", value.0);
    }

    Ok(())
}