tnorms 0.1.2

T-norm and t-conorm families
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! T-conorm (s-norm) families for fuzzy logic and differentiable relaxations.
//!
//! A t-conorm `S: [0,1]^2 -> [0,1]` generalizes logical OR. It is:
//! - Commutative: S(a, b) = S(b, a)
//! - Associative: S(S(a, b), c) = S(a, S(b, c))
//! - Monotone: a1 <= a2 => S(a1, b) <= S(a2, b)
//! - Bounded: S(a, 0) = a (0 is identity)
//!
//! Different families provide different "softness" of the OR operation,
//! useful in differentiable relaxations and probabilistic reasoning.
//!
//! ## Named families
//!
//! The constants [`GODEL`], [`PRODUCT`], and [`LUKASIEWICZ`] name the three
//! common fuzzy-logic families. [`LogicFamily`] adds the corresponding
//! residuum for implication:
//!
//! ```
//! assert_eq!(tnorms::tnorm(tnorms::GODEL, 0.4, 0.7), 0.4);
//! assert!((tnorms::tnorm(tnorms::PRODUCT, 0.4, 0.7) - 0.28).abs() < 1e-12);
//! assert!((tnorms::tnorm(tnorms::LUKASIEWICZ, 0.4, 0.7) - 0.1).abs() < 1e-12);
//! assert_eq!(tnorms::LogicFamily::Godel.residuum(0.7, 0.4), 0.4);
//! ```
//!
//! ## Catalog
//!
//! | Family | Formula S(a,b) | Parameter | Behavior |
//! |--------|---------------|-----------|----------|
//! | Maximum | max(a,b) | none | Hard OR |
//! | Probabilistic | a+b-ab | none | Independent events |
//! | Bounded (Lukasiewicz) | min(1, a+b) | none | Saturating sum |
//! | Einstein | (a+b)/(1+ab) | none | Smooth OR |
//! | Hamacher | (a+b-2ab)/(1-ab) | none | Aggressive |
//! | Yager | min(1, (a^p + b^p)^(1/p)) | p >= 1 | Lp norm |
//! | Frank | 1 - log_s(1+(s^(1-a)-1)(s^(1-b)-1)/(s-1)) | s > 0, s != 1 | Interpolates max<->bounded |
//! | Dombi | 1/(1+((1/a-1)^p + (1/b-1)^p)^(-1/p)) | p > 0 | Power-based |
//!
//! Based on: Petersen et al., gendr -- Generalized Differentiable Rendering.
//! The t-conorm catalog provides the relaxation families used for differentiable
//! logical operations and soft aggregation.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

/// Evaluate a t-conorm S(a, b) for the given family.
pub fn tconorm(family: TConormFamily, a: f64, b: f64) -> f64 {
    let a = a.clamp(0.0, 1.0);
    let b = b.clamp(0.0, 1.0);

    match family {
        TConormFamily::Maximum => a.max(b),
        TConormFamily::Probabilistic => a + b - a * b,
        TConormFamily::Bounded => (a + b).min(1.0),
        TConormFamily::Einstein => {
            let denom = 1.0 + a * b;
            if denom == 0.0 {
                0.0
            } else {
                (a + b) / denom
            }
        }
        TConormFamily::Hamacher => {
            let denom = 1.0 - a * b;
            if denom.abs() < 1e-15 {
                1.0 // both at 1.0
            } else {
                (a + b - 2.0 * a * b) / denom
            }
        }
        TConormFamily::Yager { p } => {
            debug_assert!(p >= 1.0, "Yager p must be >= 1");
            (a.powf(p) + b.powf(p)).powf(1.0 / p).min(1.0)
        }
        TConormFamily::Frank { s } => {
            debug_assert!(s > 0.0 && s != 1.0, "Frank s must be > 0 and != 1");
            let num = (s.powf(1.0 - a) - 1.0) * (s.powf(1.0 - b) - 1.0);
            let denom = s - 1.0;
            1.0 - (1.0 + num / denom).log(s)
        }
        TConormFamily::Dombi { p } => {
            debug_assert!(p > 0.0, "Dombi p must be > 0");
            if a <= 0.0 {
                return b;
            }
            if b <= 0.0 {
                return a;
            }
            if a >= 1.0 || b >= 1.0 {
                return 1.0;
            }
            let ta = (1.0 / a - 1.0).powf(p);
            let tb = (1.0 / b - 1.0).powf(p);
            // Harmonic-like combination
            let inner = (ta.recip() + tb.recip()).recip();
            1.0 / (1.0 + inner.powf(1.0 / p))
        }
    }
}

