fbool 0.2.0

Boolean function analysis library: entanglement, entropy, sensitivity, spectral analysis, frontier, and circuit complexity
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! # Boolean Function Entanglement Analysis Library
//!
//! This library provides tools for analyzing entanglement properties of boolean functions.
//! It includes structures and traits for computing entanglement measures, entropy calculations,
//! and information-theoretic properties of boolean function partitions.
//!
//! ## Key Concepts
//!
//! - **Entanglement**: Measures how interrelated different parts of a boolean function are
//! - **Entropy**: Information-theoretic measure of randomness in function partitions
//! - **Information**: Quantifies the amount of information contained in variable sets
//!
//! ## Main Structures
//!
//! - [`EntanglementSet`] - Represents an entanglement value with its corresponding variable partition
//! - [`EntropySet`] - Represents an entropy value with its corresponding variable partition
//!
//! ## Main Traits
//!
//! - [`Entanglement`] - Provides methods for computing entanglement measures
//! - [`Entropy`] - Provides methods for computing entropy measures
//! - [`WithInformation`] - Provides information computation for variable sets

#[cfg(feature = "fmatrix")]
use crate::fmulti::FMulti;
use crate::{auxiliar::SubsetIterator, fvalue::FValue};
use rayon::prelude::*;
use std::hash::Hash;

/// Minimum number of variables required to activate parallel computation.
///
/// For functions with fewer variables the parallelization overhead exceeds the
/// gain; benchmarks show the crossover point is around n = 10.
const PARALLEL_THRESHOLD: usize = 10;

/// Represents an entanglement measurement with its associated variable partition.
///
/// This structure stores the entanglement value computed for a specific partition
/// of variables into two disjoint sets, along with the sets themselves.
///
/// # Fields
/// * `entanglement` - The computed entanglement value for this partition
/// * `set1` - The first set of variable indices in the partition
/// * `set2` - The second set of variable indices in the partition
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EntanglementSet {
    /// The entanglement value for this variable partition
    pub entanglement: usize,
    /// The first subset of variables in the partition
    pub set1: Vec<usize>,
    /// The second subset of variables in the partition
    pub set2: Vec<usize>,
}

impl Default for EntanglementSet {
    fn default() -> Self {
        EntanglementSet {
            entanglement: usize::MAX,
            set1: vec![],
            set2: vec![],
        }
    }
}

/// Represents an entropy measurement with its associated variable partition.
///
/// This structure stores the entropy value computed for a specific partition
/// of variables into two disjoint sets, along with the sets themselves.
///
/// # Fields
/// * `entropy` - The computed entropy value for this partition
/// * `set1` - The first set of variable indices in the partition
/// * `set2` - The second set of variable indices in the partition
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EntropySet {
    /// The entropy value for this variable partition
    pub entropy: f32,
    /// The first subset of variables in the partition
    pub set1: Vec<usize>,
    /// The second subset of variables in the partition
    pub set2: Vec<usize>,
}

impl Default for EntropySet {
    fn default() -> Self {
        EntropySet {
            entropy: f32::MAX,
            set1: vec![],
            set2: vec![],
        }
    }
}

/// Trait for types that have a defined number of variables.
pub trait NVars {
    /// Returns the number of boolean variables in the function.
    fn num_vars(&self) -> usize;
}

/// Trait for types that can compute information measures for variable sets.
///
/// Information typically refers to the number of distinct function forms
/// when certain variables are held fixed while others vary.
pub trait WithInformation {
    /// Computes the information content for a given set of variables.
    ///
    /// # Arguments
    /// * `vars` - A vector of variable indices to compute information for
    ///
    /// # Returns
    /// The information value (typically count of distinct forms) for the variable set
    fn get_information(&self, vars: &[usize]) -> usize;
}

/// Trait for types that can compute multiple information measures simultaneously.
pub trait WithMultipleInformation {
    /// Computes multiple information values for a given set of variables.
    ///
    /// # Arguments
    /// * `vars` - A vector of variable indices to compute information for
    ///
    /// # Returns
    /// A vector of information values for the variable set
    fn get_multiple_information(&self, vars: &[usize]) -> Vec<usize>;
}

