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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use std::{
    collections::{BTreeSet, BTreeMap},
    iter::FromIterator,
    mem, fmt,
    error::Error,
};
use varisat::{Var, Lit, ExtendFormula, solver::SolverError};
use crate::{
    ContextHandle, Contextual, NodeID, AtomID, ForkID, JoinID, Harc, AcesError,
    atom::Atom,
    sat::{CEVar, CELit, Encoding, Search, Clause, Formula},
};

#[derive(Clone, Default, Debug)]
pub(crate) struct Props {
    pub(crate) sat_encoding: Option<Encoding>,
    pub(crate) sat_search:   Option<Search>,
}

impl Props {
    pub(crate) fn clear(&mut self) {
        *self = Default::default();
    }
}

enum ModelSearchResult {
    Reset,
    Found(Vec<Lit>),
    Done,
    Failed(SolverError),
}

impl ModelSearchResult {
    #[allow(dead_code)]
    fn get_model(&self) -> Option<&[Lit]> {
        match self {
            ModelSearchResult::Found(ref v) => Some(v.as_slice()),
            _ => None,
        }
    }

    #[inline]
    #[allow(dead_code)]
    fn take(&mut self) -> Self {
        mem::replace(self, ModelSearchResult::Reset)
    }

    fn take_error(&mut self) -> Option<SolverError> {
        let old_result = match self {
            ModelSearchResult::Failed(_) => mem::replace(self, ModelSearchResult::Reset),
            _ => return None,
        };

        if let ModelSearchResult::Failed(err) = old_result {
            Some(err)
        } else {
            unreachable!()
        }
    }
}

impl Default for ModelSearchResult {
    fn default() -> Self {
        ModelSearchResult::Reset
    }
}

#[derive(Default, Debug)]
struct Assumptions {
    literals:      Vec<Lit>,
    permanent_len: usize,
}

impl Assumptions {
    fn block_variable(&mut self, var: Var) {
        let lit = Lit::from_var(var, false);

        let pos = if self.permanent_len > 0 {
            match self.literals[..self.permanent_len].binary_search(&lit) {
                Ok(_) => return,
                Err(pos) => pos,
            }
        } else {
            0
        };

        self.literals.insert(pos, lit);
        self.permanent_len += 1;
    }

    fn unblock_variable(&mut self, var: Var) -> bool {
        let lit = Lit::from_var(var, false);

        if self.permanent_len > 0 {
            match self.literals[..self.permanent_len].binary_search(&lit) {
                Ok(pos) => {
                    self.literals.remove(pos);
                    self.permanent_len -= 1;
                    true
                }
                Err(_) => false,
            }
        } else {
            false
        }
    }

    fn unblock_all_variables(&mut self) {
        if self.permanent_len > 0 {
            let new_literals = self.literals.split_off(self.permanent_len);

            self.literals = new_literals;
            self.permanent_len = 0;
        }
    }

    #[inline]
    fn is_empty(&self) -> bool {
        self.literals.len() == self.permanent_len
    }

    #[inline]
    fn reset(&mut self) {
        self.literals.truncate(self.permanent_len);
    }

    #[inline]
    fn add(&mut self, lit: Lit) {
        self.literals.push(lit);
    }

    #[inline]
    fn get_literals(&self) -> &[Lit] {
        assert!(self.literals.len() >= self.permanent_len);

        self.literals.as_slice()
    }
}

impl Contextual for Assumptions {
    fn format(&self, ctx: &ContextHandle) -> Result<String, Box<dyn Error>> {
        self.literals.format(ctx)
    }
}

pub struct Solver<'a> {
    context:     ContextHandle,
    engine:      varisat::Solver<'a>,
    all_vars:    BTreeSet<Var>,
    is_sat:      Option<bool>,
    last_model:  ModelSearchResult,
    min_residue: BTreeSet<Var>,
    assumptions: Assumptions,
}

impl<'a> Solver<'a> {
    pub fn new(ctx: &ContextHandle) -> Self {
        Self {
            context:     ctx.clone(),
            engine:      Default::default(),
            all_vars:    Default::default(),
            is_sat:      None,
            last_model:  Default::default(),
            min_residue: Default::default(),
            assumptions: Default::default(),
        }
    }

    pub fn reset(&mut self) -> Result<(), SolverError> {
        self.is_sat = None;
        self.last_model = ModelSearchResult::Reset;
        self.min_residue.clear();
        self.assumptions.reset();
        self.engine.close_proof()
    }

    pub fn block_atom_id(&mut self, atom_id: AtomID) {
        let var = Var::from_atom_id(atom_id);

        self.assumptions.block_variable(var);
    }

    pub fn unblock_atom_id(&mut self, atom_id: AtomID) -> bool {
        let var = Var::from_atom_id(atom_id);

        self.assumptions.unblock_variable(var)
    }

