libreda-logic 0.0.3

Logic library for LibrEDA.
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
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Exact NPN (negation-permutation-negation) canonization of truth tables based on brute-force search.
//! Boolean functions can be categorized in equivalence classes such that members of a class can be
//! transformed into eachother by applying negations on the inputs, permuting the inputs and possibly negating the output.
//! Each NPN class has the same combinational complexity, i.e. its members share the same size-optimal implementation as a boolean network.

use crate::traits::NumInputs;

use super::bitflip_iter::{bitflips, BitFlippable};
use super::permutation_gray_code::{permutation_swaps, permutation_swaps_cyclic};
use super::permutation_iter::{permutations, Permutable};
use super::small_lut::{SmallStaticTruthTable, SmallTT, SmallTruthTable};
use super::{gray_code_flips, npn_transform::*};

/// Track input inversions, input permutations and output inversions of `SmallTruthTable`s.
/// This is used to find a transformation which leads a function to it's canonical form.
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub struct NPNTransformTracker {
    /// The truth-table. Result of applying `tf`.
    tt: SmallTruthTable,
    /// The transform which as lead to the truth-table.
    tf: NPNTransform,
}

impl NPNTransformTracker {
    /// Wrap the truth-table into a transform tracker.
    /// The transform tracker allows to apply input reordering, input negation and output negation to
    /// the truth-table while keeping track of the applied operations.
    pub fn new(tt: SmallTruthTable) -> Self {
        Self {
            tt,
            tf: NPNTransform::identity(tt.num_inputs()),
        }
    }

    /// Get the truth-table.
    /// It is the result of applying the `transform()` to the original truth-table.
    pub fn truth_table(&self) -> SmallTruthTable {
        self.tt
    }

    /// Get the transform which led to the `truth_table`.
    pub fn transform(&self) -> NPNTransform {
        self.tf
    }
}

impl InvertOutput for NPNTransformTracker {
    fn inverted_output(mut self) -> Self {
        self.invert_output();
        self
    }

    fn invert_output(&mut self) {
        self.tt.invert_output();
        self.tf.invert_output();
    }
}

impl BitFlippable for NPNTransformTracker {
    fn num_bits(&self) -> usize {
        self.tt.num_bits()
    }

    fn flip_bit(&mut self, bit_idx: usize) {
        self.tt.flip_bit(bit_idx);
        self.tf.flip_bit(bit_idx);
    }
}

impl Permutable for NPNTransformTracker {
    fn len(&self) -> usize {
        self.tt.len()
    }

    fn swap(&mut self, i: usize, j: usize) {
        self.tt.swap(i, j);
        self.tf.swap(i, j);
    }
}

/// Find the NPN-representative of the truth-table. I.e. the lexicographically smallest
/// truth-table which can be generated from `tt` by applying inversions at the inputs, permuting the inputs
/// and inverting the output.
///
/// # Example
///
/// ```
/// use libreda_logic::truth_table::canonization::exact_npn_canonization;
/// use libreda_logic::truth_table::small_lut::SmallTruthTable;
///
/// let tt1 = SmallTruthTable::new(|[a, b, c]| a & b ^ c);
/// let tt2 = SmallTruthTable::new(|[a, b, c]| !(c & !b ^ a));
///
/// assert_eq!(exact_npn_canonization(tt1), exact_npn_canonization(tt2));
/// ```
/// # Example - extracting the transform which leads to the canonical form.
///
/// Sometimes not only the canonical form of the truth-table is of interest but also
/// the transform which converts the original truth-table into its canonical form.
/// This can be used by wrapping the truth-table into a 'transform tracker':
///
/// ```
/// use libreda_logic::truth_table::canonization::{exact_npn_canonization, NPNTransformTracker};
/// use libreda_logic::truth_table::small_lut::SmallTruthTable;
///
/// let tt = SmallTruthTable::new(|[a, b, c]| a & b ^ c);
///
/// let tracker = NPNTransformTracker::new(tt);
///
/// // Perform canonization on the wrapped truth-table `tracker`!
/// exact_npn_canonization(tt);
/// let canonical_form = exact_npn_canonization(tracker);
///
/// let canonical_truth_table = canonical_form.truth_table();
///
/// let transform = canonical_form.transform();
/// let inverse_transform = transform.inverse();
///
/// assert_eq!(transform.apply(tt), canonical_truth_table);
/// assert_eq!(tt, inverse_transform.apply(canonical_truth_table));
///
/// ```
pub fn exact_npn_canonization<T>(tt: T) -> T
where
    T: Clone + BitFlippable + Permutable + InvertOutput + Ord,
{
    let mut state = tt.clone();
    let mut min = tt.clone();
    let n = tt.num_bits();

    // Swapping inputs is slower than inverting inputs which is slower than inverting the output.
    // Therefore, do the slowest operation in the outer loop and the fastest in the inner loop.

    // For all permutations...
    for swap in permutation_swaps_cyclic(n) {
        //let pre_flip = state.clone();
        // for all input flips...
        for flip_idx in gray_code_flips::gray_code_flips(n) {
            // for all output flips
            for _ in 0..2 {
                if state < min {
                    state.clone_into(&mut min);
                }
                state.invert_output();
            }
            state.flip_bit(flip_idx);
        }
        //debug_assert!(state == pre_flip, "state should be reverted");

        state.swap(swap.0, swap.1);
    }
    debug_assert!(state == tt, "state should be reverted to the initial state");

    min

    //// Neater but slower (requires clones):
    //// Iterate over all permutations of the inputs.
    //permutations(tt)
    //    // Find canonical form by inverting inputs and output.
    //    .map(exact_nn_canonization)
    //    // Find lexicographical smallest truth-table.
    //    .min()
    //    .unwrap() // There is always at least one lement in the iterator.

    //// TODO: Use this simpler alternative if it performs better. Benchmark says it's worse.
    // all_npn_equivalent_functions(tt)
    // // Find lexicographical smallest truth-table.
    // .min()
    // .unwrap()
}