/// Trait for types that can compute entropy measures for variable sets.
///
/// Entropy provides an information-theoretic measure of the randomness
/// or uncertainty in the function when variables are partitioned.
pub trait WithEntropy {
    /// Computes the entropy for a given set of variables.
    ///
    /// # Arguments
    /// * `vars` - A vector of variable indices to compute entropy for
    ///
    /// # Returns
    /// The entropy value for the variable set
    fn get_entropy(&self, vars: &[usize]) -> f32;
}

/// Trait for computing entanglement measures of boolean functions.
///
/// Entanglement measures quantify how much the function depends on interactions
/// between different subsets of variables, rather than being separable.
pub trait Entanglement {
    /// Computes the minimum entanglement value across all possible variable partitions.
    ///
    /// # Returns
    /// The minimum sum of information values across all bipartitions of variables
    fn entanglement(&self) -> usize;

    /// Returns all entanglement values for every possible variable partition.
    ///
    /// # Returns
    /// A vector of `EntanglementSet` structures containing entanglement values
    /// and their corresponding variable partitions
    fn entanglement_sets(&self) -> Vec<EntanglementSet>;

    /// Computes the minimum max-entanglement value across all possible variable partitions.
    ///
    /// Instead of summing information values, this takes the maximum of the two
    /// partition information values, then finds the minimum across all partitions.
    ///
    /// # Returns
    /// The minimum max information value across all bipartitions of variables
    fn minmax_entanglement(&self) -> usize;

    /// Returns all max-entanglement values for every possible variable partition.
    ///
    /// # Returns
    /// A vector of `EntanglementSet` structures containing max-entanglement values
    /// and their corresponding variable partitions
    fn minmax_entanglement_sets(&self) -> Vec<EntanglementSet>;
}

/// Trait for computing information values for individual variables.
pub trait SubInfos {
    /// Computes the information content for each individual variable.
    ///
    /// # Returns
    /// A vector where each element is the information content when fixing
    /// the corresponding variable (by index)
    fn sub_infos(&self) -> Vec<usize>;
}

/// Trait for computing entropy measures of boolean functions.
///
/// Entropy provides information-theoretic measures of uncertainty when
/// variables are partitioned into different subsets.
pub trait Entropy {
    /// Computes the minimum entropy value across all possible variable partitions.
    ///
    /// # Returns
    /// The minimum sum of entropy values across all bipartitions of variables
    fn entropy(&self) -> f32;

    /// Returns all entropy values for every possible variable partition.
    ///
    /// # Returns
    /// A vector of `EntropySet` structures containing entropy values
    /// and their corresponding variable partitions
    fn entropy_sets(&self) -> Vec<EntropySet>;
}

impl<T: WithInformation + NVars + Sync> Entanglement for T {
    fn entanglement(&self) -> usize {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    s1 + s2
                })
                .min()
                .unwrap_or(usize::MAX)
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    s1 + s2
                })
                .min()
                .unwrap_or(usize::MAX)
        }
    }

    fn entanglement_sets(&self) -> Vec<EntanglementSet> {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    EntanglementSet {
                        entanglement: s1 + s2,
                        set1,
                        set2,
                    }
                })
                .collect()
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    EntanglementSet {
                        entanglement: s1 + s2,
                        set1,
                        set2,
                    }
                })
                .collect()
        }
    }

    fn minmax_entanglement(&self) -> usize {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    s1.max(s2)
                })
                .min()
                .unwrap_or(usize::MAX)
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    s1.max(s2)
                })
                .min()
                .unwrap_or(usize::MAX)
        }
    }

    fn minmax_entanglement_sets(&self) -> Vec<EntanglementSet> {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    EntanglementSet {
                        entanglement: s1.max(s2),
                        set1,
                        set2,
                    }
                })
                .collect()
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_information(&set1);
                    let s2 = self.get_information(&set2);
                    EntanglementSet {
                        entanglement: s1.max(s2),
                        set1,
                        set2,
                    }
                })
                .collect()
        }
    }
}

