dtwasat.cc 35.5 KB
Newer Older
1
// -*- coding: utf-8 -*-
Alexandre Duret-Lutz's avatar
typos    
Alexandre Duret-Lutz committed
2
// Copyright (C) 2013, 2014, 2015, 2016 Laboratoire de Recherche et
3
// Développement de l'Epita.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <iostream>
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
21
#include <fstream>
22
#include <sstream>
23
24
#include <spot/twaalgos/dtwasat.hh>
#include <spot/twaalgos/dtbasat.hh>
25
26
#include <map>
#include <utility>
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <spot/twaalgos/sccinfo.hh>
#include <spot/twa/bddprint.hh>
#include <spot/twaalgos/stats.hh>
#include <spot/tl/defaultenv.hh>
#include <spot/misc/satsolver.hh>
#include <spot/misc/timer.hh>
#include <spot/twaalgos/isweakscc.hh>
#include <spot/twaalgos/isdet.hh>
#include <spot/twaalgos/dot.hh>
#include <spot/twaalgos/complete.hh>
#include <spot/misc/optionmap.hh>
#include <spot/twaalgos/sccfilter.hh>
#include <spot/twaalgos/sbacc.hh>
#include <spot/twaalgos/postproc.hh>
41

42
43
44
// If you set the SPOT_TMPKEEP environment variable the temporary
// file used to communicate with the sat solver will be left in
// the current directory.
45
//
46
47
// Additionally, if the following DEBUG macro is set to 1, the CNF
// file will be output with a comment before each clause, and an
48
// additional output file (dtwa-sat.dbg) will be created with a list
49
// of all positive variables in the result and their meaning.
50
51
52
53

#define DEBUG 0
#if DEBUG
#define dout out << "c "
54
#define trace std::cerr
55
#else
56
57
#define dout while (0) std::cout
#define trace dout
58
59
60
61
62
63
#endif

namespace spot
{
  namespace
  {
64
65
66
    static bdd_dict_ptr debug_dict = nullptr;
    static const acc_cond* debug_ref_acc = nullptr;
    static const acc_cond* debug_cand_acc = nullptr;
67
68
69

    struct transition
    {
70
      unsigned src;
71
      bdd cond;
72
      unsigned dst;
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

      transition(int src, bdd cond, int dst)
	: src(src), cond(cond), dst(dst)
      {
      }

      bool operator<(const transition& other) const
      {
	if (this->src < other.src)
	  return true;
	if (this->src > other.src)
	  return false;
	if (this->dst < other.dst)
	  return true;
	if (this->dst > other.dst)
	  return false;
	return this->cond.id() < other.cond.id();
      }

      bool operator==(const transition& other) const
      {
	return (this->src == other.src
		&& this->dst == other.dst
		&& this->cond.id() == other.cond.id());
      }
    };

100
101
    struct src_cond
    {
102
      unsigned src;
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
      bdd cond;

      src_cond(int src, bdd cond)
	: src(src), cond(cond)
      {
      }

      bool operator<(const src_cond& other) const
      {
	if (this->src < other.src)
	  return true;
	if (this->src > other.src)
	  return false;
	return this->cond.id() < other.cond.id();
      }

      bool operator==(const src_cond& other) const
      {
	return (this->src == other.src
		&& this->cond.id() == other.cond.id());
      }
    };

126
127
    struct transition_acc
    {
128
      unsigned src;
129
      bdd cond;
130
      acc_cond::mark_t acc;
131
      unsigned dst;
132

133
      transition_acc(int src, bdd cond, acc_cond::mark_t acc, int dst)
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
	: src(src), cond(cond), acc(acc), dst(dst)
      {
      }

      bool operator<(const transition_acc& other) const
      {
	if (this->src < other.src)
	  return true;
	if (this->src > other.src)
	  return false;
	if (this->dst < other.dst)
	  return true;
	if (this->dst > other.dst)
	  return false;
	if (this->cond.id() < other.cond.id())
	  return true;
	if (this->cond.id() > other.cond.id())
	  return false;
152
	return this->acc < other.acc;
153
154
155
156
157
158
159
      }

      bool operator==(const transition_acc& other) const
      {
	return (this->src == other.src
		&& this->dst == other.dst
		&& this->cond.id() == other.cond.id()
160
		&& this->acc == other.acc);
161
162
163
164
165
      }
    };

    struct path
    {
166
167
168
169
      unsigned src_cand;
      unsigned src_ref;
      unsigned dst_cand;
      unsigned dst_ref;
170
171
      acc_cond::mark_t acc_cand;
      acc_cond::mark_t acc_ref;
172

173
      path(unsigned src_cand, unsigned src_ref)
174
175
	: src_cand(src_cand), src_ref(src_ref),
	  dst_cand(src_cand), dst_ref(src_ref),
176
	  acc_cand(0U), acc_ref(0U)
177
178
179
      {
      }

180
181
      path(unsigned src_cand, unsigned src_ref,
	   unsigned dst_cand, unsigned dst_ref,
182
	   acc_cond::mark_t acc_cand, acc_cond::mark_t acc_ref)
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
	: src_cand(src_cand), src_ref(src_ref),
	  dst_cand(dst_cand), dst_ref(dst_ref),
	  acc_cand(acc_cand), acc_ref(acc_ref)
      {
      }