/// T-conorm family selection.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TConormFamily {
    /// S(a,b) = max(a,b). Hard OR, not differentiable at a=b.
    Maximum,
    /// S(a,b) = a+b-ab. Probabilistic sum (independent events).
    Probabilistic,
    /// S(a,b) = min(1, a+b). Lukasiewicz / bounded sum.
    Bounded,
    /// S(a,b) = (a+b)/(1+ab). Smooth, well-behaved for optimization.
    Einstein,
    /// S(a,b) = (a+b-2ab)/(1-ab). More aggressive than probabilistic.
    Hamacher,
    /// S(a,b) = min(1, (a^p + b^p)^(1/p)). Lp-norm family.
    Yager {
        /// Exponent, must be >= 1. p=1 gives Bounded, p->inf gives Maximum.
        p: f64,
    },
    /// Frank t-conorm parameterized by base s.
    /// s->0 gives Maximum, s=1 gives Probabilistic (limit), s->inf gives Bounded.
    Frank {
        /// Base parameter, must be > 0 and != 1.
        s: f64,
    },
    /// Dombi t-conorm. p->0 gives Maximum, p->inf gives Bounded.
    Dombi {
        /// Exponent, must be > 0.
        p: f64,
    },
}

/// Short alias for selecting a t-norm/t-conorm family.
pub type Family = TConormFamily;

/// Godel family: `min(a, b)` t-norm and `max(a, b)` t-conorm.
pub const GODEL: Family = Family::Maximum;

/// Product family: `a * b` t-norm and `a + b - a * b` t-conorm.
pub const PRODUCT: Family = Family::Probabilistic;

/// Lukasiewicz family: `max(0, a + b - 1)` t-norm and `min(1, a + b)` t-conorm.
pub const LUKASIEWICZ: Family = Family::Bounded;

/// Standard t-norm fuzzy logic families with residual implication.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogicFamily {
    /// Godel logic: minimum t-norm.
    Godel,
    /// Product logic: product t-norm.
    Product,
    /// Lukasiewicz logic: bounded-sum t-norm.
    Lukasiewicz,
}

impl LogicFamily {
    /// The t-conorm catalog family corresponding to this logic.
    pub const fn family(self) -> Family {
        match self {
            Self::Godel => GODEL,
            Self::Product => PRODUCT,
            Self::Lukasiewicz => LUKASIEWICZ,
        }
    }

    /// Evaluate the t-norm conjunction.
    pub fn tnorm(self, a: f64, b: f64) -> f64 {
        tnorm(self.family(), a, b)
    }

    /// Evaluate the dual t-conorm disjunction.
    pub fn tconorm(self, a: f64, b: f64) -> f64 {
        tconorm(self.family(), a, b)
    }

    /// Evaluate the residual implication `a -> b`.
    pub fn residuum(self, a: f64, b: f64) -> f64 {
        let a = a.clamp(0.0, 1.0);
        let b = b.clamp(0.0, 1.0);
        match self {
            Self::Godel => {
                if a <= b {
                    1.0
                } else {
                    b
                }
            }
            Self::Product => {
                if a <= b {
                    1.0
                } else {
                    b / a
                }
            }
            Self::Lukasiewicz => (1.0 - a + b).min(1.0),
        }
    }

    /// Evaluate the residual negation `a -> 0`.
    pub fn neg(self, a: f64) -> f64 {
        self.residuum(a, 0.0)
    }

    /// Evaluate the t-norm conjunction using `f32`.
    pub fn tnorm_f32(self, a: f32, b: f32) -> f32 {
        self.tnorm(f64::from(a), f64::from(b)) as f32
    }