    pub fn unblock_all_atoms(&mut self) {
        self.assumptions.unblock_all_variables();
    }

    /// Only for internal use.
    fn add_clause(&mut self, clause: Clause) -> Result<(), AcesError> {
        if clause.is_empty() {
            Err(AcesError::EmptyClauseRejectedBySolver(clause.get_info().to_owned()))
        } else {
            debug!("Add (to solver) {} clause: {}", clause.get_info(), clause.with(&self.context));

            self.engine.add_clause(clause.get_literals());

            Ok(())
        }
    }

    pub fn add_formula(&mut self, formula: &Formula) -> Result<(), AcesError> {
        self.engine.add_formula(formula.get_cnf());

        let new_vars = formula.get_variables();
        self.all_vars.extend(new_vars);

        Ok(())
    }

    /// Blocks empty solution models by adding a _void inhibition_
    /// clause.
    ///
    /// A model represents an empty solution iff it contains only
    /// negative [`Port`] literals (hence no [`Port`] variable
    /// evaluates to `true`).  Thus, the blocking clause is the
    /// disjunction of all [`Port`] variables known by the solver.
    ///
    /// [`Port`]: crate::Port
    pub fn inhibit_empty_solution(&mut self) -> Result<(), AcesError> {
        let clause = {
            let ctx = self.context.lock().unwrap();
            let mut all_lits: Vec<_> = self
                .all_vars
                .iter()
                .filter_map(|&var| {
                    ctx.is_port(var.into_atom_id()).then(|| Lit::from_var(var, true))
                })
                .collect();
            let mut fork_lits: Vec<_> = self
                .all_vars
                .iter()
                .filter_map(|&var| {
                    ctx.is_fork(var.into_atom_id()).then(|| Lit::from_var(var, true))
                })
                .collect();
            let mut join_lits: Vec<_> = self
                .all_vars
                .iter()
                .filter_map(|&var| {
                    ctx.is_join(var.into_atom_id()).then(|| Lit::from_var(var, true))
                })
                .collect();

            // Include all fork variables or all join variables,
            // depending on in which case the clause grows less.
            if fork_lits.len() > join_lits.len() {
                if join_lits.is_empty() {
                    return Err(AcesError::IncoherencyLeak)
                } else {
                    all_lits.append(&mut join_lits);
                }
            } else if !fork_lits.is_empty() {
                all_lits.append(&mut fork_lits);
            } else if !join_lits.is_empty() {
                return Err(AcesError::IncoherencyLeak)
            }

            Clause::from_vec(all_lits, "void inhibition")
        };

        self.add_clause(clause)
    }

    /// Adds a _model inhibition_ clause which will remove a specific
    /// `model` from solution space.
    ///
    /// The blocking clause is constructed by negating the given
    /// `model`, i.e. by taking the disjunction of all _explicit_
    /// literals and reversing polarity of each.  A literal is
    /// explicit iff its variable has been _registered_ by occurring
    /// in a formula passed to a call to [`add_formula()`].
    ///
    /// [`add_formula()`]: Solver::add_formula()
    pub fn inhibit_model(&mut self, model: &[Lit]) -> Result<(), AcesError> {
        let anti_lits =
            model.iter().filter_map(|&lit| self.all_vars.contains(&lit.var()).then(|| !lit));
        let clause = Clause::from_literals(anti_lits, "model inhibition");

        self.add_clause(clause)
    }

    fn inhibit_last_model(&mut self) -> Result<(), AcesError> {
        if let ModelSearchResult::Found(ref model) = self.last_model {
            let anti_lits =
                model.iter().filter_map(|&lit| self.all_vars.contains(&lit.var()).then(|| !lit));
            let clause = Clause::from_literals(anti_lits, "model inhibition");

            self.add_clause(clause)
        } else {
            Err(AcesError::NoModelToInhibit)
        }
    }

    fn reduce_model(&mut self, model: &[Lit]) -> Result<bool, AcesError> {
        let mut reducing_lits = Vec::new();

        for &lit in model.iter() {
            if !self.min_residue.contains(&lit.var()) {
                if lit.is_positive() {
                    reducing_lits.push(!lit);
                } else {
                    self.assumptions.add(lit);
                    self.min_residue.insert(lit.var());
                }
            }
        }

        if reducing_lits.is_empty() {
            Ok(false)
        } else {
            let clause = Clause::from_literals(reducing_lits.into_iter(), "model reduction");
            self.add_clause(clause)?;

            Ok(true)
        }
    }