      bool operator<(const path& other) const
      {
	if (this->src_cand < other.src_cand)
	  return true;
	if (this->src_cand > other.src_cand)
	  return false;
	if (this->src_ref < other.src_ref)
	  return true;
	if (this->src_ref > other.src_ref)
	  return false;
	if (this->dst_cand < other.dst_cand)
	  return true;
	if (this->dst_cand > other.dst_cand)
	  return false;
	if (this->dst_ref < other.dst_ref)
	  return true;
	if (this->dst_ref > other.dst_ref)
	  return false;
207
	if (this->acc_ref < other.acc_ref)
208
	  return true;
209
	if (this->acc_ref > other.acc_ref)
210
	  return false;
211
	if (this->acc_cand < other.acc_cand)
212
	  return true;
213
	if (this->acc_cand > other.acc_cand)
214
215
216
217
218
219
220
221
222
	  return false;

	return false;
      }

    };

    std::ostream& operator<<(std::ostream& os, const transition& t)
    {
223
      os << '<' << t.src << ','
224
	 << bdd_format_formula(debug_dict, t.cond)
225
	 << ',' << t.dst << '>';
226
227
228
229
230
231
      return os;
    }


    std::ostream& operator<<(std::ostream& os, const transition_acc& t)
    {
232
233
      os << '<' << t.src << ','
	 << bdd_format_formula(debug_dict, t.cond) << ','
234
	 << debug_cand_acc->format(t.acc)
235
	 << ',' << t.dst << '>';
236
237
238
239
240
      return os;
    }

    std::ostream& operator<<(std::ostream& os, const path& p)
    {
241
242
243
244
      os << '<'
	 << p.src_cand << ','
	 << p.src_ref << ','
	 << p.dst_cand << ','
245
	 << p.dst_ref << ", "
246
247
	 << debug_cand_acc->format(p.acc_cand) << ", "
	 << debug_ref_acc->format(p.acc_ref) << '>';
248
249
250
      return os;
    }

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
    // If the DNF is
    //  Fin(1)&Fin(2)&Inf(3) | Fin(0)&Inf(3) | Fin(4)&Inf(5)&Inf(6)
    // this returns the following map:
    //  {3} => [{1,2} {0}]
    //  {5} => [{4}]
    //  {6} => [{4}]
    // We use that do detect (and disallow) what we call "silly histories",
    // i.e., transitions or histories labeled by sets such as
    // {3,1,0}, that have no way to be satisfied.  So whenever we see
    // such history in a path, we actually map it to {1,0} instead,
    // which is enough to remember that this history is not satisfiable.
    // We also forbid any transition from being labeled by {3,1,0}.
    typedef std::map<unsigned, std::vector<acc_cond::mark_t>> trimming_map;
    static trimming_map
    split_dnf_acc_by_inf(const acc_cond::acc_code& input_acc)
    {
      trimming_map res;
      auto acc = input_acc.to_dnf();
      auto pos = &acc.back();
      if (pos->op == acc_cond::acc_op::Or)
	--pos;
      acc_cond::mark_t all_fin = 0U;
      auto start = &acc.front();
      while (pos > start)
	{
	  if (pos->op == acc_cond::acc_op::Fin)
	    {
	      // We have only a Fin term, without Inf.
	      // There is nothing to do about it.
	      pos -= pos->size + 1;
	    }
	  else
	    {
	      // We have a conjunction of Fin and Inf sets.
	      auto end = pos - pos->size - 1;
	      acc_cond::mark_t fin = 0U;
	      acc_cond::mark_t inf = 0U;
	      while (pos > end)
		{
		  switch (pos->op)
		    {
		    case acc_cond::acc_op::And:
		      --pos;
		      break;
		    case acc_cond::acc_op::Fin:
		      fin |= pos[-1].mark;
		      assert(pos[-1].mark.count() == 1);
		      pos -= 2;
		      break;
		    case acc_cond::acc_op::Inf:
		      inf |= pos[-1].mark;
		      pos -= 2;
		      break;
		    case acc_cond::acc_op::FinNeg:
		    case acc_cond::acc_op::InfNeg:
		    case acc_cond::acc_op::Or:
		      SPOT_UNREACHABLE();
		      break;
		    }
		}
	      assert(pos == end);

	      all_fin |= fin;
	      for (unsigned i: inf.sets())
		if (fin)
		  {
		    res[i].emplace_back(fin);
		  }
		else
		  {
		    // Make sure the empty set is always the first one.
		    res[i].clear();
		    res[i].emplace_back(fin);
		  }
	    }
	}
      // Remove entries that are necessarily false because they
      // contain an emptyset, or entries that also appear as Fin
      // somewhere in the acceptance.
      auto i = res.begin();
      while (i != res.end())
	{
	  if (all_fin.has(i->first) || !i->second[0])
	    i = res.erase(i);
	  else
	    ++i;
	}

      return res;
    }

342
343
    struct dict
    {
344
      dict(const const_twa_ptr& a)
345
	: aut(a)
346
347
348
      {
      }

349
      const_twa_ptr aut;
350
351
352
353
354
355
356
357
358
359
      typedef std::map<transition, int> trans_map;
      typedef std::map<transition_acc, int> trans_acc_map;
      trans_map transid;
      trans_acc_map transaccid;
      typedef std::map<int, transition> rev_map;
      typedef std::map<int, transition_acc> rev_acc_map;
      rev_map revtransid;
      rev_acc_map revtransaccid;