    /// Evaluate the dual t-conorm disjunction using `f32`.
    pub fn tconorm_f32(self, a: f32, b: f32) -> f32 {
        self.tconorm(f64::from(a), f64::from(b)) as f32
    }

    /// Evaluate the residual implication using `f32`.
    pub fn residuum_f32(self, a: f32, b: f32) -> f32 {
        self.residuum(f64::from(a), f64::from(b)) as f32
    }

    /// Evaluate the residual negation using `f32`.
    pub fn neg_f32(self, a: f32) -> f32 {
        self.neg(f64::from(a)) as f32
    }
}

/// The dual t-norm T(a,b) = 1 - S(1-a, 1-b) for a given t-conorm family.
///
/// T-norms generalize logical AND.
pub fn tnorm(family: TConormFamily, a: f64, b: f64) -> f64 {
    1.0 - tconorm(family, 1.0 - a, 1.0 - b)
}

/// Aggregate multiple values using a t-conorm (generalized multi-way OR).
///
/// Folds left-to-right using associativity: S(S(S(a, b), c), d)...
pub fn tconorm_fold(family: TConormFamily, values: &[f64]) -> f64 {
    match values.len() {
        0 => 0.0, // identity element for t-conorms
        1 => values[0].clamp(0.0, 1.0),
        _ => values
            .iter()
            .skip(1)
            .fold(values[0].clamp(0.0, 1.0), |acc, &v| tconorm(family, acc, v)),
    }
}

