Skip to main content

oxirs_rule/
fuzzy.rs

1//! # Fuzzy Logic Reasoning Module
2//!
3//! This module provides fuzzy logic reasoning capabilities for handling
4//! vague and uncertain knowledge in rule-based systems.
5//!
6//! ## Features
7//!
8//! - **Fuzzy Sets**: Membership functions (triangular, trapezoidal, gaussian)
9//! - **Fuzzy Rules**: IF-THEN rules with fuzzy predicates
10//! - **Fuzzy Inference**: Mamdani and Sugeno inference systems
11//! - **Defuzzification**: Centroid, bisector, mean of maximum methods
12//! - **Fuzzy Ontologies**: OWL ontologies with fuzzy concepts
13//!
14//! ## Example
15//!
16//! ```text
17//! use oxirs_rule::fuzzy::*;
18//!
19//! // Create a fuzzy set for "tall"
20//! let tall = FuzzySet::new(
21//!     "tall".to_string(),
22//!     MembershipFunction::Triangular { a: 160.0, b: 180.0, c: 200.0 }
23//! );
24//!
25//! // Check membership degree
26//! let degree = tall.membership(175.0);
27//! assert!(degree > 0.5 && degree < 1.0);
28//!
29//! // Create fuzzy rules
30//! let mut system = MamdaniFuzzySystem::new();
31//! system.add_input_variable("height".to_string(), 0.0, 220.0);
32//! system.add_output_variable("category".to_string(), 0.0, 10.0);
33//!
34//! // Add a fuzzy rule: IF height is tall THEN category is high
35//! system.add_rule(FuzzyRule {
36//!     antecedents: vec![("height".to_string(), "tall".to_string())],
37//!     consequents: vec![("category".to_string(), "high".to_string())],
38//!     weight: 1.0,
39//! });
40//!
41//! // Perform inference
42//! let result = system.infer(&[("height".to_string(), 175.0)]).expect("should succeed");
43//! # Ok::<(), anyhow::Error>(())
44//! ```
45
46use crate::{Rule, RuleAtom, Term};
47use anyhow::{anyhow, Result};
48use scirs2_core::ndarray_ext::Array1;
49use std::collections::HashMap;
50
51/// Membership function types for fuzzy sets
52#[derive(Debug, Clone)]
53pub enum MembershipFunction {
54    /// Triangular membership function: μ(x) = max(min((x-a)/(b-a), (c-x)/(c-b)), 0)
55    Triangular { a: f64, b: f64, c: f64 },
56    /// Trapezoidal membership function
57    Trapezoidal { a: f64, b: f64, c: f64, d: f64 },
58    /// Gaussian membership function: μ(x) = exp(-((x-c)^2)/(2*σ^2))
59    Gaussian { center: f64, sigma: f64 },
60    /// Sigmoid membership function: μ(x) = 1/(1 + exp(-a(x-c)))
61    Sigmoid { a: f64, c: f64 },
62    /// Singleton (crisp value)
63    Singleton { value: f64 },
64}
65
66impl MembershipFunction {
67    /// Compute membership degree for a given value
68    pub fn membership(&self, x: f64) -> f64 {
69        match self {
70            MembershipFunction::Triangular { a, b, c } => {
71                if x <= *a || x >= *c {
72                    0.0
73                } else if x <= *b {
74                    (x - a) / (b - a)
75                } else {
76                    (c - x) / (c - b)
77                }
78            }
79            MembershipFunction::Trapezoidal { a, b, c, d } => {
80                if x <= *a || x >= *d {
81                    0.0
82                } else if x >= *b && x <= *c {
83                    1.0
84                } else if x < *b {
85                    (x - a) / (b - a)
86                } else {
87                    (d - x) / (d - c)
88                }
89            }
90            MembershipFunction::Gaussian { center, sigma } => {
91                let exp_arg = -((x - center).powi(2)) / (2.0 * sigma.powi(2));
92                exp_arg.exp()
93            }
94            MembershipFunction::Sigmoid { a, c } => 1.0 / (1.0 + (-a * (x - c)).exp()),
95            MembershipFunction::Singleton { value } => {
96                if (x - value).abs() < 1e-10 {
97                    1.0
98                } else {
99                    0.0
100                }
101            }
102        }
103    }
104}
105
106/// Fuzzy set with a name and membership function
107#[derive(Debug, Clone)]
108pub struct FuzzySet {
109    /// Name of the fuzzy set
110    pub name: String,
111    /// Membership function
112    pub function: MembershipFunction,
113}
114
115impl FuzzySet {
116    /// Create a new fuzzy set
117    pub fn new(name: String, function: MembershipFunction) -> Self {
118        Self { name, function }
119    }
120
121    /// Get membership degree for a value
122    pub fn membership(&self, x: f64) -> f64 {
123        self.function.membership(x)
124    }
125
126    /// Get the support (values where membership > 0)
127    pub fn support(&self, min: f64, max: f64, num_points: usize) -> Vec<f64> {
128        let step = (max - min) / (num_points as f64);
129        (0..num_points)
130            .map(|i| min + step * (i as f64))
131            .filter(|&x| self.membership(x) > 1e-10)
132            .collect()
133    }
134
135    /// Get the core (values where membership = 1)
136    pub fn core(&self, min: f64, max: f64, num_points: usize) -> Vec<f64> {
137        let step = (max - min) / (num_points as f64);
138        (0..num_points)
139            .map(|i| min + step * (i as f64))
140            .filter(|&x| (self.membership(x) - 1.0).abs() < 1e-10)
141            .collect()
142    }
143}
144
145/// Fuzzy rule with antecedents and consequents
146#[derive(Debug, Clone)]
147pub struct FuzzyRule {
148    /// Antecedents: (variable, fuzzy_set_name)
149    pub antecedents: Vec<(String, String)>,
150    /// Consequents: (variable, fuzzy_set_name)
151    pub consequents: Vec<(String, String)>,
152    /// Rule weight (default: 1.0)
153    pub weight: f64,
154}
155
156/// Fuzzy variable with domain and associated fuzzy sets
157#[derive(Debug, Clone)]
158pub struct FuzzyVariable {
159    /// Variable name
160    pub name: String,
161    /// Minimum value
162    pub min: f64,
163    /// Maximum value
164    pub max: f64,
165    /// Associated fuzzy sets
166    pub fuzzy_sets: HashMap<String, FuzzySet>,
167}
168
169impl FuzzyVariable {
170    /// Create a new fuzzy variable
171    pub fn new(name: String, min: f64, max: f64) -> Self {
172        Self {
173            name,
174            min,
175            max,
176            fuzzy_sets: HashMap::new(),
177        }
178    }
179
180    /// Add a fuzzy set to this variable
181    pub fn add_fuzzy_set(&mut self, fuzzy_set: FuzzySet) {
182        self.fuzzy_sets.insert(fuzzy_set.name.clone(), fuzzy_set);
183    }
184
185    /// Get membership degree for a value in a specific fuzzy set
186    pub fn membership(&self, fuzzy_set_name: &str, value: f64) -> Result<f64> {
187        self.fuzzy_sets
188            .get(fuzzy_set_name)
189            .map(|fs| fs.membership(value))
190            .ok_or_else(|| anyhow!("Fuzzy set {} not found", fuzzy_set_name))
191    }
192}
193
194/// Mamdani-style fuzzy inference system
195#[derive(Debug, Clone)]
196pub struct MamdaniFuzzySystem {
197    /// Input variables
198    input_variables: HashMap<String, FuzzyVariable>,
199    /// Output variables
200    output_variables: HashMap<String, FuzzyVariable>,
201    /// Fuzzy rules
202    rules: Vec<FuzzyRule>,
203    /// T-norm (AND operation): min, product, lukasiewicz
204    t_norm: TNorm,
205    /// T-conorm (OR operation): max, probabilistic_sum
206    t_conorm: TConorm,
207    /// Defuzzification method
208    defuzz_method: DefuzzificationMethod,
209}
210
211/// T-norm (fuzzy AND)
212#[derive(Debug, Clone, Copy)]
213pub enum TNorm {
214    /// Minimum: min(a, b)
215    Min,
216    /// Product: a * b
217    Product,
218    /// Lukasiewicz: max(0, a + b - 1)
219    Lukasiewicz,
220}
221
222impl TNorm {
223    /// Apply the T-norm
224    pub fn apply(&self, a: f64, b: f64) -> f64 {
225        match self {
226            TNorm::Min => a.min(b),
227            TNorm::Product => a * b,
228            TNorm::Lukasiewicz => (a + b - 1.0).max(0.0),
229        }
230    }
231}
232
233/// T-conorm (fuzzy OR)
234#[derive(Debug, Clone, Copy)]
235pub enum TConorm {
236    /// Maximum: max(a, b)
237    Max,
238    /// Probabilistic sum: a + b - a*b
239    ProbabilisticSum,
240}
241
242impl TConorm {
243    /// Apply the T-conorm
244    pub fn apply(&self, a: f64, b: f64) -> f64 {
245        match self {
246            TConorm::Max => a.max(b),
247            TConorm::ProbabilisticSum => a + b - a * b,
248        }
249    }
250}
251
252/// Defuzzification method
253#[derive(Debug, Clone, Copy)]
254pub enum DefuzzificationMethod {
255    /// Centroid (center of gravity)
256    Centroid,
257    /// Bisector (divides area in half)
258    Bisector,
259    /// Mean of maximum
260    MeanOfMaximum,
261    /// Smallest of maximum
262    SmallestOfMaximum,
263    /// Largest of maximum
264    LargestOfMaximum,
265}
266
267impl MamdaniFuzzySystem {
268    /// Create a new Mamdani fuzzy system
269    pub fn new() -> Self {
270        Self {
271            input_variables: HashMap::new(),
272            output_variables: HashMap::new(),
273            rules: Vec::new(),
274            t_norm: TNorm::Min,
275            t_conorm: TConorm::Max,
276            defuzz_method: DefuzzificationMethod::Centroid,
277        }
278    }
279
280    /// Add an input variable
281    pub fn add_input_variable(&mut self, name: String, min: f64, max: f64) {
282        let var = FuzzyVariable::new(name.clone(), min, max);
283        self.input_variables.insert(name, var);
284    }
285
286    /// Add an output variable
287    pub fn add_output_variable(&mut self, name: String, min: f64, max: f64) {
288        let var = FuzzyVariable::new(name.clone(), min, max);
289        self.output_variables.insert(name, var);
290    }
291
292    /// Add a fuzzy set to an input variable
293    pub fn add_input_fuzzy_set(&mut self, var_name: &str, fuzzy_set: FuzzySet) -> Result<()> {
294        self.input_variables
295            .get_mut(var_name)
296            .ok_or_else(|| anyhow!("Input variable {} not found", var_name))?
297            .add_fuzzy_set(fuzzy_set);
298        Ok(())
299    }
300
301    /// Add a fuzzy set to an output variable
302    pub fn add_output_fuzzy_set(&mut self, var_name: &str, fuzzy_set: FuzzySet) -> Result<()> {
303        self.output_variables
304            .get_mut(var_name)
305            .ok_or_else(|| anyhow!("Output variable {} not found", var_name))?
306            .add_fuzzy_set(fuzzy_set);
307        Ok(())
308    }
309
310    /// Add a fuzzy rule
311    pub fn add_rule(&mut self, rule: FuzzyRule) {
312        self.rules.push(rule);
313    }
314
315    /// Set T-norm
316    pub fn set_t_norm(&mut self, t_norm: TNorm) {
317        self.t_norm = t_norm;
318    }
319
320    /// Set T-conorm
321    pub fn set_t_conorm(&mut self, t_conorm: TConorm) {
322        self.t_conorm = t_conorm;
323    }
324
325    /// Set defuzzification method
326    pub fn set_defuzzification_method(&mut self, method: DefuzzificationMethod) {
327        self.defuzz_method = method;
328    }
329
330    /// Perform fuzzy inference
331    pub fn infer(&self, inputs: &[(String, f64)]) -> Result<HashMap<String, f64>> {
332        // Step 1: Fuzzification - compute membership degrees for inputs
333        let mut input_memberships: HashMap<String, HashMap<String, f64>> = HashMap::new();
334
335        for (var_name, value) in inputs {
336            let var = self
337                .input_variables
338                .get(var_name)
339                .ok_or_else(|| anyhow!("Input variable {} not found", var_name))?;
340
341            let mut memberships = HashMap::new();
342            for (fs_name, fuzzy_set) in &var.fuzzy_sets {
343                memberships.insert(fs_name.clone(), fuzzy_set.membership(*value));
344            }
345            input_memberships.insert(var_name.clone(), memberships);
346        }
347
348        // Step 2: Rule evaluation - compute firing strength for each rule
349        let mut output_fuzzy_values: HashMap<String, Vec<(String, f64)>> = HashMap::new();
350
351        for rule in &self.rules {
352            // Compute antecedent firing strength using T-norm (AND)
353            let mut firing_strength = 1.0;
354            for (var_name, fs_name) in &rule.antecedents {
355                let membership = input_memberships
356                    .get(var_name)
357                    .and_then(|m| m.get(fs_name))
358                    .copied()
359                    .unwrap_or(0.0);
360                firing_strength = self.t_norm.apply(firing_strength, membership);
361            }
362
363            // Apply rule weight
364            firing_strength *= rule.weight;
365
366            // Apply to consequents
367            for (var_name, fs_name) in &rule.consequents {
368                output_fuzzy_values
369                    .entry(var_name.clone())
370                    .or_default()
371                    .push((fs_name.clone(), firing_strength));
372            }
373        }
374
375        // Step 3: Aggregation and Defuzzification
376        let mut results = HashMap::new();
377
378        for (var_name, fuzzy_values) in output_fuzzy_values {
379            let output_var = self
380                .output_variables
381                .get(&var_name)
382                .ok_or_else(|| anyhow!("Output variable {} not found", var_name))?;
383
384            // Build aggregated fuzzy output
385            let num_points = 1000;
386            let step = (output_var.max - output_var.min) / (num_points as f64);
387
388            let mut aggregated_membership = vec![0.0; num_points];
389
390            for (i, agg_mem) in aggregated_membership.iter_mut().enumerate() {
391                let x = output_var.min + step * (i as f64);
392
393                for (fs_name, firing_strength) in &fuzzy_values {
394                    let fs = output_var
395                        .fuzzy_sets
396                        .get(fs_name)
397                        .ok_or_else(|| anyhow!("Fuzzy set {} not found", fs_name))?;
398
399                    let membership = fs.membership(x).min(*firing_strength);
400                    *agg_mem = self.t_conorm.apply(*agg_mem, membership);
401                }
402            }
403
404            // Defuzzify
405            let crisp_value = self.defuzzify(
406                &Array1::from_vec(aggregated_membership),
407                output_var.min,
408                output_var.max,
409            )?;
410
411            results.insert(var_name, crisp_value);
412        }
413
414        Ok(results)
415    }
416
417    /// Defuzzify an aggregated fuzzy output
418    fn defuzzify(&self, membership: &Array1<f64>, min: f64, max: f64) -> Result<f64> {
419        let num_points = membership.len();
420        let step = (max - min) / (num_points as f64);
421
422        match self.defuzz_method {
423            DefuzzificationMethod::Centroid => {
424                // Centroid: ∫ x * μ(x) dx / ∫ μ(x) dx
425                let mut numerator = 0.0;
426                let mut denominator = 0.0;
427
428                for i in 0..num_points {
429                    let x = min + step * (i as f64);
430                    numerator += x * membership[i];
431                    denominator += membership[i];
432                }
433
434                if denominator < 1e-10 {
435                    return Err(anyhow!("Cannot defuzzify: membership sum is zero"));
436                }
437
438                Ok(numerator / denominator)
439            }
440            DefuzzificationMethod::MeanOfMaximum => {
441                // Find maximum membership degree
442                let max_membership = membership
443                    .iter()
444                    .copied()
445                    .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
446                    .unwrap_or(0.0);
447
448                if max_membership < 1e-10 {
449                    return Err(anyhow!("Cannot defuzzify: max membership is zero"));
450                }
451
452                // Find all indices with maximum membership
453                let max_indices: Vec<usize> = membership
454                    .iter()
455                    .enumerate()
456                    .filter(|(_, &m)| (m - max_membership).abs() < 1e-10)
457                    .map(|(i, _)| i)
458                    .collect();
459
460                // Return mean of maximum values
461                let sum: f64 = max_indices.iter().map(|&i| min + step * (i as f64)).sum();
462                Ok(sum / (max_indices.len() as f64))
463            }
464            DefuzzificationMethod::SmallestOfMaximum => {
465                let max_membership = membership
466                    .iter()
467                    .copied()
468                    .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
469                    .unwrap_or(0.0);
470
471                if max_membership < 1e-10 {
472                    return Err(anyhow!("Cannot defuzzify: max membership is zero"));
473                }
474
475                membership
476                    .iter()
477                    .enumerate()
478                    .find(|(_, &m)| (m - max_membership).abs() < 1e-10)
479                    .map(|(i, _)| min + step * (i as f64))
480                    .ok_or_else(|| anyhow!("Cannot find maximum"))
481            }
482            DefuzzificationMethod::LargestOfMaximum => {
483                let max_membership = membership
484                    .iter()
485                    .copied()
486                    .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
487                    .unwrap_or(0.0);
488
489                if max_membership < 1e-10 {
490                    return Err(anyhow!("Cannot defuzzify: max membership is zero"));
491                }
492
493                membership
494                    .iter()
495                    .enumerate()
496                    .rev()
497                    .find(|(_, &m)| (m - max_membership).abs() < 1e-10)
498                    .map(|(i, _)| min + step * (i as f64))
499                    .ok_or_else(|| anyhow!("Cannot find maximum"))
500            }
501            DefuzzificationMethod::Bisector => {
502                // Find area under curve
503                let total_area: f64 = membership.iter().sum::<f64>() * step;
504                let half_area = total_area / 2.0;
505
506                // Find x where area to the left equals half the total area
507                let mut cumulative_area = 0.0;
508                for i in 0..num_points {
509                    cumulative_area += membership[i] * step;
510                    if cumulative_area >= half_area {
511                        return Ok(min + step * (i as f64));
512                    }
513                }
514
515                Err(anyhow!("Cannot compute bisector"))
516            }
517        }
518    }
519}
520
521impl Default for MamdaniFuzzySystem {
522    fn default() -> Self {
523        Self::new()
524    }
525}
526
527/// Fuzzy rule engine integrating fuzzy logic with standard rules
528#[derive(Debug)]
529pub struct FuzzyRuleEngine {
530    /// Mamdani fuzzy system
531    fuzzy_system: MamdaniFuzzySystem,
532    /// Mapping from standard rules to fuzzy rules
533    rule_mapping: HashMap<String, FuzzyRule>,
534}
535
536impl FuzzyRuleEngine {
537    /// Create a new fuzzy rule engine
538    pub fn new() -> Self {
539        Self {
540            fuzzy_system: MamdaniFuzzySystem::new(),
541            rule_mapping: HashMap::new(),
542        }
543    }
544
545    /// Add a fuzzy rule from a standard rule
546    pub fn add_fuzzy_rule(&mut self, rule: Rule, fuzzy_rule: FuzzyRule) {
547        self.rule_mapping
548            .insert(rule.name.clone(), fuzzy_rule.clone());
549        self.fuzzy_system.add_rule(fuzzy_rule);
550    }
551
552    /// Infer with fuzzy logic
553    pub fn fuzzy_infer(&self, inputs: &[(String, f64)]) -> Result<HashMap<String, f64>> {
554        self.fuzzy_system.infer(inputs)
555    }
556
557    /// Convert RuleAtoms to fuzzy inputs
558    pub fn atoms_to_fuzzy_inputs(&self, atoms: &[RuleAtom]) -> Vec<(String, f64)> {
559        let mut inputs = Vec::new();
560
561        for atom in atoms {
562            if let RuleAtom::Triple {
563                subject,
564                predicate,
565                object,
566            } = atom
567            {
568                if let (Term::Constant(s), Term::Constant(p), Term::Literal(o)) =
569                    (subject, predicate, object)
570                {
571                    // Try to parse the object as a number
572                    if let Ok(value) = o.parse::<f64>() {
573                        inputs.push((format!("{}_{}", s, p), value));
574                    }
575                }
576            }
577        }
578
579        inputs
580    }
581
582    /// Get the fuzzy system reference
583    pub fn fuzzy_system(&self) -> &MamdaniFuzzySystem {
584        &self.fuzzy_system
585    }
586
587    /// Get mutable fuzzy system reference
588    pub fn fuzzy_system_mut(&mut self) -> &mut MamdaniFuzzySystem {
589        &mut self.fuzzy_system
590    }
591}
592
593impl Default for FuzzyRuleEngine {
594    fn default() -> Self {
595        Self::new()
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn test_triangular_membership() {
605        let mf = MembershipFunction::Triangular {
606            a: 0.0,
607            b: 5.0,
608            c: 10.0,
609        };
610
611        assert_eq!(mf.membership(-1.0), 0.0);
612        assert_eq!(mf.membership(0.0), 0.0);
613        assert_eq!(mf.membership(5.0), 1.0);
614        assert_eq!(mf.membership(10.0), 0.0);
615        assert_eq!(mf.membership(11.0), 0.0);
616    }
617
618    #[test]
619    fn test_trapezoidal_membership() {
620        let mf = MembershipFunction::Trapezoidal {
621            a: 0.0,
622            b: 2.0,
623            c: 8.0,
624            d: 10.0,
625        };
626
627        assert_eq!(mf.membership(-1.0), 0.0);
628        assert_eq!(mf.membership(0.0), 0.0);
629        assert_eq!(mf.membership(5.0), 1.0);
630        assert_eq!(mf.membership(10.0), 0.0);
631        assert_eq!(mf.membership(11.0), 0.0);
632    }
633
634    #[test]
635    fn test_gaussian_membership() {
636        let mf = MembershipFunction::Gaussian {
637            center: 5.0,
638            sigma: 1.0,
639        };
640
641        let mem_center = mf.membership(5.0);
642        let mem_away = mf.membership(8.0);
643
644        assert!((mem_center - 1.0).abs() < 1e-10);
645        assert!(mem_away < 0.1);
646    }
647
648    #[test]
649    fn test_fuzzy_set() {
650        let fs = FuzzySet::new(
651            "medium".to_string(),
652            MembershipFunction::Triangular {
653                a: 0.0,
654                b: 5.0,
655                c: 10.0,
656            },
657        );
658
659        assert_eq!(fs.membership(5.0), 1.0);
660        assert!(fs.membership(2.5) > 0.0 && fs.membership(2.5) < 1.0);
661    }
662
663    #[test]
664    fn test_t_norm() {
665        let min_norm = TNorm::Min;
666        assert_eq!(min_norm.apply(0.7, 0.3), 0.3);
667
668        let product_norm = TNorm::Product;
669        assert_eq!(product_norm.apply(0.5, 0.5), 0.25);
670    }
671
672    #[test]
673    fn test_t_conorm() {
674        let max_conorm = TConorm::Max;
675        assert_eq!(max_conorm.apply(0.7, 0.3), 0.7);
676
677        let prob_conorm = TConorm::ProbabilisticSum;
678        let result = prob_conorm.apply(0.5, 0.5);
679        assert!((result - 0.75).abs() < 1e-10);
680    }
681
682    #[test]
683    fn test_mamdani_fuzzy_system() -> Result<(), Box<dyn std::error::Error>> {
684        let mut system = MamdaniFuzzySystem::new();
685
686        // Add input variable "temperature" with range 0-40
687        system.add_input_variable("temperature".to_string(), 0.0, 40.0);
688
689        // Add fuzzy sets for temperature
690        system.add_input_fuzzy_set(
691            "temperature",
692            FuzzySet::new(
693                "cold".to_string(),
694                MembershipFunction::Triangular {
695                    a: 0.0,
696                    b: 0.0,
697                    c: 20.0,
698                },
699            ),
700        )?;
701
702        system.add_input_fuzzy_set(
703            "temperature",
704            FuzzySet::new(
705                "hot".to_string(),
706                MembershipFunction::Triangular {
707                    a: 20.0,
708                    b: 40.0,
709                    c: 40.0,
710                },
711            ),
712        )?;
713
714        // Add output variable "fan_speed" with range 0-100
715        system.add_output_variable("fan_speed".to_string(), 0.0, 100.0);
716
717        system.add_output_fuzzy_set(
718            "fan_speed",
719            FuzzySet::new(
720                "low".to_string(),
721                MembershipFunction::Triangular {
722                    a: 0.0,
723                    b: 0.0,
724                    c: 50.0,
725                },
726            ),
727        )?;
728
729        system.add_output_fuzzy_set(
730            "fan_speed",
731            FuzzySet::new(
732                "high".to_string(),
733                MembershipFunction::Triangular {
734                    a: 50.0,
735                    b: 100.0,
736                    c: 100.0,
737                },
738            ),
739        )?;
740
741        // Add rules
742        system.add_rule(FuzzyRule {
743            antecedents: vec![("temperature".to_string(), "cold".to_string())],
744            consequents: vec![("fan_speed".to_string(), "low".to_string())],
745            weight: 1.0,
746        });
747
748        system.add_rule(FuzzyRule {
749            antecedents: vec![("temperature".to_string(), "hot".to_string())],
750            consequents: vec![("fan_speed".to_string(), "high".to_string())],
751            weight: 1.0,
752        });
753
754        // Test inference
755        let result = system.infer(&[("temperature".to_string(), 30.0)])?;
756
757        assert!(result.contains_key("fan_speed"));
758        let fan_speed = result["fan_speed"];
759        assert!((0.0..=100.0).contains(&fan_speed));
760        Ok(())
761    }
762
763    #[test]
764    fn test_fuzzy_rule_engine() -> Result<(), Box<dyn std::error::Error>> {
765        let mut engine = FuzzyRuleEngine::new();
766
767        // Setup input variable
768        engine
769            .fuzzy_system_mut()
770            .add_input_variable("age".to_string(), 0.0, 100.0);
771
772        engine.fuzzy_system_mut().add_input_fuzzy_set(
773            "age",
774            FuzzySet::new(
775                "young".to_string(),
776                MembershipFunction::Triangular {
777                    a: 0.0,
778                    b: 0.0,
779                    c: 30.0,
780                },
781            ),
782        )?;
783
784        // Setup output variable
785        engine
786            .fuzzy_system_mut()
787            .add_output_variable("category".to_string(), 0.0, 10.0);
788
789        engine.fuzzy_system_mut().add_output_fuzzy_set(
790            "category",
791            FuzzySet::new(
792                "student".to_string(),
793                MembershipFunction::Triangular {
794                    a: 0.0,
795                    b: 5.0,
796                    c: 10.0,
797                },
798            ),
799        )?;
800
801        // Add fuzzy rule
802        let rule = Rule {
803            name: "young_student".to_string(),
804            body: vec![],
805            head: vec![],
806        };
807
808        let fuzzy_rule = FuzzyRule {
809            antecedents: vec![("age".to_string(), "young".to_string())],
810            consequents: vec![("category".to_string(), "student".to_string())],
811            weight: 1.0,
812        };
813
814        engine.add_fuzzy_rule(rule, fuzzy_rule);
815
816        // Test inference
817        let result = engine.fuzzy_infer(&[("age".to_string(), 20.0)])?;
818        assert!(result.contains_key("category"));
819        Ok(())
820    }
821}