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
use std::{
    fmt,
    ops::{BitAnd, BitOr, Not},
};

use crate::sop::Cube;
use crate::Lut;

/// Sum of Products representation (Or of And)
///
/// This is the usual representation for 2-level logic optimization. Any boolean function can be
/// represented this way, and the optimization can be done quite efficiently (with
/// [Espresso](https://en.wikipedia.org/wiki/Espresso_heuristic_logic_minimizer), for example).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Sop {
    num_vars: usize,
    cubes: Vec<Cube>,
}

impl Sop {
    /// Query the number of variables
    pub fn num_vars(&self) -> usize {
        self.num_vars
    }

    /// Return the constant zero Sop
    pub fn zero(num_vars: usize) -> Sop {
        Sop {
            num_vars,
            cubes: vec![],
        }
    }

    /// Return the constant one Sop
    pub fn one(num_vars: usize) -> Sop {
        Sop {
            num_vars,
            cubes: vec![Cube::one()],
        }
    }

    /// Number of cubes in the Sop
    pub fn num_cubes(&self) -> usize {
        self.cubes.len()
    }

    /// Number of literals in the Sop
    pub fn num_lits(&self) -> usize {
        let mut ret = 0;
        for c in &self.cubes {
            ret += c.num_lits();
        }
        ret
    }

    /// Returns whether the Sop is trivially constant zero
    pub fn is_zero(&self) -> bool {
        self.cubes.is_empty()
    }

    /// Returns whether the Sop is trivially constant one
    pub fn is_one(&self) -> bool {
        match self.cubes.first() {
            Some(c) => c.is_one(),
            None => false,
        }
    }

    /// Return the Sop representing the nth variable
    pub fn nth_var(num_vars: usize, var: usize) -> Sop {
        Sop {
            num_vars,
            cubes: vec![Cube::nth_var(var)],
        }
    }

    /// Return the Sop representing the nth variable, inverted
    pub fn nth_var_inv(num_vars: usize, var: usize) -> Sop {
        Sop {
            num_vars,
            cubes: vec![Cube::nth_var_inv(var)],
        }
    }

    /// Build an Sop from cubes
    pub fn from_cubes(num_vars: usize, cubes: Vec<Cube>) -> Sop {
        for c in &cubes {
            for v in c.pos_vars() {
                assert!(v < num_vars);
            }
            for v in c.neg_vars() {
                assert!(v < num_vars);
            }
        }
        Sop { num_vars, cubes }
    }

    /// Returns the cubes in the Sop
    pub fn cubes(&self) -> &[Cube] {
        &self.cubes
    }

    /// Get the value of the Sop for these inputs (input bits packed in the mask)
    pub fn value(&self, mask: usize) -> bool {
        let mut ret = false;
        for c in &self.cubes {
            ret |= c.value(mask);
        }
        ret
    }

    /// Basic simplification of the Sop
    ///
    /// The following simplifications are performed:
    ///   * Zero cubes are removed
    ///   * Cubes that imply another are removed
    ///
    /// The following are not yet implemented:
    ///   * Cubes that differ by one literal are merged
    fn simplify(&mut self) {
        // No need for zeros
        self.cubes.retain(|c| !c.is_zero());
        // Remove any duplicate cube the easy way
        self.cubes.sort();
        self.cubes.dedup();
        // Remove any cube that implies another
        let mut new_cubes = Vec::new();
        for c in &self.cubes {
            if self.cubes.iter().all(|o| *c == *o || !c.implies(*o)) {
                new_cubes.push(*c);
            }
        }
        self.cubes = new_cubes;
    }

    /// Compute the or of two Sops
    fn or(a: &Sop, b: &Sop) -> Sop {
        assert_eq!(a.num_vars, b.num_vars);
        let mut cubes = a.cubes.clone();
        cubes.extend(&b.cubes);
        let mut ret = Sop {
            num_vars: a.num_vars,
            cubes,
        };
        ret.simplify();
        ret
    }

    /// Compute the and of two Sops
    fn and(a: &Sop, b: &Sop) -> Sop {
        assert_eq!(a.num_vars, b.num_vars);
        let mut cubes = Vec::new();
        for c1 in &a.cubes {
            for c2 in &b.cubes {
                let c = c1 & c2;
                if c != Cube::zero() {
                    cubes.push(c);
                }
            }
        }
        let mut ret = Sop {
            num_vars: a.num_vars,
            cubes,
        };
        ret.simplify();
        ret
    }
}

impl Not for Sop {
    type Output = Sop;
    fn not(self) -> Self::Output {
        !&self
    }
}

impl Not for &Sop {
    type Output = Sop;
    fn not(self) -> Self::Output {
        let mut ret = Sop::one(self.num_vars);
        for c in &self.cubes {
            let mut v = Vec::new();
            for l in c.pos_vars() {
                v.push(Cube::nth_var_inv(l));
            }
            for l in c.neg_vars() {
                v.push(Cube::nth_var(l));
            }
            let s = Sop {
                num_vars: self.num_vars,
                cubes: v,
            };
            ret = ret & s;
        }
        ret
    }
}

