Skip to main content

contree/data/
mod.rs

1use std::cmp::Ordering;
2use std::ops::{Index, IndexMut};
3
4mod dataset;
5pub mod view;
6
7pub use dataset::{Dataset, DatasetError};
8
9/// One observation of one feature: the instance id, its value and its label.
10#[derive(Copy, Clone, Debug)]
11pub struct DataPoint {
12    tid: usize,
13    value: f64,
14    unique_value_idx: usize,
15    label: f64,
16}
17
18impl DataPoint {
19    /// An observation of instance `tid`, not yet indexed.
20    pub fn new(tid: usize, value: f64, label: f64) -> Self {
21        Self {
22            tid,
23            value,
24            unique_value_idx: usize::MAX,
25            label,
26        }
27    }
28
29    pub fn tid(&self) -> usize {
30        self.tid
31    }
32
33    pub fn value(&self) -> f64 {
34        self.value
35    }
36
37    pub fn label(&self) -> f64 {
38        self.label
39    }
40
41    /// Sets the index of the value among the column's distinct values.
42    pub fn set_unique_value_id(&mut self, value: usize) {
43        self.unique_value_idx = value
44    }
45
46    /// The index of the value among the column's distinct values.
47    pub fn unique_value_id(&self) -> usize {
48        self.unique_value_idx
49    }
50}
51
52impl PartialEq for DataPoint {
53    fn eq(&self, other: &Self) -> bool {
54        self.value == other.value
55    }
56}
57
58impl Eq for DataPoint {}
59
60impl PartialOrd for DataPoint {
61    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
62        Some(self.cmp(other))
63    }
64}
65
66impl Ord for DataPoint {
67    fn cmp(&self, other: &Self) -> Ordering {
68        self.value.total_cmp(&other.value)
69    }
70}
71
72/// One column of the dataset: every observation of a single feature, kept
73/// sorted by value so that split candidates are consecutive positions.
74#[derive(Debug, Default)]
75pub struct Feature {
76    elements: Vec<DataPoint>,
77}
78
79impl Feature {
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    pub fn sort(&mut self) {
85        self.elements.sort()
86    }
87
88    pub fn insert(&mut self, data_point: DataPoint) {
89        self.elements.push(data_point);
90    }
91
92    pub fn len(&self) -> usize {
93        self.elements.len()
94    }
95
96    pub fn is_empty(&self) -> bool {
97        self.elements.is_empty()
98    }
99}
100
101impl Index<usize> for Feature {
102    type Output = DataPoint;
103
104    fn index(&self, index: usize) -> &Self::Output {
105        &self.elements[index]
106    }
107}
108
109impl IndexMut<usize> for Feature {
110    fn index_mut(&mut self, index: usize) -> &mut DataPoint {
111        &mut self.elements[index]
112    }
113}