    fn solve(&mut self) -> Option<bool> {
        if !self.assumptions.is_empty() {
            debug!("Solving under assumptions: {}", self.assumptions.with(&self.context));
        }

        self.engine.assume(self.assumptions.get_literals());

        let result = self.engine.solve();

        if self.is_sat.is_none() {
            self.is_sat = result.as_ref().ok().copied();
        }

        match result {
            Ok(is_sat) => {
                if is_sat {
                    if let Some(model) = self.engine.model() {
                        self.last_model = ModelSearchResult::Found(model);
                        Some(true)
                    } else {
                        warn!("Solver reported SAT without a model");

                        self.last_model = ModelSearchResult::Done;
                        Some(false)
                    }
                } else {
                    self.last_model = ModelSearchResult::Done;
                    Some(false)
                }
            }
            Err(err) => {
                self.last_model = ModelSearchResult::Failed(err);
                None
            }
        }
    }

    pub(crate) fn is_sat(&self) -> Option<bool> {
        self.is_sat
    }

    /// Returns `true` if last call to [`solve()`] was interrupted.
    /// Returns `false` if [`solve()`] either failed, or succeeded, or
    /// hasn't been called yet.
    ///
    /// Note, that even if last call to [`solve()`] was indeed
    /// interrupted, a subsequent invocation of [`take_last_error()`]
    /// resets this to return `false` until next [`solve()`].
    ///
    /// [`solve()`]: Solver::solve()
    /// [`take_last_error()`]: Solver::take_last_error()
    pub fn was_interrupted(&self) -> bool {
        if let ModelSearchResult::Failed(ref err) = self.last_model {
            err.is_recoverable()
        } else {
            false
        }
    }

    pub fn last_solution(&self) -> Option<Solution> {
        self.engine.model().and_then(|model| match Solution::from_model(&self.context, model) {
            Ok(solution) => Some(solution),
            Err(err) => {
                warn!("{} in solver's solution ctor", err);
                None
            }
        })
    }

    /// Returns the error reported by last call to [`solve()`], if
    /// solving has failed; otherwise returns `None`.
    ///
    /// Note, that this may be invoked only once for every
    /// unsuccessful call to [`solve()`], because, in varisat 0.2,
    /// `varisat::solver::SolverError` can't be cloned.
    ///
    /// [`solve()`]: Solver::solve()
    pub(crate) fn take_last_error(&mut self) -> Option<SolverError> {
        self.last_model.take_error()
    }

    fn next_solution(&mut self) -> Option<Solution> {
        self.solve();

        if let ModelSearchResult::Found(ref model) = self.last_model {
            match Solution::from_model(&self.context, model.iter().copied()) {
                Ok(solution) => {
                    if let Err(err) = self.inhibit_last_model() {
                        warn!("{} in solver's iteration", err);

                        None
                    } else {
                        Some(solution)
                    }
                }
                Err(err) => {
                    warn!("{} in solver's iteration", err);
                    None
                }
            }
        } else {
            None
        }
    }

    fn next_minimal_solution(&mut self) -> Option<Solution> {
        self.assumptions.reset();

        self.solve();

        if let ModelSearchResult::Found(ref top_model) = self.last_model {
            let top_model = top_model.clone();

            trace!("Top model: {:?}", top_model);

            self.min_residue.clear();
            self.assumptions.reset();

            let mut model = top_model.clone();

            loop {
                match self.reduce_model(&model) {
                    Ok(true) => {}
                    Ok(false) => break,
                    Err(err) => {
                        warn!("{} in solver's iteration", err);
                        return None
                    }
                }

                self.solve();

                if let ModelSearchResult::Found(ref reduced_model) = self.last_model {
                    trace!("Reduced model: {:?}", reduced_model);
                    model = reduced_model.clone();
                } else {
                    break
                }
            }

            let min_model = top_model
                .iter()
                .map(|lit| Lit::from_var(lit.var(), !self.min_residue.contains(&lit.var())));

            match Solution::from_model(&self.context, min_model) {
                Ok(solution) => Some(solution),
                Err(err) => {
                    warn!("{} in solver's iteration", err);
                    None
                }
            }
        } else {
            None
        }
    }
}

impl Iterator for Solver<'_> {
    type Item = Solution;

    fn next(&mut self) -> Option<Self::Item> {
        let search = self.context.lock().unwrap().get_search().unwrap_or(Search::MinSolutions);

        match search {
            Search::MinSolutions => self.next_minimal_solution(),
            Search::AllSolutions => self.next_solution(),
        }
    }
}

pub struct Solution {
    context:  ContextHandle,
    model:    Vec<Lit>,
    pre_set:  Vec<NodeID>,
    post_set: Vec<NodeID>,
    fork_set: Vec<ForkID>,
    join_set: Vec<JoinID>,
}

impl Solution {
    fn new(ctx: &ContextHandle) -> Self {
        Self {
            context:  ctx.clone(),
            model:    Default::default(),
            pre_set:  Default::default(),
            post_set: Default::default(),
            fork_set: Default::default(),
            join_set: Default::default(),
        }
    }

