avila_math/autograd/
variable.rs

1//! Variable type for automatic differentiation
2
3use std::cell::RefCell;
4use std::rc::Rc;
5
6/// A variable in the computational graph
7#[derive(Debug, Clone)]
8pub struct Variable {
9    pub(crate) id: usize,
10    pub(crate) value: Rc<RefCell<f64>>,
11}
12
13impl Variable {
14    pub(crate) fn new(id: usize, value: f64) -> Self {
15        Self {
16            id,
17            value: Rc::new(RefCell::new(value)),
18        }
19    }
20
21    /// Get the current value
22    pub fn value(&self) -> f64 {
23        *self.value.borrow()
24    }
25
26    /// Get the variable ID
27    pub fn id(&self) -> usize {
28        self.id
29    }
30
31    /// Set the value (for tape operations)
32    #[allow(dead_code)]
33    pub(crate) fn set_value(&self, val: f64) {
34        *self.value.borrow_mut() = val;
35    }
36}
37
38impl PartialEq for Variable {
39    fn eq(&self, other: &Self) -> bool {
40        self.id == other.id
41    }
42}
43
44impl Eq for Variable {}
45
46impl std::hash::Hash for Variable {
47    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
48        self.id.hash(state);
49    }
50}