impl<T: WithEntropy + NVars + Sync> Entropy for T {
    fn entropy(&self) -> f32 {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_entropy(&set1);
                    let s2 = self.get_entropy(&set2);
                    s1 + s2
                })
                .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .unwrap_or(f32::MAX)
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_entropy(&set1);
                    let s2 = self.get_entropy(&set2);
                    s1 + s2
                })
                .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .unwrap_or(f32::MAX)
        }
    }

    fn entropy_sets(&self) -> Vec<EntropySet> {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            SubsetIterator::new(n)
                .into_par_iter()
                .map(|(set1, set2)| {
                    let s1 = self.get_entropy(&set1);
                    let s2 = self.get_entropy(&set2);
                    EntropySet {
                        entropy: s1 + s2,
                        set1,
                        set2,
                    }
                })
                .collect()
        } else {
            SubsetIterator::new(n)
                .map(|(set1, set2)| {
                    let s1 = self.get_entropy(&set1);
                    let s2 = self.get_entropy(&set2);
                    EntropySet {
                        entropy: s1 + s2,
                        set1,
                        set2,
                    }
                })
                .collect()
        }
    }
}

impl<T: WithInformation + NVars + Sync> SubInfos for T {
    fn sub_infos(&self) -> Vec<usize> {
        let n = self.num_vars();
        if n >= PARALLEL_THRESHOLD {
            (0..n)
                .into_par_iter()
                .map(|i| self.get_information(&[i]))
                .collect()
        } else {
            (0..n).map(|i| self.get_information(&[i])).collect()
        }
    }
}

#[cfg(feature = "fmatrix")]
impl<T: crate::fmulti::GenericValue + Send + Sync> NVars for FMulti<T> {
    fn num_vars(&self) -> usize {
        self.repr().len().ilog2() as usize
    }
}

#[cfg(feature = "fmatrix")]
impl<T: crate::fmulti::GenericValue + Send + Hash + Sync> WithInformation for FMulti<T> {
    fn get_information(&self, vars: &[usize]) -> usize {
        self.count_forms_by_multiple_fixed(vars)
    }
}

impl<T: crate::fvalue::GenericValue + Send + Sync> NVars for FValue<T> {
    fn num_vars(&self) -> usize {
        self.repr().len().ilog2() as usize
    }
}

impl<T: crate::fvalue::GenericValue + Send + Hash + Sync> WithInformation for FValue<T> {
    fn get_information(&self, vars: &[usize]) -> usize {
        self.count_forms_by_multiple_fixed(vars)
    }
}

impl<T: crate::fvalue::GenericValue + Send + Hash + Sync> WithEntropy for FValue<T> {
    fn get_entropy(&self, vars: &[usize]) -> f32 {
        self.set_entropy(vars)
    }
}

/// Trait for computing equanimity importance measures of boolean functions.
pub trait EquanimityImportance {
    fn equanimity_importance(&self) -> f32;
}

