Skip to main content

dtrees_rs/algorithms/greedy/lgdt/
builder.rs

1use crate::algorithms::common::config::BaseSearchConfig;
2use crate::algorithms::common::errors::NativeError;
3use crate::algorithms::greedy::lgdt::LGDT;
4use crate::algorithms::optimal::depth2::{ErrorMinimizer, InfoGainMaximizer, OptimalDepth2Tree};
5use crate::tree::Tree;
6
7/// Builder for [`LGDT`]. A depth-2 solver is required.
8///
9/// ```
10/// use dtrees_rs::algorithms::greedy::factories::with_error_minimizer;
11///
12/// let lgdt = with_error_minimizer().max_depth(5).min_support(5).build();
13/// assert!(lgdt.is_ok());
14/// ```
15pub struct LGDTBuilder<D>
16where
17    D: OptimalDepth2Tree + ?Sized,
18{
19    config: BaseSearchConfig,
20    search: Option<Box<D>>,
21}
22
23impl<D> Default for LGDTBuilder<D>
24where
25    D: OptimalDepth2Tree + ?Sized,
26{
27    fn default() -> Self {
28        Self {
29            config: BaseSearchConfig::default(),
30            search: None,
31        }
32    }
33}
34
35impl<D> LGDTBuilder<D>
36where
37    D: OptimalDepth2Tree + ?Sized,
38{
39    /// A builder whose lookahead maximises information gain.
40    pub fn with_default_info_gain_maximizer() -> LGDTBuilder<InfoGainMaximizer<NativeError>> {
41        LGDTBuilder::default().search(Box::<InfoGainMaximizer<NativeError>>::default())
42    }
43
44    /// A builder whose lookahead minimises the error.
45    pub fn with_default_error_minimizer() -> LGDTBuilder<ErrorMinimizer<NativeError>> {
46        LGDTBuilder::default().search(Box::<ErrorMinimizer<NativeError>>::default())
47    }
48
49    /// Minimum number of instances in each leaf.
50    pub fn min_support(mut self, value: usize) -> Self {
51        self.config.min_support = value;
52        self
53    }
54
55    /// Maximum depth of the tree.
56    pub fn max_depth(mut self, value: usize) -> Self {
57        self.config.max_depth = value;
58        self
59    }
60
61    /// Only trees with a lower error are accepted.
62    pub fn max_error(mut self, value: f64) -> Self {
63        self.config.max_error = value;
64        self
65    }
66
67    /// Time limit in seconds.
68    pub fn max_time(mut self, value: f64) -> Self {
69        self.config.max_time = value;
70        self
71    }
72
73    /// The depth-2 solver used for the lookahead.
74    pub fn search(mut self, value: Box<D>) -> Self {
75        self.search = Some(value);
76        self
77    }
78
79    /// Builds the learner, or says which required part is missing.
80    pub fn build(self) -> Result<LGDT<D>, String> {
81        let search = self
82            .search
83            .ok_or("Optimal Depth two Search algorithm is required")?;
84        Ok(LGDT {
85            search,
86            config: self.config,
87            tree: Tree::default(),
88        })
89    }
90}