impl BitAnd<Sop> for Sop {
    type Output = Sop;
    fn bitand(self, rhs: Sop) -> Self::Output {
        Sop::and(&self, &rhs)
    }
}

impl BitAnd<Sop> for &Sop {
    type Output = Sop;
    fn bitand(self, rhs: Sop) -> Self::Output {
        Sop::and(self, &rhs)
    }
}

impl BitAnd<&Sop> for &Sop {
    type Output = Sop;
    fn bitand(self, rhs: &Sop) -> Self::Output {
        Sop::and(self, rhs)
    }
}

impl BitAnd<&Sop> for Sop {
    type Output = Sop;
    fn bitand(self, rhs: &Sop) -> Self::Output {
        Sop::and(&self, rhs)
    }
}

impl BitOr<Sop> for Sop {
    type Output = Sop;
    fn bitor(self, rhs: Sop) -> Self::Output {
        Sop::or(&self, &rhs)
    }
}

impl BitOr<Sop> for &Sop {
    type Output = Sop;
    fn bitor(self, rhs: Sop) -> Self::Output {
        Sop::or(self, &rhs)
    }
}

impl BitOr<&Sop> for &Sop {
    type Output = Sop;
    fn bitor(self, rhs: &Sop) -> Self::Output {
        Sop::or(self, rhs)
    }
}

impl BitOr<&Sop> for Sop {
    type Output = Sop;
    fn bitor(self, rhs: &Sop) -> Self::Output {
        Sop::or(&self, rhs)
    }
}

impl fmt::Display for Sop {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_zero() {
            write!(f, "0")?;
            return Ok(());
        }
        let s = self
            .cubes
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(" | ");
        write!(f, "{}", s)
    }
}

impl From<&Lut> for Sop {
    fn from(value: &Lut) -> Self {
        let mut ret = Sop::zero(value.num_vars());
        let mx = value.num_bits();
        for mask in 0..mx {
            if value.value(mask) {
                ret.cubes.push(Cube::minterm(value.num_vars(), mask));
            }
        }
        ret
    }
}

impl From<Lut> for Sop {
    fn from(value: Lut) -> Self {
        Sop::from(&value)
    }
}

impl From<&Sop> for Lut {
    fn from(value: &Sop) -> Self {
        let mut ret = Lut::zero(value.num_vars());
        let mx = ret.num_bits();
        for mask in 0..mx {
            if value.value(mask) {
                ret.set_bit(mask);
            }
        }
        ret
    }
}

impl From<Sop> for Lut {
    fn from(value: Sop) -> Self {
        Lut::from(&value)
    }
}

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

    #[test]
    fn test_zero_one() {
        assert!(Sop::zero(32).is_zero());
        assert!(!Sop::one(32).is_zero());
        assert!(!Sop::zero(32).is_one());
        assert!(Sop::one(32).is_one());
        for i in 0..32 {
            assert!(!Sop::nth_var(32, i).is_zero());
            assert!(!Sop::nth_var(32, i).is_one());
            assert!(!Sop::nth_var_inv(32, i).is_zero());
            assert!(!Sop::nth_var_inv(32, i).is_one());
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_random() {
        use crate::Lut;

        for i in 0..8 {
            for _ in 0..10 {
                let l = Lut::random(i);
                assert_eq!(l, Sop::from(&l).into());
            }
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_not() {
        use crate::Lut;

        for i in 0..8 {
            for _ in 0..10 {
                let l = Lut::random(i);
                let ln = !&l;
                let s: Sop = l.into();
                let sn = !&s;
                assert_eq!(ln, sn.into());
            }
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_or() {
        use crate::Lut;

        for i in 0..8 {
            for _ in 0..10 {
                let l1 = Lut::random(i);
                let l2 = Lut::random(i);
                let lo = &l1 | &l2;
                let s1: Sop = l1.into();
                let s2: Sop = l2.into();
                let so = s1 | s2;
                assert_eq!(lo, so.into());
            }
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_and() {
        use crate::Lut;

        for i in 0..8 {
            for _ in 0..10 {
                let l1 = Lut::random(i);
                let l2 = Lut::random(i);
                let lo = &l1 & &l2;
                let s1: Sop = l1.into();
                let s2: Sop = l2.into();
                let so = s1 & s2;
                assert_eq!(lo, so.into());
            }
        }
    }

    #[test]
    fn test_display() {
        let s = Sop::from_cubes(
            6,
            vec![
                Cube::from_vars(&[1, 2], &[3]),
                Cube::from_vars(&[2, 1], &[0, 4, 5]),
            ],
        );
        assert_eq!(format!("{:}", s), "x1x2!x3 | !x0x1x2!x4!x5");
    }
}