rust_fuzzylogic/
defuzz.rs

1// Defuzzification utilities for collapsing aggregated membership values.
2use crate::{prelude::*, variable::Variable};
3use std::{borrow::Borrow, collections::HashMap, hash::Hash};
4
5/// Defuzzify aggregated membership samples using the centroid of area method.
6pub fn defuzzification<KV>(
7    myu: HashMap<String, Vec<Float>>,
8    vars: &HashMap<KV, Variable>,
9) -> Result<HashMap<String, Float>>
10where
11    KV: Eq + Hash + Borrow<str>,
12{
13    let mut result_map: HashMap<String, Float> = HashMap::new();
14    for (i, j) in myu {
15        let num = j.len();
16        let (var_min, var_max) = vars.get(&i).ok_or(FuzzyError::EmptyInput)?.domain();
17        let step = (var_max - var_min) / (num as Float - 1.0);
18
19        let (mut sum_myux, mut sum_myu): (Float, Float) = (0.0, 0.0);
20        let mut l: usize = 0;
21        for k in j {
22            let x = var_min + step * l as Float;
23            sum_myux = sum_myux + (x * k);
24            sum_myu = sum_myu + k;
25            l += 1;
26        }
27        result_map.insert(i, sum_myux / sum_myu);
28    }
29
30    return Ok(result_map);
31}