/// Find the NN-representative of the truth-table. I.e. the lexicographically smallest
/// truth-table which can be generated from `tt` by applying inversions at the inputs and at the output.
pub fn exact_nn_canonization<T>(tt: T) -> T
where
    T: Clone + BitFlippable + InvertOutput + Ord,
{
    let mut state = tt.clone();
    let mut min = tt.clone();
    let n = tt.num_bits();

    // for all input flips...
    for flip_idx in gray_code_flips::gray_code_flips(n) {
        // for all output flips
        for _ in 0..2 {
            if state < min {
                state.clone_into(&mut min);
            }
            // Inverting the output is cheap, therefore do it in the inner loop.
            state.invert_output();
        }
        state.flip_bit(flip_idx);
    }
    debug_assert!(state == tt, "state should be reverted to the initial state");

    min
    //bitflips(tt)
    //    // Find canonical form by inverting the output.
    //    .map(|tt| tt.clone().inverted_output().min(tt))
    //    .min()
    //    .unwrap()

    //// TODO: Use this simpler alternative if it performs better.
    //all_nn_equivalent_functions(tt)
    //    // Find lexicographical smallest truth-table.
    //    .min()
    //    .unwrap()
}

/// Iterate over the truth-tables of all functions which are in the same 'NN' class as `tt`.
/// I.e. all functions which can be derived from `tt` by inverting input and output bits.
pub fn all_nn_equivalent_functions<T>(tt: T) -> impl Iterator<Item = T>
where
    T: Clone + BitFlippable + InvertOutput + Ord,
{
    [tt.clone(), tt.inverted_output()]
        .into_iter()
        .flat_map(bitflips)
}

/// Iterate over the truth-tables of all functions which are in the same 'NPN' class as `tt`.
/// I.e. all functions which can be derived from `tt` by inverting input bits, permuting inputs and inverting the output.
pub fn all_npn_equivalent_functions<T>(tt: T) -> impl Iterator<Item = T>
where
    T: Clone + BitFlippable + InvertOutput + Permutable + Ord,
{
    all_nn_equivalent_functions(tt).flat_map(all_p_equivalent_functions)
}

#[test]
fn test_nn_canonization_3_inputs() {
    let tt1 = SmallTruthTable::new(|[a, b, c]| a & b | c);
    let tt2 = SmallTruthTable::new(|[a, b, c]| !(a & b | !c));

    assert_eq!(exact_nn_canonization(tt1), exact_nn_canonization(tt2));
}

#[test]
fn test_npn_canonization_2_inputs() {
    let tt1 = SmallTruthTable::new(|[a, b]| a & b);
    let tt2 = SmallTruthTable::new(|[a, b]| !(!b & a));

    assert_eq!(exact_npn_canonization(tt1), exact_npn_canonization(tt2));

    //let tt3 = SmallTruthTable::new(|[a, b]| a ^ b);
    //assert_ne!(exact_npn_canonization(tt1), exact_npn_canonization(tt3));
}

#[test]
fn test_npn_canonization_3_inputs() {
    let tt1 = SmallTruthTable::new(|[a, b, c]| a & b ^ c);
    let tt2 = SmallTruthTable::new(|[a, b, c]| !(c & !b ^ a));

    assert_eq!(exact_npn_canonization(tt1), exact_npn_canonization(tt2));
}