    fn from_model<I: IntoIterator<Item = Lit>>(
        ctx: &ContextHandle,
        model: I,
    ) -> Result<Self, AcesError> {
        let mut solution = Self::new(ctx);

        let mut pre_set: BTreeSet<NodeID> = BTreeSet::new();
        let mut post_set: BTreeSet<NodeID> = BTreeSet::new();
        let mut fork_map: BTreeMap<NodeID, BTreeSet<NodeID>> = BTreeMap::new();
        let mut join_map: BTreeMap<NodeID, BTreeSet<NodeID>> = BTreeMap::new();
        let mut fork_set: BTreeSet<ForkID> = BTreeSet::new();
        let mut join_set: BTreeSet<JoinID> = BTreeSet::new();

        for lit in model {
            solution.model.push(lit);

            if lit.is_positive() {
                let (atom_id, _) = lit.into_atom_id();
                let ctx = solution.context.lock().unwrap();

                if let Some(atom) = ctx.get_atom(atom_id) {
                    match atom {
                        Atom::Tx(port) => {
                            pre_set.insert(port.get_node_id());
                        }
                        Atom::Rx(port) => {
                            post_set.insert(port.get_node_id());
                        }
                        Atom::Link(link) => {
                            let tx_node_id = link.get_tx_node_id();
                            let rx_node_id = link.get_rx_node_id();

                            fork_map
                                .entry(tx_node_id)
                                .or_insert_with(BTreeSet::new)
                                .insert(rx_node_id);
                            join_map
                                .entry(rx_node_id)
                                .or_insert_with(BTreeSet::new)
                                .insert(tx_node_id);
                        }
                        Atom::Fork(fork) => {
                            if let Some(fork_id) = fork.get_fork_id() {
                                pre_set.insert(fork.get_host_id());
                                fork_set.insert(fork_id);
                            } else {
                                return Err(AcesError::HarcMismatch)
                            }
                        }
                        Atom::Join(join) => {
                            if let Some(join_id) = join.get_join_id() {
                                post_set.insert(join.get_host_id());
                                join_set.insert(join_id);
                            } else {
                                return Err(AcesError::HarcMismatch)
                            }
                        }
                        Atom::Bottom => return Err(AcesError::BottomAtomAccess),
                    }
                } else {
                    return Err(AcesError::AtomMissingForID)
                }
            }
        }

        fork_set.extend(fork_map.into_iter().map(|(host, suit)| {
            let suit = Vec::from_iter(suit.into_iter());
            let mut fork = Harc::new_fork(host, suit);
            solution.context.lock().unwrap().share_fork(&mut fork)
        }));

        join_set.extend(join_map.into_iter().map(|(host, suit)| {
            let suit = Vec::from_iter(suit.into_iter());
            let mut join = Harc::new_join(host, suit);
            solution.context.lock().unwrap().share_join(&mut join)
        }));

        solution.pre_set.extend(pre_set.into_iter());
        solution.post_set.extend(post_set.into_iter());
        solution.fork_set.extend(fork_set.into_iter());
        solution.join_set.extend(join_set.into_iter());

        Ok(solution)
    }

    pub fn get_context(&self) -> &ContextHandle {
        &self.context
    }

    pub fn get_model(&self) -> &[Lit] {
        self.model.as_slice()
    }

    pub fn get_pre_set(&self) -> &[NodeID] {
        self.pre_set.as_slice()
    }

    pub fn get_post_set(&self) -> &[NodeID] {
        self.post_set.as_slice()
    }

    pub fn get_fork_set(&self) -> &[ForkID] {
        self.fork_set.as_slice()
    }

    pub fn get_join_set(&self) -> &[JoinID] {
        self.join_set.as_slice()
    }
}

impl fmt::Debug for Solution {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Solution {{ model: {:?}, pre_set: {}, post_set: {}, fork_set: {}, join_set: {} }}",
            self.model,
            self.pre_set.with(&self.context),
            self.post_set.with(&self.context),
            self.fork_set.with(&self.context),
            self.join_set.with(&self.context),
        )
    }
}

impl fmt::Display for Solution {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.pre_set.is_empty() {
            write!(f, "{{}} => {{")?;
        } else {
            write!(f, "{{")?;

            for node_id in self.pre_set.iter() {
                write!(f, " {}", node_id.with(&self.context))?;
            }

            write!(f, " }} => {{")?;
        }

        if self.post_set.is_empty() {
            write!(f, "}}")?;
        } else {
            for node_id in self.post_set.iter() {
                write!(f, " {}", node_id.with(&self.context))?;
            }

            write!(f, " }}")?;
        }

        Ok(())
    }
}