      std::map<path, int> pathid;
360
361
362
363
364
365
366
      int nvars = 0;
      //typedef std::unordered_map<const state*, int,
      //state_ptr_hash, state_ptr_equal> state_map;
      //typedef std::unordered_map<int, const state*> int_map;
      //state_map state_to_int;
      //      int_map int_to_state;
      unsigned cand_size;
367
      unsigned int cand_nacc;
368
      acc_cond::acc_code cand_acc;
369

370
371
      std::vector<acc_cond::mark_t> all_cand_acc;
      std::vector<acc_cond::mark_t> all_ref_acc;
372
373
374
      // Markings that make no sense and that we do not want to see in
      // the candidate.  See comment above split_dnf_acc_by_inf().
      std::vector<acc_cond::mark_t> all_silly_cand_acc;
375

376
      std::vector<bool> is_weak_scc;
377
      std::vector<acc_cond::mark_t> scc_marks;
378

379
      acc_cond cacc;
380
381
      trimming_map ref_inf_trim_map;
      trimming_map cand_inf_trim_map;
382

383
384
385
386
      ~dict()
      {
	aut->get_dict()->unregister_all_my_variables(this);
      }
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

      acc_cond::mark_t
      inf_trim(acc_cond::mark_t m, trimming_map& tm)
      {
	for (auto& s: tm)
	  {
	    unsigned inf = s.first;
	    if (m.has(inf))
	      {
		bool remove = true;
		for (auto fin: s.second)
		  if (!(m & fin))
		    {
		      remove = false;
		      break;
		    }
		if (remove)
		  m.clear(inf);
	      }
	  }
	return m;
      }

      acc_cond::mark_t
      ref_inf_trim(acc_cond::mark_t m)
      {
	return inf_trim(m, ref_inf_trim_map);
      }