/// Find the P-representative of the truth-table. I.e. the lexicographically smallest
/// truth-table which can be generated from `tt` by permuting the inputs.
pub fn exact_p_canonization<T>(tt: T) -> T
where
    T: Permutable + Ord + Clone,
{
    let mut state = tt.clone();
    let mut min = tt.clone();
    let n = tt.len();

    // For all permutations...
    for swap in permutation_swaps(n) {
        state.swap(swap.0, swap.1);
        if state < min {
            state.clone_into(&mut min);
        }
    }

    min
    //permutations(tt)
    //    // Find the lexicographical smallest truth-table.
    //    .min()
    //    .unwrap() // There's always an element in this iterator.
}

/// Iterate over the truth-tables of all functions which are in the same 'P' class as `tt`.
/// I.e. all functions which can be derived from `tt` by permuting the inputs.
pub fn all_p_equivalent_functions<T>(tt: T) -> impl Iterator<Item = T>
where
    T: Clone + Permutable,
{
    permutations(tt)
}

impl Permutable for SmallTruthTable {
    fn len(&self) -> usize {
        self.num_inputs()
    }

    fn swap(&mut self, i: usize, j: usize) {
        *self = self.swap_inputs(i, j);
    }
}

impl BitFlippable for SmallTruthTable {
    fn num_bits(&self) -> usize {
        self.num_inputs()
    }

    fn flip_bit(&mut self, bit_idx: usize) {
        *self = self.invert_input(bit_idx)
    }
}

impl InvertOutput for SmallTruthTable {
    fn inverted_output(mut self) -> Self {
        self.invert_output();
        self
    }

    fn invert_output(&mut self) {
        *self = <Self as SmallTT>::invert(*self);
    }
}

impl<const N: usize> Permutable for SmallStaticTruthTable<N> {
    fn len(&self) -> usize {
        self.num_inputs()
    }

    fn swap(&mut self, i: usize, j: usize) {
        *self = self.swap_inputs(i, j);
    }
}

impl<const N: usize> BitFlippable for SmallStaticTruthTable<N> {
    fn num_bits(&self) -> usize {
        self.num_inputs()
    }

    fn flip_bit(&mut self, bit_idx: usize) {
        *self = self.invert_input(bit_idx)
    }
}

impl<const N: usize> InvertOutput for SmallStaticTruthTable<N> {
    fn inverted_output(mut self) -> Self {
        self.invert_output();
        self
    }

    fn invert_output(&mut self) {
        *self = <Self as SmallTT>::invert(*self);
    }
}
#[test]
fn test_p_canonization_2_inputs() {
    let tt1 = SmallTruthTable::new(|[a, b]| !a & b);
    let tt2 = SmallTruthTable::new(|[a, b]| a & !b);

    assert_eq!(exact_p_canonization(tt1), exact_p_canonization(tt2));
}

#[test]
fn test_p_canonization_6_inputs() {
    let tt1 = SmallTruthTable::new(|[a, b, c, d, e, f]| a & b & !c | d ^ e ^ f);
    let tt2 = SmallTruthTable::new(|[f, b, c, e, d, a]| a & b & !c | d ^ e ^ f);

    assert_eq!(exact_p_canonization(tt1), exact_p_canonization(tt2));
}

#[test]
fn test_npn_canonization_get_transform() {
    let tt = SmallTruthTable::new(|[a, b, c]| a & b ^ c);

    let tracker = NPNTransformTracker::new(tt);

    // Perform canonization on the wrapped truth-table `tracker`!
    exact_npn_canonization(tt);
    let canonical_form = exact_npn_canonization(tracker);

    let canonical_truth_table = canonical_form.truth_table();

    let transform = canonical_form.transform();
    let inverse_transform = transform.inverse();

    assert_eq!(transform.apply(tt), canonical_truth_table);
    assert_eq!(tt, inverse_transform.apply(canonical_truth_table));
}

#[test]
fn test_generate_3_input_npn_classes() {
    use std::collections::HashSet;

    let all_functions = (0..(1 << 8)).map(|i| SmallTruthTable::from_table(i, 3));

    let canonized = all_functions.map(exact_npn_canonization);
    let npn_classes: HashSet<_> = canonized.collect();

    assert_eq!(
        npn_classes.len(),
        14,
        "there must be 14 different NPN classes of 3-input Boolean functions"
    );
}

#[test]
fn test_generate_4_input_npn_classes() {
    use std::collections::HashSet;

    let all_functions = (0..(1 << 16)).map(|i| SmallTruthTable::from_table(i, 4));

    let canonized = all_functions.map(exact_npn_canonization);
    let npn_classes: HashSet<_> = canonized.collect();

    assert_eq!(
        npn_classes.len(),
        222,
        "there must be 222 different NPN classes of 4-input Boolean functions"
    );
}