rust_fuzzylogic/
rulespace.rs

1use std::{borrow::Borrow, collections::HashMap, hash::Hash};
2
3use crate::{
4    aggregate::aggregation,
5    defuzz::defuzzification,
6    error::{self},
7    mamdani::Rule,
8    sampler::UniformSampler,
9    variable::Variable,
10    Float,
11};
12
13// Container for fuzzy variables, rules, and intermediate membership data.
14pub struct RuleSpace {
15    pub vars: HashMap<String, Variable>,
16    pub myu: HashMap<String, Vec<Float>>,
17    pub rules: Vec<Rule>,
18}
19
20impl RuleSpace {
21    /// Create a rule space with the supplied variables and rules.
22    pub fn new(self, vars: HashMap<String, Variable>, rules: Vec<Rule>) -> Self {
23        return Self {
24            vars: vars,
25            myu: HashMap::new(),
26            rules: rules,
27        };
28    }
29
30    /// Append additional rules to the existing rule set.
31    pub fn add_rules(mut self, rules: &mut Vec<Rule>) {
32        self.rules.append(rules);
33    }
34
35    /// Run the aggregation step for all rules with the provided crisp inputs.
36    pub fn aggregate<KI>(
37        &mut self,
38        input: &HashMap<KI, Float>,
39        sampler: UniformSampler,
40    ) -> error::Result<()>
41    where
42        KI: Eq + Hash + Borrow<str>,
43    {
44        let rules = std::mem::take(&mut self.rules);
45        let myu = aggregation(rules, input, &self.vars, sampler)?;
46        self.myu = myu;
47
48        Ok(())
49    }
50
51    /// Aggregate and then defuzzify each output variable using the supplied sampler.
52    pub fn defuzzificate<KI>(
53        &mut self,
54        input: &HashMap<KI, Float>,
55        sampler: UniformSampler,
56    ) -> crate::error::Result<HashMap<String, Float>>
57    where
58        KI: Eq + Hash + Borrow<str>,
59    {
60        let _ = self.aggregate(input, sampler);
61        let myu = std::mem::take(&mut self.myu);
62        Ok(defuzzification(myu, &self.vars)?)
63    }
64    //is there a nessecity?
65    //pub fn consequent_keys() {}
66}