      acc_cond::mark_t
      cand_inf_trim(acc_cond::mark_t m)
      {
	return inf_trim(m, cand_inf_trim_map);
      }
421
422
423
    };


424
    unsigned declare_vars(const const_twa_graph_ptr& aut,
425
			  dict& d, bdd ap, bool state_based, scc_info& sm)
426
    {
427
428
429
430
431
432
433
434
435
436
437
438
439
440
      d.is_weak_scc = sm.weak_sccs();
      unsigned scccount = sm.scc_count();
      {
	auto tmp = sm.used_acc();
	d.scc_marks.reserve(scccount);
	for (auto& v: tmp)
	  {
	    acc_cond::mark_t m = 0U;
	    for (auto i: v)
	      m |= i;
	    d.scc_marks.emplace_back(m);
	  }
      }

441
      d.cacc.add_sets(d.cand_nacc);
442
443
444
445
446
447
448
449
450
451
      d.cacc.set_acceptance(d.cand_acc);

      // If the acceptance conditions use both Fin and Inf primitives,
      // we may have some silly history configurations to ignore.
      if (aut->acc().uses_fin_acceptance())
	d.ref_inf_trim_map = split_dnf_acc_by_inf(aut->get_acceptance());
      if (d.cacc.uses_fin_acceptance())
	d.cand_inf_trim_map = split_dnf_acc_by_inf(d.cand_acc);

      bdd_dict_ptr bd = aut->get_dict();
452
      d.all_cand_acc.push_back(0U);
453
454
      for (unsigned n = 0; n < d.cand_nacc; ++n)
	{
455
	  auto c = d.cacc.mark(n);
456
457
458
459
460

	  size_t ss = d.all_silly_cand_acc.size();
	  for (size_t i = 0; i < ss; ++i)
	    d.all_silly_cand_acc.push_back(d.all_silly_cand_acc[i] | c);

461
462
	  size_t s = d.all_cand_acc.size();
	  for (size_t i = 0; i < s; ++i)
463
464
465
466
467
468
469
	    {
	      acc_cond::mark_t m = d.all_cand_acc[i] | c;
	      if (d.cand_inf_trim(m) == m)
		d.all_cand_acc.push_back(m);
	      else
		d.all_silly_cand_acc.push_back(m);
	    }
470
	}
471

472
      d.all_ref_acc.push_back(0U);
473
      unsigned ref_nacc = aut->num_sets();
474
      for (unsigned n = 0; n < ref_nacc; ++n)
475
	{
476
	  auto c = aut->acc().mark(n);
477
478
	  size_t s = d.all_ref_acc.size();
	  for (size_t i = 0; i < s; ++i)
479
480
481
482
483
484
	    {
	      acc_cond::mark_t m = d.all_ref_acc[i] | c;
	      if (d.ref_inf_trim(m) != m)
		continue;
	      d.all_ref_acc.push_back(m);
	    }
485
	}
486

487
      unsigned ref_size = aut->num_states();
488

489
490
491
492
493
494
      if (d.cand_size == -1U)
	for (unsigned i = 0; i < ref_size; ++i)
	  if (sm.reachable_state(i))
	    ++d.cand_size;      // Note that we start from -1U the
				// cand_size is one less than the
				// number of reachable states.
495

496
497
498
499
500
501
      for (unsigned i = 0; i < ref_size; ++i)
	{
	  if (!sm.reachable_state(i))
	    continue;
	  unsigned i_scc = sm.scc_of(i);
	  bool is_weak = d.is_weak_scc[i_scc];
502

503
504
505
506
507
508
509
510
511
512
513
	  for (unsigned j = 0; j < d.cand_size; ++j)
	    {
	      for (unsigned k = 0; k < ref_size; ++k)
		{
		  if (!sm.reachable_state(k))
		    continue;
		  if (sm.scc_of(k) != i_scc)
		    continue;
		  for (unsigned l = 0; l < d.cand_size; ++l)
		    {
		      size_t sfp = is_weak ? 1 : d.all_ref_acc.size();
514
		      acc_cond::mark_t sccmarks = d.scc_marks[i_scc];
515
516
		      for (size_t fp = 0; fp < sfp; ++fp)
			{
517
518
			  auto refhist = d.all_ref_acc[fp];
			  // refhist cannot have more sets than used in the SCC
519
			  if (!is_weak && (sccmarks & refhist) != refhist)
520
521
			    continue;

522
523
524
525
			  size_t sf = d.all_cand_acc.size();
			  for (size_t f = 0; f < sf; ++f)
			    {
			      path p(j, i, l, k,
526
				     d.all_cand_acc[f], refhist);
527
528
			      d.pathid[p] = ++d.nvars;
			    }
529

530
531
532
533
534
			}
		    }
		}
	    }
	}
535

536
537
538
539
      if (!state_based)
	{
	  for (unsigned i = 0; i < d.cand_size; ++i)
	    for (unsigned j = 0; j < d.cand_size; ++j)
540
	      {
541
542
		bdd all = bddtrue;
		while (all != bddfalse)
543
		  {
544
545
546
547
548
549
550
551
552
553
554
		    bdd one = bdd_satoneset(all, ap, bddfalse);
		    all -= one;

		    transition t(i, one, j);
		    d.transid[t] = ++d.nvars;
		    d.revtransid.emplace(d.nvars, t);

		    // Create the variable for the accepting transition
		    // immediately afterwards.  It helps parsing the
		    // result.
		    for (unsigned n = 0; n < d.cand_nacc; ++n)
555
		      {
556
			transition_acc ta(i, one, d.cacc.mark(n), j);
557
558
			d.transaccid[ta] = ++d.nvars;
			d.revtransaccid.emplace(d.nvars, ta);
559
560
		      }
		  }
561
	      }
562
563
564
565
566
567
568
	}
      else // state based
	{
	  for (unsigned i = 0; i < d.cand_size; ++i)
	    for (unsigned n = 0; n < d.cand_nacc; ++n)
	      {
		++d.nvars;
569
		for (unsigned j = 0; j < d.cand_size; ++j)
570
571
572
573
574
575
		  {
		    bdd all = bddtrue;
		    while (all != bddfalse)
		      {
			bdd one = bdd_satoneset(all, ap, bddfalse);
			all -= one;
576

577
			transition_acc ta(i, one, d.cacc.mark(n), j);
578
579
580
581
582
583
584
585
586
587
588
589
590
			d.transaccid[ta] = d.nvars;
			d.revtransaccid.emplace(d.nvars, ta);
		      }
		  }
	      }
	  for (unsigned i = 0; i < d.cand_size; ++i)
	    for (unsigned j = 0; j < d.cand_size; ++j)
	      {
		bdd all = bddtrue;
		while (all != bddfalse)
		  {
		    bdd one = bdd_satoneset(all, ap, bddfalse);
		    all -= one;
591

592
593
594
595
596
597
598
599
		    transition t(i, one, j);
		    d.transid[t] = ++d.nvars;
		    d.revtransid.emplace(d.nvars, t);
		  }
	      }
	}
      return ref_size;
    }
600

601
602
    typedef std::pair<int, int> sat_stats;

603
    static
604
    sat_stats dtwa_to_sat(std::ostream& out, const_twa_graph_ptr ref,
605
			   dict& d, bool state_based, bool colored)
606
    {
607
608
609
#if DEBUG
      debug_dict = ref->get_dict();
#endif
610
      clause_counter nclauses;
611

612
613
      // Compute the AP used in the hard way.
      bdd ap = bddtrue;
614
      for (auto& t: ref->edges())
615
	ap &= bdd_support(t.cond);
616

617
618
619
620
621
622
623
624
625
626
627
      // Count the number of atomic propositions
      int nap = 0;
      {
	bdd cur = ap;
	while (cur != bddtrue)
	  {
	    ++nap;
	    cur = bdd_high(cur);
	  }
	nap = 1 << nap;
      }
628

629
      scc_info sm(ref);
630
      sm.determine_unknown_acceptance();
631
632
633

      // Number all the SAT variables we may need.
      unsigned ref_size = declare_vars(ref, d, ap, state_based, sm);
634
635
636
637
638

      // empty automaton is impossible
      if (d.cand_size == 0)
	{
	  out << "p cnf 1 2\n-1 0\n1 0\n";
639
	  return std::make_pair(1, 2);
640
641
642
643
644
	}

      // An empty line for the header
      out << "                                                 \n";

645
#if DEBUG
646
647
      debug_ref_acc = &ref->acc();
      debug_cand_acc = &d.cacc;
648
649
      dout << "ref_size: " << ref_size << '\n';
      dout << "cand_size: " << d.cand_size << '\n';
650
#endif
651
      auto& racc = ref->acc();
652
653
654
655
656
657
658
659

      dout << "symmetry-breaking clauses\n";
      int j = 0;
      bdd all = bddtrue;
      while (all != bddfalse)
 	{
 	  bdd s = bdd_satoneset(all, ap, bddfalse);
 	  all -= s;
660
661
 	  for (unsigned i = 0; i < d.cand_size - 1; ++i)
 	    for (unsigned k = i * nap + j + 2; k < d.cand_size; ++k)
662
663
664
	      {
		transition t(i, s, k);
		int ti = d.transid[t];
665
		dout << "¬" << t << '\n';
666
667
668
669
670
		out << -ti << " 0\n";
		++nclauses;
	      }
 	  ++j;
 	}
671
      if (!nclauses.nb_clauses())
672
673
 	dout << "(none)\n";

674
      dout << "(8) the candidate automaton is complete\n";
675
      for (unsigned q1 = 0; q1 < d.cand_size; ++q1)
676
677
678
679
680
681
682
683
684
	{
	  bdd all = bddtrue;
	  while (all != bddfalse)
	    {
	      bdd s = bdd_satoneset(all, ap, bddfalse);
	      all -= s;

#if DEBUG
	      dout;
685
	      for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
686
687
688
689
690
691
		{
		  transition t(q1, s, q2);
		  out << t << "δ";
		  if (q2 != d.cand_size)
		    out << " ∨ ";
		}
692
	      out << '\n';
693
694
#endif

695
	      for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
696
697
698
699
		{
		  transition t(q1, s, q2);
		  int ti = d.transid[t];

700
		  out << ti << ' ';
701
702
703
704
705
706
707
		}
	      out << "0\n";
	      ++nclauses;
	    }
	}

      dout << "(9) the initial state is reachable\n";
708
709
710
711
712
713
      {
	unsigned init = ref->get_init_state_number();
	dout << path(0, init) << '\n';
	out << d.pathid[path(0, init)] << " 0\n";
	++nclauses;
      }
714

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
      if (colored)
	{
	  unsigned nacc = d.cand_nacc;
	  dout << "transitions belong to exactly one of the "
	       << nacc << " acceptance set\n";
	  bdd all = bddtrue;
	  while (all != bddfalse)
	    {
	      bdd l = bdd_satoneset(all, ap, bddfalse);
	      all -= l;
	      for (unsigned q1 = 0; q1 < d.cand_size; ++q1)
		for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
		  {
		    for (unsigned i = 0; i < nacc; ++i)
		      {
			transition_acc ti(q1, l, {i}, q2);
			int tai = d.transaccid[ti];

			for (unsigned j = 0; j < nacc; ++j)
			  if (i != j)
			    {
			      transition_acc tj(q1, l, {j}, q2);
			      int taj = d.transaccid[tj];
			      out << -tai << ' ' << -taj << " 0\n";
			      ++nclauses;
			    }
		      }
		    for (unsigned i = 0; i < nacc; ++i)
		      {
			transition_acc ti(q1, l, {i}, q2);
			int tai = d.transaccid[ti];
			out << tai << ' ';
		      }
		    out << "0\n";
		    ++nclauses;
		  }
	    }
	}

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
      if (!d.all_silly_cand_acc.empty())
	{
	  dout << "no transition with silly acceptance\n";
	  bdd all = bddtrue;
	  while (all != bddfalse)
	    {
	      bdd l = bdd_satoneset(all, ap, bddfalse);
	      all -= l;
	      for (unsigned q1 = 0; q1 < d.cand_size; ++q1)
		for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
		  for (auto& s: d.all_silly_cand_acc)
		    {
		      dout << "no (" << q1 << ','
			   << bdd_format_formula(debug_dict, l)
			   << ',' << s << ',' << q2 << ")\n";
		      for (unsigned v: s.sets())
			{
			  transition_acc ta(q1, l, d.cacc.mark(v), q2);
			  int tai = d.transaccid[ta];
			  assert(tai != 0);
			  out << ' ' << -tai;
			}
		      for (unsigned v: d.cacc.comp(s).sets())
			{
			  transition_acc ta(q1, l, d.cacc.mark(v), q2);
			  int tai = d.transaccid[ta];
			  assert(tai != 0);
			  out << ' ' << tai;
			}
		      out << " 0\n";
		      ++nclauses;
		    }
	    }
	}

789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
      for (unsigned q1 = 0; q1 < d.cand_size; ++q1)
	for (unsigned q1p = 0; q1p < ref_size; ++q1p)
	  {
	    if (!sm.reachable_state(q1p))
	      continue;
	    dout << "(10) augmenting paths based on Cand[" << q1
		 << "] and Ref[" << q1p << "]\n";
	    path p1(q1, q1p);
	    int p1id = d.pathid[p1];

	    for (auto& tr: ref->out(q1p))
	      {
		unsigned dp = tr.dst;
		bdd all = tr.cond;
		while (all != bddfalse)
		  {
		    bdd s = bdd_satoneset(all, ap, bddfalse);
		    all -= s;
807

808
809
810
811
		    for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
		      {
			transition t(q1, s, q2);
			int ti = d.transid[t];
812

813
814
			path p2(q2, dp);
			int succ = d.pathid[p2];
815

816
817
			if (p1id == succ)
			  continue;
818

819
820
821
822
823
824
825
			dout << p1 << " ∧ " << t << "δ → " << p2 << '\n';
			out << -p1id << ' ' << -ti << ' ' << succ << " 0\n";
			++nclauses;
		      }
		  }
	      }
	  }
826
827

      // construction of constraints (11,12,13)
828
      for (unsigned q1p = 0; q1p < ref_size; ++q1p)
829
	{
830
831
832
833
	  if (!sm.reachable_state(q1p))
	    continue;
	  unsigned q1p_scc = sm.scc_of(q1p);
	  for (unsigned q2p = 0; q2p < ref_size; ++q2p)
834
	    {
835
836
	      if (!sm.reachable_state(q2p))
		continue;
837
838
	      // We are only interested in transition that can form a
	      // cycle, so they must belong to the same SCC.
839
	      if (sm.scc_of(q2p) != q1p_scc)
840
		continue;
841
	      bool is_weak = d.is_weak_scc[q1p_scc];
842
	      bool is_rej = sm.is_rejecting_scc(q1p_scc);
843

844
845
	      for (unsigned q1 = 0; q1 < d.cand_size; ++q1)
		for (unsigned q2 = 0; q2 < d.cand_size; ++q2)
846
847
		  {
		    size_t sf = d.all_cand_acc.size();
848
		    size_t sfp = is_weak ? 1 : d.all_ref_acc.size();
849
		    acc_cond::mark_t sccmarks = d.scc_marks[q1p_scc];
850

851
852
853
		    for (size_t f = 0; f < sf; ++f)
		      for (size_t fp = 0; fp < sfp; ++fp)
			{
854
855
			  auto refhist = d.all_ref_acc[fp];
			  // refhist cannot have more sets than used in the SCC
856
			  if (!is_weak && (sccmarks & refhist) != refhist)
857
858
			    continue;

859
			  path p(q1, q1p, q2, q2p,
860
				 d.all_cand_acc[f], refhist);
861

862
			  dout << "(11&12&13) paths from " << p << '\n';
863

864
			  int pid = d.pathid[p];
865

866
			  for (auto& tr: ref->out(q2p))
867
			    {
868
			      unsigned dp = tr.dst;
869
			      // Skip destinations not in the SCC.
870
871
			      if (sm.scc_of(dp) != q1p_scc)
				continue;
872

873
			      for (unsigned q3 = 0; q3 < d.cand_size; ++q3)
874
				{
875
				  bdd all = tr.cond;
876
				  acc_cond::mark_t curacc = tr.acc;
877
				  while (all != bddfalse)
878
				    {
879
880
				      bdd l = bdd_satoneset(all, ap, bddfalse);
				      all -= l;
881

882
883
				      transition t(q2, l, q3);
				      int ti = d.transid[t];
884

885
				      if (dp == q1p && q3 == q1) // (11,12) loop
886
					{
887
888
889
890
891
892
893
894
895
896
897
					  bool rejloop =
					    (is_rej ||
					     !racc.accepting
					     (curacc | d.all_ref_acc[fp]));

					  auto missing =
					    d.cand_acc.
					    missing(d.all_cand_acc[f],
						    !rejloop);

					  for (auto& v: missing)
898
					    {
899
#if DEBUG
900
901
902
903
904
905
					      dout << (rejloop ?
						       "(11) " : "(12) ")
						   << p << " ∧ "
						   << t << "δ → (";
					      const char* orsep = "";
					      for (int s: v)
906
						{
907
908
909
910
911
912
913
914
						  if (s < 0)
						    {
						      transition_acc
							ta(q2, l,
							   d.cacc.mark(-s - 1),
							   q1);
						      out << orsep << "¬" << ta;
						    }
915
						  else
916
917
918
919
920
921
						    {
						      transition_acc
							ta(q2, l,
							   d.cacc.mark(s), q1);
						      out << orsep << ta;
						    }
922
						  out << "FC";
923
						  orsep = " ∨ ";
924
925
						}
					      out << ")\n";
926
#endif // DEBUG
927
					      out << -pid << ' ' << -ti;
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
					      for (int s: v)
						if (s < 0)
						  {
						    transition_acc
						      ta(q2, l,
							 d.cacc.mark(-s - 1),
							 q1);
						    int tai = d.transaccid[ta];
						    assert(tai != 0);
						    out << ' ' << -tai;
						  }
						else
						  {
						    transition_acc
						      ta(q2, l,
							 d.cacc.mark(s), q1);
						    int tai = d.transaccid[ta];
						    assert(tai != 0);
						    out << ' ' << tai;
						  }
948
					      out << " 0\n";
949
950
951
					      ++nclauses;
					    }
					}
952
				      // (13) augmenting paths (always).
953
				      {
954
955
					size_t sf = d.all_cand_acc.size();
					for (size_t f = 0; f < sf; ++f)
956
					  {
957
					    acc_cond::mark_t f2 =
958
959
960
					      d.cand_inf_trim
					      (p.acc_cand |
					       d.all_cand_acc[f]);
961
					    acc_cond::mark_t f2p = 0U;
962
					    if (!is_weak)
963
964
					      f2p = d.ref_inf_trim(p.acc_ref |
								   curacc);
965

966
967
968
969
970
971
972
973
974
					    path p2(p.src_cand, p.src_ref,
						    q3, dp, f2, f2p);
					    int p2id = d.pathid[p2];
					    if (pid == p2id)
					      continue;
#if DEBUG
					    dout << "(13) " << p << " ∧ "
						 << t << "δ ";

975
976
977
					    auto biga_ = d.all_cand_acc[f];
					    for (unsigned m = 0;
						 m < d.cand_nacc; ++m)
978
					      {
979
980
981
982
983
984
985
986
						transition_acc
						  ta(q2, l,
						     d.cacc.mark(m), q3);
						const char* not_ = "¬";
						if (d.cacc.has(biga_, m))
						  not_ = "";
						out <<  " ∧ " << not_
						    << ta << "FC";
987
					      }
988
					    out << " → " << p2 << '\n';
989
#endif
990
					    out << -pid << ' ' << -ti << ' ';
991
992
993
					    auto biga = d.all_cand_acc[f];
					    for (unsigned m = 0;
						 m < d.cand_nacc; ++m)
994
					      {
995
996
997
						transition_acc
						  ta(q2, l,
						     d.cacc.mark(m), q3);
998
						int tai = d.transaccid[ta];
999
						if (biga.has(m))
1000
						  tai = -tai;
1001
						out << tai << ' ';
1002
1003
1004
1005
					      }

					    out << p2id << " 0\n";
					    ++nclauses;
1006
1007
					  }
				      }
1008
				    }
1009
1010
1011
				}
			    }
			}
1012
1013
1014
		  }
	    }
	}
1015
      out.seekp(0);
1016
      out << "p cnf " << d.nvars << ' ' << nclauses.nb_clauses();
1017
      return std::make_pair(d.nvars, nclauses.nb_clauses());
1018
1019
    }

1020
    static twa_graph_ptr
1021
    sat_build(const satsolver::solution& solution, dict& satdict,
1022
	      const_twa_graph_ptr aut, bool state_based)
1023
    {
1024
      auto autdict = aut->get_dict();
1025
      auto a = make_twa_graph(autdict);
1026
      a->copy_ap_of(aut);
1027
      if (state_based)
1028
	a->prop_state_acc(true);
1029
      a->prop_deterministic(true);
1030
      a->set_acceptance(satdict.cand_nacc, satdict.cand_acc);
1031
      a->new_states(satdict.cand_size);
1032

1033
1034
1035
1036
      // Last transition set in the automaton.
      unsigned last_aut_trans = -1U;
      // Last transition read from the SAT result.
      const transition* last_sat_trans = nullptr;
1037
1038

#if DEBUG
1039
      std::fstream out("dtwa-sat.dbg",
1040
		       std::ios_base::trunc | std::ios_base::out);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1041
      out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
1042
1043
1044
1045
      std::set<int> positive;
#endif

      dout << "--- transition variables ---\n";
1046
      std::map<int, acc_cond::mark_t> state_acc;
1047
      std::set<src_cond> seen_trans;
1048
      for (int v: solution)
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
	{
	  if (v < 0)  // FIXME: maybe we can have (v < NNN)?
	    continue;

#if DEBUG
	  positive.insert(v);
#endif

	  dict::rev_map::const_iterator t = satdict.revtransid.find(v);

	  if (t != satdict.revtransid.end())
	    {
1061
1062
1063
1064
	      // Skip (s,l,d2) if we have already seen some (s,l,d1).
	      if (seen_trans.insert(src_cond(t->second.src,
					     t->second.cond)).second)
		{
1065
		  acc_cond::mark_t acc = 0U;
1066
1067
		  if (state_based)
		    {
1068
		      auto i = state_acc.find(t->second.src);
1069
		      if (i != state_acc.end())
1070
			acc = i->second;
1071
		    }
1072

1073
1074
1075
		  last_aut_trans = a->new_edge(t->second.src,
					       t->second.dst,
					       t->second.cond, acc);
1076
1077
1078
		  last_sat_trans = &t->second;

		  dout << v << '\t' << t->second << \n";
1079
		}
1080
1081
1082
1083
1084
1085
1086
1087
1088
	    }
	  else
	    {
	      dict::rev_acc_map::const_iterator ta;
	      ta = satdict.revtransaccid.find(v);
	      // This assumes that the sat solvers output variables in
	      // increasing order.
	      if (ta != satdict.revtransaccid.end())
		{
1089
		  dout << v << '\t' << ta->second << "F\n";
1090
1091
1092
1093
1094

		  if (last_sat_trans &&
		      ta->second.src == last_sat_trans->src &&
		      ta->second.cond == last_sat_trans->cond &&
		      ta->second.dst == last_sat_trans->dst)
1095
1096
		    {
		      assert(!state_based);
1097
		      auto& v = a->edge_data(last_aut_trans).acc;
1098
		      v |= ta->second.acc;
1099
1100
1101
		    }
		  else if (state_based)
		    {
1102
1103
		      auto& v = state_acc[ta->second.src];
		      v |= ta->second.acc;
1104
		    }
1105
1106
1107
1108
		}
	    }
	}
#if DEBUG
1109
      dout << "--- pathid variables ---\n";
1110
1111
1112
      for (auto pit: satdict.pathid)
	if (positive.find(pit.second) != positive.end())
	  dout << pit.second << '\t' << pit.first << "C\n";
1113
1114
#endif

1115
      a->merge_edges();
1116
1117
1118
1119
      return a;
    }
  }

1120
  twa_graph_ptr
1121
1122
1123
1124
1125
  dtwa_sat_synthetize(const const_twa_graph_ptr& a,
		      unsigned target_acc_number,
		      const acc_cond::acc_code& target_acc,
		      int target_state_number,
		      bool state_based, bool colored)
1126
  {
1127
    if (target_state_number == 0)
1128
      return nullptr;
1129
    trace << "dtwa_sat_synthetize(..., nacc = " << target_acc_number
1130
1131
	  << ", acc = \"" << target_acc
	  << "\", states = " << target_state_number
1132
1133
	  << ", state_based = " << state_based << ")\n";

1134
1135
1136
    dict d(a);
    d.cand_size = target_state_number;
    d.cand_nacc = target_acc_number;
1137
    d.cand_acc = target_acc;
1138

1139
1140
    satsolver solver;
    satsolver::solution_pair solution;
1141

1142
1143
    timer_map t;
    t.start("encode");
1144
    sat_stats s = dtwa_to_sat(solver(), a, d, state_based, colored);
1145
1146
    t.stop("encode");
    t.start("solve");
1147
    solution = solver.get_solution();
1148
    t.stop("solve");
1149

1150
    twa_graph_ptr res = nullptr;
1151
1152
    if (!solution.second.empty())
      res = sat_build(solution.second, d, a, state_based);
1153

1154
1155
1156
1157
1158
1159
1160
1161
1162
    // Always copy the environment variable into a static string,
    // so that we (1) look it up once, but (2) won't crash if the
    // environment is changed.
    static std::string log = []()
      {
	auto s = getenv("SPOT_SATLOG");
	return s ? s : "";
      }();
    if (!log.empty())
1163
1164
1165
1166
1167
1168
1169
1170
1171
      {
	std::fstream out(log,
			 std::ios_base::app | std::ios_base::out);
	out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
	const timer& te = t.timer("encode");
	const timer& ts = t.timer("solve");
	out << target_state_number << ',';
	if (res)
	  {
1172
1173
	    twa_sub_statistics st = sub_stats_reachable(res);
	    out << st.states << ',' << st.edges << ',' << st.transitions;
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
	  }
	else
	  {
	    out << ",,";
	  }
	out << ','
	    << s.first << ',' << s.second << ','
	    << te.utime() << ',' << te.stime() << ','
	    << ts.utime() << ',' << ts.stime() << '\n';
      }
1184
    static bool show = getenv("SPOT_SATSHOW");
1185
    if (show && res)
1186
      print_dot(std::cout, res);
1187