impl<T: crate::fvalue::GenericValue> EquanimityImportance for FValue<T> {
    fn equanimity_importance(&self) -> f32 {
        fn pow2(n: usize) -> usize {
            1 << n
        }

        let mut importance_sum = 0;
        let num_input_bits = self.repr().len().ilog2() as usize;

        for i in 1..=num_input_bits {
            for j in (0..pow2(num_input_bits)).step_by(pow2(i)) {
                for k in 0..pow2(i - 1) {
                    if self.repr()[j + k] != self.repr()[j + k + pow2(i - 1)] {
                        importance_sum += 1;
                    }
                }
            }
        }

        importance_sum as f32 / (num_input_bits * pow2(num_input_bits - 1)) as f32
    }
}

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

    #[test]
    fn test_entanglement_set_default() {
        let es = EntanglementSet::default();
        assert_eq!(es.entanglement, usize::MAX);
        assert_eq!(es.set1.len(), 0);
        assert_eq!(es.set2.len(), 0);
    }

    #[test]
    fn test_entropy_set_default() {
        let es = EntropySet::default();
        assert_eq!(es.entropy, f32::MAX);
        assert_eq!(es.set1.len(), 0);
        assert_eq!(es.set2.len(), 0);
    }

    #[test]
    fn test_nvars_fvalue() {
        let f = FValue::parity(3);
        assert_eq!(f.num_vars(), 3);

        let f4 = FValue::majority(4);
        assert_eq!(f4.num_vars(), 4);
    }

    #[test]
    fn test_with_information() {
        let f = FValue::parity(3);

        // Information for empty set should be 1 (constant when all vars fixed)
        let info_empty = f.get_information(&[]);
        assert!(info_empty > 0);

        // Information for single variable
        let info_single = f.get_information(&[0]);
        assert!(info_single > 0);

        // Information for all variables should be the total number of distinct functions
        let info_all = f.get_information(&[0, 1, 2]);
        assert!(info_all > 0);
    }

    #[test]
    fn test_entanglement_computation() {
        let f = FValue::parity(3);
        let ent = f.entanglement();

        // Entanglement should be a finite positive value
        assert!(ent < usize::MAX);
        assert!(ent > 0);
    }

    #[test]
    fn test_entanglement_sets() {
        let f = FValue::parity(2);
        let ent_sets = f.entanglement_sets();

        // Should have at least one entanglement set
        assert!(!ent_sets.is_empty());

        // Each set should have valid data
        for es in &ent_sets {
            assert!(es.entanglement < usize::MAX);
            // set1 and set2 together should cover all variables
            assert!(es.set1.len() + es.set2.len() <= f.num_vars());
        }
    }

    #[test]
    fn test_minmax_entanglement() {
        let f = FValue::majority(3);
        let minmax = f.minmax_entanglement();

        // MinMax entanglement should be a finite value
        assert!(minmax < usize::MAX);
        assert!(minmax > 0);
    }

    #[test]
    fn test_minmax_entanglement_sets() {
        let f = FValue::majority(3);
        let minmax_sets = f.minmax_entanglement_sets();

        // Should have at least one set
        assert!(!minmax_sets.is_empty());

        // Each set should have valid data
        for es in &minmax_sets {
            assert!(es.entanglement < usize::MAX);
        }
    }

    #[test]
    fn test_entropy_computation() {
        let f = FValue::parity(3);
        let ent = f.entropy();

        // Entropy should be a finite positive value
        assert!(ent < f32::MAX);
        assert!(ent > 0.0);
    }

    #[test]
    fn test_entropy_sets() {
        let f = FValue::parity(3);
        let ent_sets = f.entropy_sets();

        // Should have at least one entropy set
        assert!(!ent_sets.is_empty());

        // Each set should have valid data
        for es in &ent_sets {
            assert!(es.entropy < f32::MAX);
            assert!(es.entropy >= 0.0);
        }
    }

    #[test]
    fn test_sub_infos() {
        let f = FValue::parity(3);
        let sub_infos = f.sub_infos();

        // Should have information for each variable
        assert_eq!(sub_infos.len(), 3);

        // Each should be positive
        for info in sub_infos {
            assert!(info > 0);
        }
    }

    #[test]
    fn test_equanimity_importance() {
        let f = FValue::majority(3);
        let eq_imp = f.equanimity_importance();

        // Should be a valid probability/ratio
        assert!(eq_imp >= 0.0);
        assert!(eq_imp <= 1.0);
    }

    #[test]
    fn test_entanglement_parity_vs_majority() {
        // Parity and majority functions should have different entanglement properties
        let parity_f = FValue::parity(3);
        let majority_f = FValue::majority(3);

        let parity_ent = parity_f.entanglement();
        let majority_ent = majority_f.entanglement();

        // Both should be valid
        assert!(parity_ent < usize::MAX);
        assert!(majority_ent < usize::MAX);

        // They should likely be different (though this is not strictly guaranteed)
        // This is more of a sanity check
        assert!(parity_ent > 0);
        assert!(majority_ent > 0);
    }

    #[test]
    fn test_with_entropy() {
        let f = FValue::parity(3);

        // Entropy for different variable sets
        let entropy_empty = f.get_entropy(&[]);
        let entropy_single = f.get_entropy(&[0]);
        let entropy_all = f.get_entropy(&[0, 1, 2]);

        // All should be finite and non-negative
        assert!((0.0..f32::MAX).contains(&entropy_empty));
        assert!((0.0..f32::MAX).contains(&entropy_single));
        assert!((0.0..f32::MAX).contains(&entropy_all));
    }
}