1use crate::{Rule, RuleAtom, Term};
47use anyhow::{anyhow, Result};
48use scirs2_core::ndarray_ext::Array1;
49use std::collections::HashMap;
50
51#[derive(Debug, Clone)]
53pub enum MembershipFunction {
54 Triangular { a: f64, b: f64, c: f64 },
56 Trapezoidal { a: f64, b: f64, c: f64, d: f64 },
58 Gaussian { center: f64, sigma: f64 },
60 Sigmoid { a: f64, c: f64 },
62 Singleton { value: f64 },
64}
65
66impl MembershipFunction {
67 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#[derive(Debug, Clone)]
108pub struct FuzzySet {
109 pub name: String,
111 pub function: MembershipFunction,
113}
114
115impl FuzzySet {
116 pub fn new(name: String, function: MembershipFunction) -> Self {
118 Self { name, function }
119 }
120
121 pub fn membership(&self, x: f64) -> f64 {
123 self.function.membership(x)
124 }
125
126 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 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#[derive(Debug, Clone)]
147pub struct FuzzyRule {
148 pub antecedents: Vec<(String, String)>,
150 pub consequents: Vec<(String, String)>,
152 pub weight: f64,
154}
155
156#[derive(Debug, Clone)]
158pub struct FuzzyVariable {
159 pub name: String,
161 pub min: f64,
163 pub max: f64,
165 pub fuzzy_sets: HashMap<String, FuzzySet>,
167}
168
169impl FuzzyVariable {
170 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 pub fn add_fuzzy_set(&mut self, fuzzy_set: FuzzySet) {
182 self.fuzzy_sets.insert(fuzzy_set.name.clone(), fuzzy_set);
183 }
184
185 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#[derive(Debug, Clone)]
196pub struct MamdaniFuzzySystem {
197 input_variables: HashMap<String, FuzzyVariable>,
199 output_variables: HashMap<String, FuzzyVariable>,
201 rules: Vec<FuzzyRule>,
203 t_norm: TNorm,
205 t_conorm: TConorm,
207 defuzz_method: DefuzzificationMethod,
209}
210
211#[derive(Debug, Clone, Copy)]
213pub enum TNorm {
214 Min,
216 Product,
218 Lukasiewicz,
220}
221
222impl TNorm {
223 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#[derive(Debug, Clone, Copy)]
235pub enum TConorm {
236 Max,
238 ProbabilisticSum,
240}
241
242impl TConorm {
243 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#[derive(Debug, Clone, Copy)]
254pub enum DefuzzificationMethod {
255 Centroid,
257 Bisector,
259 MeanOfMaximum,
261 SmallestOfMaximum,
263 LargestOfMaximum,
265}
266
267impl MamdaniFuzzySystem {
268 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 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 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 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 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 pub fn add_rule(&mut self, rule: FuzzyRule) {
312 self.rules.push(rule);
313 }
314
315 pub fn set_t_norm(&mut self, t_norm: TNorm) {
317 self.t_norm = t_norm;
318 }
319
320 pub fn set_t_conorm(&mut self, t_conorm: TConorm) {
322 self.t_conorm = t_conorm;
323 }
324
325 pub fn set_defuzzification_method(&mut self, method: DefuzzificationMethod) {
327 self.defuzz_method = method;
328 }
329
330 pub fn infer(&self, inputs: &[(String, f64)]) -> Result<HashMap<String, f64>> {
332 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 let mut output_fuzzy_values: HashMap<String, Vec<(String, f64)>> = HashMap::new();
350
351 for rule in &self.rules {
352 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 firing_strength *= rule.weight;
365
366 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 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 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 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 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 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 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 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 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 let total_area: f64 = membership.iter().sum::<f64>() * step;
504 let half_area = total_area / 2.0;
505
506 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#[derive(Debug)]
529pub struct FuzzyRuleEngine {
530 fuzzy_system: MamdaniFuzzySystem,
532 rule_mapping: HashMap<String, FuzzyRule>,
534}
535
536impl FuzzyRuleEngine {
537 pub fn new() -> Self {
539 Self {
540 fuzzy_system: MamdaniFuzzySystem::new(),
541 rule_mapping: HashMap::new(),
542 }
543 }
544
545 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 pub fn fuzzy_infer(&self, inputs: &[(String, f64)]) -> Result<HashMap<String, f64>> {
554 self.fuzzy_system.infer(inputs)
555 }
556
557 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 if let Ok(value) = o.parse::<f64>() {
573 inputs.push((format!("{}_{}", s, p), value));
574 }
575 }
576 }
577 }
578
579 inputs
580 }
581
582 pub fn fuzzy_system(&self) -> &MamdaniFuzzySystem {
584 &self.fuzzy_system
585 }
586
587 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 system.add_input_variable("temperature".to_string(), 0.0, 40.0);
688
689 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 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 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 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 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 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 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 let result = engine.fuzzy_infer(&[("age".to_string(), 20.0)])?;
818 assert!(result.contains_key("category"));
819 Ok(())
820 }
821}