/// Aggregate multiple values using a t-norm (generalized multi-way AND).
pub fn tnorm_fold(family: TConormFamily, values: &[f64]) -> f64 {
    match values.len() {
        0 => 1.0, // identity element for t-norms
        1 => values[0].clamp(0.0, 1.0),
        _ => values
            .iter()
            .skip(1)
            .fold(values[0].clamp(0.0, 1.0), |acc, &v| tnorm(family, acc, v)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn all_families() -> Vec<TConormFamily> {
        vec![
            TConormFamily::Maximum,
            TConormFamily::Probabilistic,
            TConormFamily::Bounded,
            TConormFamily::Einstein,
            TConormFamily::Hamacher,
            TConormFamily::Yager { p: 2.0 },
            TConormFamily::Frank { s: 2.0 },
            TConormFamily::Dombi { p: 2.0 },
        ]
    }

    #[test]
    fn identity_element() {
        for f in all_families() {
            let r = tconorm(f, 0.5, 0.0);
            assert!(
                (r - 0.5).abs() < 1e-6,
                "{f:?}: S(0.5, 0) = {r}, expected 0.5"
            );
        }
    }

    #[test]
    fn commutativity() {
        for f in all_families() {
            let r1 = tconorm(f, 0.3, 0.7);
            let r2 = tconorm(f, 0.7, 0.3);
            assert!(
                (r1 - r2).abs() < 1e-10,
                "{f:?}: S(0.3,0.7)={r1} != S(0.7,0.3)={r2}"
            );
        }
    }

    #[test]
    fn monotonicity() {
        for f in all_families() {
            let r1 = tconorm(f, 0.3, 0.5);
            let r2 = tconorm(f, 0.6, 0.5);
            assert!(
                r2 >= r1 - 1e-10,
                "{f:?}: monotonicity violated S(0.3,0.5)={r1} > S(0.6,0.5)={r2}"
            );
        }
    }

    #[test]
    fn bounded_output() {
        for f in all_families() {
            for &a in &[0.0, 0.25, 0.5, 0.75, 1.0] {
                for &b in &[0.0, 0.25, 0.5, 0.75, 1.0] {
                    let r = tconorm(f, a, b);
                    assert!(
                        (-1e-10..=1.0 + 1e-10).contains(&r),
                        "{f:?}: S({a},{b}) = {r} out of [0,1]"
                    );
                }
            }
        }
    }

    #[test]
    fn probabilistic_known_values() {
        let f = TConormFamily::Probabilistic;
        // S(0.5, 0.5) = 0.5 + 0.5 - 0.25 = 0.75
        assert!((tconorm(f, 0.5, 0.5) - 0.75).abs() < 1e-10);
        // S(1, x) = 1 for all x
        assert!((tconorm(f, 1.0, 0.3) - 1.0).abs() < 1e-10);
    }

    #[test]
    fn yager_p1_equals_bounded() {
        let yager = TConormFamily::Yager { p: 1.0 };
        let bounded = TConormFamily::Bounded;
        for &a in &[0.1, 0.3, 0.5, 0.7, 0.9] {
            for &b in &[0.1, 0.3, 0.5, 0.7, 0.9] {
                let ry = tconorm(yager, a, b);
                let rb = tconorm(bounded, a, b);
                assert!(
                    (ry - rb).abs() < 1e-10,
                    "Yager(p=1) != Bounded: S({a},{b}) = {ry} vs {rb}"
                );
            }
        }
    }

    #[test]
    fn tnorm_duality() {
        // T(a,b) = 1 - S(1-a, 1-b)
        // For probabilistic: T(a,b) = ab
        let f = TConormFamily::Probabilistic;
        let t = tnorm(f, 0.5, 0.6);
        assert!((t - 0.3).abs() < 1e-10, "T(0.5,0.6) = {t}, expected 0.3");
    }

    #[test]
    fn named_family_constants_match_common_tnorms() {
        assert!((tnorm(GODEL, 0.4, 0.7) - 0.4).abs() < 1e-12);
        assert!((tconorm(GODEL, 0.4, 0.7) - 0.7).abs() < 1e-12);

        assert!((tnorm(PRODUCT, 0.4, 0.7) - 0.28).abs() < 1e-12);
        assert!((tconorm(PRODUCT, 0.4, 0.7) - 0.82).abs() < 1e-12);

        assert!((tnorm(LUKASIEWICZ, 0.4, 0.7) - 0.1).abs() < 1e-12);
        assert!((tconorm(LUKASIEWICZ, 0.4, 0.7) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn logic_family_residua_match_common_formulas() {
        assert!((LogicFamily::Godel.residuum(0.4, 0.7) - 1.0).abs() < 1e-12);
        assert!((LogicFamily::Godel.residuum(0.7, 0.4) - 0.4).abs() < 1e-12);

        assert!((LogicFamily::Product.residuum(0.4, 0.7) - 1.0).abs() < 1e-12);
        assert!((LogicFamily::Product.residuum(0.7, 0.28) - 0.4).abs() < 1e-12);

        assert!((LogicFamily::Lukasiewicz.residuum(0.7, 0.4) - 0.7).abs() < 1e-12);
        assert!((LogicFamily::Lukasiewicz.neg(0.4) - 0.6).abs() < 1e-12);
    }

    #[test]
    fn logic_family_f32_helpers_match_f64() {
        let a = 0.4_f32;
        let b = 0.7_f32;
        for logic in [
            LogicFamily::Godel,
            LogicFamily::Product,
            LogicFamily::Lukasiewicz,
        ] {
            assert!(
                (logic.tnorm_f32(a, b) - logic.tnorm(f64::from(a), f64::from(b)) as f32).abs()
                    < 1e-6
            );
            assert!(
                (logic.tconorm_f32(a, b) - logic.tconorm(f64::from(a), f64::from(b)) as f32).abs()
                    < 1e-6
            );
            assert!(
                (logic.residuum_f32(a, b) - logic.residuum(f64::from(a), f64::from(b)) as f32)
                    .abs()
                    < 1e-6
            );
        }
    }

    #[test]
    fn fold_empty_returns_identity() {
        let f = TConormFamily::Maximum;
        assert_eq!(tconorm_fold(f, &[]), 0.0);
        assert_eq!(tnorm_fold(f, &[]), 1.0);
    }

    #[test]
    fn fold_single_value() {
        let f = TConormFamily::Probabilistic;
        assert!((tconorm_fold(f, &[0.7]) - 0.7).abs() < 1e-10);
    }

    #[test]
    fn fold_associativity() {
        let f = TConormFamily::Einstein;
        let abc = tconorm_fold(f, &[0.3, 0.5, 0.7]);
        let ab_c = tconorm(f, tconorm(f, 0.3, 0.5), 0.7);
        assert!(
            (abc - ab_c).abs() < 1e-10,
            "fold should match left-to-right application"
        );
    }
}