sccfilter.cc 27.7 KB
Newer Older
1
// -*- coding: utf-8 -*-
2
3
// Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Laboratoire de
// Recherche et Développement de l'Epita (LRDE).
4
5
6
7
8
//
// 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
9
// the Free Software Foundation; either version 3 of the License, or
10
11
12
13
14
15
16
17
// (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
18
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20

#include "tgba/tgbaexplicit.hh"
21
#include "sccfilter.hh"
22
23
#include "reachiter.hh"
#include "tgbaalgos/scc.hh"
24
#include "tgbaalgos/sccinfo.hh"
25
26
27
28
29

namespace spot
{
  namespace
  {
30
31
32
33
    // BDD.id -> Acc number
    typedef std::map<int, unsigned> accremap_t;
    typedef std::vector<accremap_t> remap_table_t;

34
35
36
37
38
39
40
41
    static
    state_explicit_number::transition*
    create_transition(const tgba*, tgba_explicit_number* out_aut,
		      const state*, int in, const state*, int out)
    {
      return out_aut->create_transition(in, out);
    }

42
    static
Pierre PARUTTO's avatar
Pierre PARUTTO committed
43
    state_explicit_string::transition*
44
    create_transition(const tgba* aut, tgba_explicit_string* out_aut,
45
		      const state* in_s, int, const state* out_s, int)
46
    {
47
48
49
50
      const tgba_explicit_string* a =
	static_cast<const tgba_explicit_string*>(aut);
      return out_aut->create_transition(a->get_label(in_s),
					a->get_label(out_s));
51
52
53
    }

    static
Pierre PARUTTO's avatar
Pierre PARUTTO committed
54
    state_explicit_formula::transition*
55
56
57
58
59
60
61
62
63
    create_transition(const tgba* aut, tgba_explicit_formula* out_aut,
		      const state* in_s, int, const state* out_s, int)
    {
      const tgba_explicit_formula* a =
	static_cast<const tgba_explicit_formula*>(aut);
      const ltl::formula* in_f = a->get_label(in_s);
      const ltl::formula* out_f = a->get_label(out_s);
      if (!out_aut->has_state(in_f))
	in_f->clone();
64
      if ((in_f != out_f) && !out_aut->has_state(out_f))
65
66
67
68
	out_f->clone();
      return out_aut->create_transition(in_f, out_f);
    }

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
    template<class T>
    class filter_iter_states: public tgba_reachable_iterator_depth_first
    {
    public:
      typedef T output_t;

      filter_iter_states(const tgba* a,
			 const scc_map& sm,
			 const std::vector<bool>& useless)
	: tgba_reachable_iterator_depth_first(a),
	  out_(new T(a->get_dict())),
	  sm_(sm),
	  useless_(useless)
      {
	a->get_dict()->register_all_variables_of(a, out_);
	out_->set_acceptance_conditions(a->all_acceptance_conditions());
      }

      T*
      result()
      {
	return out_;
      }

      bool
      want_state(const state* s) const
      {
	return !useless_[sm_.scc_of_state(s)];
      }

      void
      process_link(const state* in_s, int in,
		   const state* out_s, int out,
		   const tgba_succ_iterator* si)
      {
	typename output_t::state::transition* t =
	  create_transition(this->aut_, out_, in_s, in, out_s, out);
	t->condition = si->current_condition();
	t->acceptance_conditions = si->current_acceptance_conditions();
      }

    protected:
      T* out_;
      const scc_map& sm_;
      const std::vector<bool>& useless_;
    };

116
    template<class T>
117
118
119
    class filter_iter: public tgba_reachable_iterator_depth_first
    {
    public:
Pierre PARUTTO's avatar
Pierre PARUTTO committed
120
      typedef T output_t;
121
122
      typedef std::map<int, bdd> map_t;
      typedef std::vector<map_t> remap_t;
Pierre PARUTTO's avatar
Pierre PARUTTO committed
123

124
125
      filter_iter(const tgba* a,
		  const scc_map& sm,
126
		  const std::vector<bool>& useless,
127
128
129
		  remap_table_t& remap_table,
		  unsigned max_num,
		  bool remove_all_useless)
130
	: tgba_reachable_iterator_depth_first(a),
131
	  out_(new T(a->get_dict())),
132
	  sm_(sm),
133
	  useless_(useless),
134
135
	  all_(remove_all_useless),
	  acc_(max_num)
136
      {
137
138
139
	acc_[0] = bddfalse;
	bdd tmp = a->all_acceptance_conditions();
	bdd_dict* d = a->get_dict();
140
	assert(a->number_of_acceptance_conditions() >= max_num - 1);
141
142
	if (tmp != bddfalse)
	  {
143
	    for (unsigned n = max_num - 1; n > 0; --n)
144
145
146
147
148
149
150
	      {
		assert(tmp != bddfalse);
		const ltl::formula* a = d->oneacc_to_formula(bdd_var(tmp));
		out_->declare_acceptance_condition(a->clone());
		tmp = bdd_low(tmp);
	      }
	    tmp = a->all_acceptance_conditions();
151
	    for (unsigned n = max_num - 1; n > 0; --n)
152
153
154
155
156
157
158
159
	      {
		const ltl::formula* a = d->oneacc_to_formula(bdd_var(tmp));
		acc_[n] = out_->get_acceptance_condition(a->clone());
		tmp = bdd_low(tmp);
	      }
	  }
	else
	  {
160
	    assert(max_num == 1);
161
162
163
164
165
166
167
168
169
	  }

	unsigned c = sm.scc_count();
	remap_.resize(c);
	bdd all_orig_neg = aut_->neg_acceptance_conditions();
	bdd all_sup = bdd_support(all_orig_neg);

	for (unsigned n = 0; n < c; ++n)
	  {
170
	    //std::cerr << "SCC #" << n << '\n';
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
	    if (!sm.accepting(n))
	      continue;

	    bdd all = sm.useful_acc_of(n);
	    while (all != bddfalse)
	      {
		bdd one = bdd_satoneset(all, all_sup, bddtrue);
		all -= one;
		bdd res = bddfalse;
		bdd resacc = bddfalse;
		while (one != bddtrue)
		  {
		    if (bdd_high(one) == bddfalse)
		      {
			one = bdd_low(one);
			continue;
		      }
		    int vn = bdd_var(one);
		    bdd v = bdd_ithvar(vn);
		    resacc |= bdd_exist(all_orig_neg, v) & v;
		    res |= acc_[remap_table[n][vn]];
		    one = bdd_high(one);
		  }
		int id = resacc.id();
195
		//std::cerr << resacc << " -> " << res << '\n';
196
197
198
		remap_[n][id] = res;
	      }
	  }
199
200
      }

201
      T*
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
      result()
      {
	return out_;
      }

      bool
      want_state(const state* s) const
      {
	return !useless_[sm_.scc_of_state(s)];
      }

      void
      process_link(const state* in_s, int in,
		   const state* out_s, int out,
		   const tgba_succ_iterator* si)
      {
Pierre PARUTTO's avatar
Pierre PARUTTO committed
218
	typename output_t::state::transition* t =
219
	  create_transition(this->aut_, out_, in_s, in, out_s, out);
220
221
	out_->add_conditions(t, si->current_condition());

222
223
224
225
226
227
228
229
	// Regardless of all_, do not output any acceptance condition
	// if the destination is not in an accepting SCC.
	//
	// If all_ is set, do not output any acceptance condition if the
	// source is not in the same SCC as dest.
	//
	// (See the documentation of scc_filter() for a rational.)
	unsigned u = sm_.scc_of_state(out_s);
230
231
232
233
234
235
	unsigned v = sm_.scc_of_state(in_s);
	if (sm_.accepting(u) && (!all_ || u == v))
	  {
	    bdd acc = si->current_acceptance_conditions();
	    if (acc == bddfalse)
	      return;
236
237
238
239
240
241
242
243
244
	    map_t::const_iterator i = this->remap_[u].find(acc.id());
	    if (i != this->remap_[u].end())
	      {
		t->acceptance_conditions = i->second;
	      }
	    else
	      {
		//t->acceptance_conditions = this->remap_[v][acc.id()];
	      }
245
	  }
246
247
      }

248
    protected:
249
      T* out_;
250
251
      const scc_map& sm_;
      const std::vector<bool>& useless_;
252
      bool all_;
253
254
      std::vector<bdd> acc_;
      remap_t remap_;
255
    };
256

257
258
259
  } // anonymous


260
  tgba* scc_filter(const tgba* aut, bool remove_all_useless,
261
		   scc_map* given_sm)
262
  {
263
264
265
266
267
268
269
    scc_map* sm = given_sm;
    if (!sm)
      {
	sm = new scc_map(aut);
	sm->build_map();
      }
    scc_stats ss = build_scc_stats(*sm);
270

271
272
    remap_table_t remap_table(ss.scc_total);
    std::vector<unsigned> max_table(ss.scc_total);
273
274
    std::vector<bdd> useful_table(ss.scc_total);
    std::vector<bdd> useless_table(ss.scc_total);
275
276
277
    unsigned max_num = 1;

    for (unsigned n = 0; n < ss.scc_total; ++n)
278
      {
279
	if (!sm->accepting(n))
280
	  continue;
281
	bdd all = sm->useful_acc_of(n);
282
	bdd negall = aut->neg_acceptance_conditions();
283

284
285
	//std::cerr << "SCC #" << n << "; used = " << all << std::endl;

286
	// Compute a set of useless acceptance sets.
287
288
289
290
291
292
	// If the acceptance combinations occurring in
	// the automata are  { a, ab, abc, bd }, then
	// ALL contains (a&!b&!c&!d)|(a&b&!c&!d)|(a&b&c&!d)|(!a&b&!c&d)
	// and we want to find that 'a' and 'b' are useless because
	// they always occur with 'c'.
	// The way we check if 'a' is useless is to look whether ALL
293
294
295
296
297
298
299
300
301
302
303
304
305
306
	// implies (x -> a) for some other acceptance set x.
	//
	// The two while() loops in the code perform the equivalent of
	//    for all a in allconds_a:
	//       for all x in allconds_x:
	//          check whether x -> a
	//          ...
	//
	// Initially allconds_a = allconds_x contains all acceptance
	// sets.  However when an acceptance set 'a' is determined to
	// be useless, it can be removed from allconds_x from future
	// iterations.
	bdd allconds_a = bdd_support(negall);
	bdd allconds_x = allconds_a;
307
	bdd useless = bddtrue;
308
	while (allconds_a != bddtrue)
309
	  {
310
	    // Speed-up the computation of implied acceptance sets by
311
312
313
314
315
316
317
	    // removing those that are always present.  We detect
	    // those that appear as conjunction of positive variables
	    // at the start of ALL.
	    bdd prefix = bdd_satprefix(all);
	    if (prefix != bddtrue)
	      {
		assert(prefix == bdd_support(prefix));
318
319
		allconds_a = bdd_exist(allconds_a, prefix);
		if (allconds_a != bddtrue)
320
321
322
323
324
325
326
327
328
		  {
		    useless &= prefix;
		  }
		else
		  {
		    // Never erase all conditions: at least keep one.
		    useless &= bdd_high(prefix);
		    break;
		  }
329
		allconds_x = bdd_exist(allconds_x, prefix);
330
331
	      }

332
333
334
335
336
	    // Pick an acceptance set 'a'.
	    bdd a = bdd_ithvar(bdd_var(allconds_a));
	    // For all acceptance sets 'x' that are not already
	    // useless...
	    bdd others = allconds_x;
337
	    while (others != bddtrue)
338
	      {
339
		bdd x = bdd_ithvar(bdd_var(others));
340
		// ... check whether 'x' always implies 'a'.
341
		if (x != a && bdd_implies(all, x >> a))
342
		  {
343
		    // If so, 'a' is useless.
344
		    all = bdd_exist(all, a);
345
		    useless &= a;
346
		    allconds_x = bdd_exist(allconds_x, a);
347
348
		    break;
		  }
349
		others = bdd_high(others);
350
	      }
351
	    allconds_a = bdd_high(allconds_a);
352
353
	  }

354
355
	// We never remove ALL acceptance marks.
	assert(negall == bddtrue || useless != bdd_support(negall));
356

357
	useless_table[n] = useless;
358
359
	bdd useful = bdd_exist(negall, useless);

360
361
	//std::cerr << "SCC #" << n << "; useful = " << useful << std::endl;

362
363
364
365
366
367
368
369
370
	// Go over all useful sets of acceptance marks, and give them
	// a number.
	unsigned num = 1;
	// First compute the number of acceptance conditions used.
	for (BDD c = useful.id(); c != 1; c = bdd_low(c))
	  ++num;
	max_table[n] = num;
	if (num > max_num)
	  max_num = num;
371
372
373
374
375
376
377
378
379
380
381

	useful_table[n] = useful;
      }

    // Now that we know about the max number of acceptance conditions,
    // use add extra acceptance conditions to those SCC that do not
    // have enough.
    for (unsigned n = 0; n < ss.scc_total; ++n)
      {
	if (!sm->accepting(n))
	  continue;
382
	//std::cerr << "SCC " << n << '\n';
383
384
385
386
387
388
389
390
391
392
393
	bdd useful = useful_table[n];

	int missing = max_num - max_table[n];
	bdd useless = useless_table[n];
	while (missing--)
	  {
	    //std::cerr << useful << "  :  " << useless << std::endl;
	    useful &= bdd_nithvar(bdd_var(useless));
	    useless = bdd_high(useless);
	  }
	int num = max_num;
394
395
396
397
398
399
	// Then number all of these acceptance conditions in the
	// reverse order.  This makes sure that the associated number
	// varies in the same direction as the bdd variables, which in
	// turn makes sure we preserve the acceptance condition
	// ordering (which matters for degeneralization).
	for (BDD c = useful.id(); c != 1; c = bdd_low(c))
400
	  remap_table[n].emplace(bdd_var(c), --num);
401
402

	max_table[n] = max_num;
403
      }
404

405
    tgba* ret;
406
407
408
409
410
411
412
413
414
415
    // In most cases we will create a tgba_explicit_string copy of the
    // initial tgba, but this is not very space efficient as the
    // labels are built using the "format_state()" string output of
    // the original automaton.  In the case where the source automaton is
    // a tgba_explicit_formula (typically after calling ltl2tgba_fm())
    // we can create another tgba_explicit_formula instead.
    const tgba_explicit_formula* af =
      dynamic_cast<const tgba_explicit_formula*>(aut);
    if (af)
      {
416
417
418
419
420
421
422
423
	filter_iter<tgba_explicit_formula> fi(af, *sm,
					      ss.useless_scc_map,
					      remap_table, max_num,
					      remove_all_useless);
	fi.run();
	tgba_explicit_formula* res = fi.result();
	res->merge_transitions();
	ret = res;
424
      }
425
426
    else
      {
427
428
429
430
431
432
433
434
435
436
437
438
439
440
	const tgba_explicit_string* as =
	  dynamic_cast<const tgba_explicit_string*>(aut);
	if (as)
	  {
	    filter_iter<tgba_explicit_string> fi(aut, *sm, ss.useless_scc_map,
						 remap_table, max_num,
						 remove_all_useless);
	    fi.run();
	    tgba_explicit_string* res = fi.result();
	    res->merge_transitions();
	    ret = res;
	  }
	else
	  {
441
442
443
444
445
446
447
448
	    filter_iter<tgba_explicit_number> fi(aut, *sm,
						 ss.useless_scc_map,
						 remap_table, max_num,
						 remove_all_useless);
	    fi.run();
	    tgba_explicit_number* res = fi.result();
	    res->merge_transitions();
	    ret = res;
449
	  }
450
      }
451
452
453
    if (!given_sm)
      delete sm;
    return ret;
454
455
  }

456
457
  tgba* scc_filter_states(const tgba* aut, scc_map* given_sm)
  {
458
459
460
461
    const tgba_digraph* autg = dynamic_cast<const tgba_digraph*>(aut);
    if (autg && !given_sm)
      return scc_filter_states(autg, nullptr);

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
    scc_map* sm = given_sm;
    if (!sm)
      {
	sm = new scc_map(aut);
	sm->build_map();
      }
    scc_stats ss = build_scc_stats(*sm);

    tgba* ret;

    const tgba_explicit_formula* af =
      dynamic_cast<const tgba_explicit_formula*>(aut);
    if (af)
      {
	filter_iter_states<tgba_explicit_formula> fi(af, *sm,
						     ss.useless_scc_map);
	fi.run();
	tgba_explicit_formula* res = fi.result();
	res->merge_transitions();
	ret = res;
      }
    else
      {
	const tgba_explicit_string* as =
	  dynamic_cast<const tgba_explicit_string*>(aut);
	if (as)
	  {
	    filter_iter_states<tgba_explicit_string> fi(aut, *sm,
							ss.useless_scc_map);
	    fi.run();
	    tgba_explicit_string* res = fi.result();
	    res->merge_transitions();
	    ret = res;
	  }
	else
	  {
	    filter_iter_states<tgba_explicit_number> fi(aut, *sm,
							ss.useless_scc_map);
	    fi.run();
	    tgba_explicit_number* res = fi.result();
	    res->merge_transitions();
	    ret = res;
	  }
      }
    if (!given_sm)
      delete sm;
    return ret;
  }

511
512
513
514

  //////////////////////////////////////////////////////////////////////
  // The goal is to remove all the code above this line eventually, so
  // do not waste your time code common to both sides of this note.
515
516
517
  //////////////////////////////////////////////////////////////////////

  namespace
518
  {
519
520

    typedef std::tuple<bool, bdd, bdd> filtered_trans;
521
    typedef std::pair<bdd, bdd> acc_pair;
522

523

524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
    // SCC filters are objects with two methods:
    //  state(src) return true iff s should be kept
    //  trans(src, dst, cond, acc) returns a triplet
    //     (keep, cond2, acc2) where keep is a Boolean stating if the
    //                      transition should be kept, and cond2/acc2
    //                      give replacement values for cond/acc
    struct id_filter
    {
      scc_info* si;
      id_filter(scc_info* si)
	: si(si)
      {
      }

      // Accept all states
      bool state(unsigned)
      {
	return true;
      }

544
545
546
547
548
      acc_pair accsets(bdd all, bdd all_neg)
      {
	return acc_pair(all, all_neg);
      }

549
550
551
552
553
554
555
556
      // Accept all transitions, unmodified
      filtered_trans trans(unsigned, unsigned, bdd cond, bdd acc)
      {
	return filtered_trans{true, cond, acc};
      }
    };

    // Remove useless states.
557
558
    template <class next_filter = id_filter>
    struct state_filter: next_filter
559
    {
560
561
562
      template<typename... Args>
      state_filter(scc_info* si, Args&&... args)
	: next_filter(si, std::forward<Args>(args)...)
563
564
      {
      }
565
566
567

      bool state(unsigned s)
      {
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
	return this->next_filter::state(s) && this->si->is_useful_state(s);
      }
    };

    // Suspension filter, used only by compsusp.cc
    template <class next_filter = id_filter>
    struct susp_filter: next_filter
    {
      bdd suspvars;
      bdd ignoredvars;
      bool early_susp;

      template<typename... Args>
      susp_filter(scc_info* si,
		  bdd suspvars, bdd ignoredvars, bool early_susp,
		  Args&&... args)
	: next_filter(si, std::forward<Args>(args)...),
	  suspvars(suspvars),
	  ignoredvars(ignoredvars),
	  early_susp(early_susp)
      {
      }

      filtered_trans trans(unsigned src, unsigned dst,
			   bdd cond, bdd acc)
      {
	bool keep;
	std::tie(keep, cond, acc) =
	  this->next_filter::trans(src, dst, cond, acc);

	if (keep)
	  {
	    // Always remove ignored variables
	    cond = bdd_exist(cond, ignoredvars);

	    // Remove the suspension variables only if
	    // the destination in not in an accepting SCC,
	    // or if we are between SCC with early_susp unset.
	    unsigned u = this->si->scc_of(dst);
	    if (!this->si->is_accepting_scc(u)
		|| (!early_susp && (u != this->si->scc_of(src))))
	      cond = bdd_exist(cond, suspvars);
	  }

	return filtered_trans(keep, cond, acc);
613
614
615
616
617
      }
    };

    // Remove acceptance conditions from all transitions outside of
    // non-accepting SCCs.
618
619
    template <class next_filter = id_filter>
    struct acc_filter_all: next_filter
620
    {
621
622
623
      template<typename... Args>
      acc_filter_all(scc_info* si, Args&&... args)
	: next_filter(si, std::forward<Args>(args)...)
624
625
626
627
628
629
      {
      }

      filtered_trans trans(unsigned src, unsigned dst,
			   bdd cond, bdd acc)
      {
630
631
632
	bool keep;
	std::tie(keep, cond, acc) =
	  this->next_filter::trans(src, dst, cond, acc);
633

634
635
636
637
638
639
640
641
642
643
	if (keep)
	  {
	    unsigned u = this->si->scc_of(src);
	    // If the transition is between two SCCs, or in a
	    // non-accepting SCC.  Remove the acceptance sets.
	    if (!this->si->is_accepting_scc(u) || u != this->si->scc_of(dst))
	      acc = bddfalse;
	  }

	return filtered_trans(keep, cond, acc);
644
645
646
647
648
      }
    };

    // Remove acceptance conditions from all transitions whose
    // destination is not an accepting SCCs.
649
650
    template <class next_filter = id_filter>
    struct acc_filter_some: next_filter
651
    {
652
653
654
      template<typename... Args>
      acc_filter_some(scc_info* si, Args&&... args)
	: next_filter(si, std::forward<Args>(args)...)
655
656
657
      {
      }

658
      filtered_trans trans(unsigned src, unsigned dst,
659
660
			   bdd cond, bdd acc)
      {
661
662
663
664
665
	bool keep;
	std::tie(keep, cond, acc) =
	  this->next_filter::trans(src, dst, cond, acc);

	if (!this->si->is_accepting_scc(this->si->scc_of(dst)))
666
	  acc = bddfalse;
667
	return filtered_trans(keep, cond, acc);
668
669
670
      }
    };

671
672
673
    // Simplify redundant acceptance sets used in each SCCs.
    template <class next_filter = id_filter>
    struct acc_filter_simplify: next_filter
674
675
676
677
678
679
    {
      std::vector<bdd> acc_;
      typedef std::map<int, bdd> map_t;
      typedef std::vector<map_t> remap_t;
      remap_t remap_;

680
681
682
      template<typename... Args>
      acc_filter_simplify(scc_info* si, Args&&... args)
	: next_filter(si, std::forward<Args>(args)...)
683
684
685
686
687
      {
      }

      acc_pair accsets(bdd in_all, bdd in_all_neg)
      {
688
689
690
691
	std::tie(in_all, in_all_neg) =
	  this->next_filter::accsets(in_all, in_all_neg);

	unsigned scc_count = this->si->scc_count();
692
693
694
695
696
	remap_table_t remap_table(scc_count);
	std::vector<unsigned> max_table(scc_count);
	std::vector<bdd> useful_table(scc_count);
	std::vector<bdd> useless_table(scc_count);
	unsigned max_num = 1;
697
	const tgba_digraph* aut = this->si->get_aut();
698

699
	std::vector<bdd> used_acc = this->si->used_acc();
700
701
702

	for (unsigned n = 0; n < scc_count; ++n)
	  {
703
	    if (!this->si->is_accepting_scc(n))
704
705
706
707
708
709
710
711
712
713
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
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
	      continue;
	    bdd all = used_acc[n];

	    //std::cerr << "SCC #" << n << "; used = " << all << std::endl;

	    // Compute a set of useless acceptance sets.
	    // If the acceptance combinations occurring in
	    // the automata are  { a, ab, abc, bd }, then
	    // ALL contains (a&!b&!c&!d)|(a&b&!c&!d)|(a&b&c&!d)|(!a&b&!c&d)
	    // and we want to find that 'a' and 'b' are useless because
	    // they always occur with 'c'.
	    // The way we check if 'a' is useless is to look whether ALL
	    // implications (x -> a) for some other acceptance set x.
	    //
	    // The two while() loops in the code perform the equivalent of
	    //    for all a in allconds_a:
	    //       for all x in allconds_x:
	    //          check whether x -> a
	    //          ...
	    //
	    // Initially allconds_a = allconds_x contains all acceptance
	    // sets.  However when an acceptance set 'a' is determined to
	    // be useless, it can be removed from allconds_x from future
	    // iterations.
	    bdd allconds_a = bdd_support(in_all_neg);
	    bdd allconds_x = allconds_a;
	    bdd useless = bddtrue;
	    while (allconds_a != bddtrue)
	      {
		// Speed-up the computation of implied acceptance sets by
		// removing those that are always present.  We detect
		// those that appear as conjunction of positive variables
		// at the start of ALL.
		bdd prefix = bdd_satprefix(all);
		if (prefix != bddtrue)
		  {
		    assert(prefix == bdd_support(prefix));
		    allconds_a = bdd_exist(allconds_a, prefix);
		    if (allconds_a != bddtrue)
		      {
			useless &= prefix;
		      }
		    else
		      {
			// Never erase all conditions: at least keep one.
			useless &= bdd_high(prefix);
			break;
		      }
		    allconds_x = bdd_exist(allconds_x, prefix);
		  }

		// Pick an acceptance set 'a'.
		bdd a = bdd_ithvar(bdd_var(allconds_a));
		// For all acceptance sets 'x' that are not already
		// useless...
		bdd others = allconds_x;
		while (others != bddtrue)
		  {
		    bdd x = bdd_ithvar(bdd_var(others));
		    // ... check whether 'x' always implies 'a'.
		    if (x != a && bdd_implies(all, x >> a))
		      {
			// If so, 'a' is useless.
			all = bdd_exist(all, a);
			useless &= a;
			allconds_x = bdd_exist(allconds_x, a);
			break;
		      }
		    others = bdd_high(others);
		  }
		allconds_a = bdd_high(allconds_a);
	      }

	    // We never remove ALL acceptance marks.
	    assert(in_all_neg == bddtrue || useless != bdd_support(in_all_neg));

	    useless_table[n] = useless;
	    bdd useful = bdd_exist(in_all_neg, useless);

	    //std::cerr << "SCC #" << n << "; useful = " << useful << std::endl;

	    // Go over all useful sets of acceptance marks, and give them
	    // a number.
	    unsigned num = 1;
	    // First compute the number of acceptance conditions used.
	    for (BDD c = useful.id(); c != 1; c = bdd_low(c))
	      ++num;
	    max_table[n] = num;
	    if (num > max_num)
	      max_num = num;

	    useful_table[n] = useful;
	  }

	// Now that we know about the max number of acceptance
	// conditions, add extra acceptance conditions to those SCC
	// that do not have enough.
	for (unsigned n = 0; n < scc_count; ++n)
	  {
803
	    if (!this->si->is_accepting_scc(n))
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
	      continue;
	    //std::cerr << "SCC " << n << '\n';
	    bdd useful = useful_table[n];

	    int missing = max_num - max_table[n];
	    bdd useless = useless_table[n];
	    while (missing--)
	      {
		//std::cerr << useful << "  :  " << useless << std::endl;
		useful &= bdd_nithvar(bdd_var(useless));
		useless = bdd_high(useless);
	      }
	    int num = max_num;
	    // Then number all of these acceptance conditions in the
	    // reverse order.  This makes sure that the associated number
	    // varies in the same direction as the bdd variables, which in
	    // turn makes sure we preserve the acceptance condition
	    // ordering (which matters for degeneralization).
	    for (BDD c = useful.id(); c != 1; c = bdd_low(c))
823
	      remap_table[n].emplace(bdd_var(c), --num);
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866

	    max_table[n] = max_num;
	  }

	acc_.resize(max_num);
	acc_[0] = bddfalse;
	bdd tmp = in_all;
	assert(aut->number_of_acceptance_conditions() >= max_num - 1);

	bdd all = bddfalse;
	bdd all_neg = bddtrue;

	if (tmp != bddfalse)
	  {
	    for (unsigned n = max_num - 1; n > 0; --n)
	      {
	    	assert(tmp != bddfalse);
		int v = bdd_var(tmp);
		bdd vn = bdd_nithvar(v);
		all = (all & vn) | (all_neg & bdd_ithvar(v));
		all_neg &= vn;
	    	tmp = bdd_low(tmp);
	      }
	    tmp = in_all;
	    for (unsigned n = max_num - 1; n > 0; --n)
	      {
		int v = bdd_var(tmp);
		acc_[n] = bdd_compose(all_neg, bdd_nithvar(v), v);
		tmp = bdd_low(tmp);
	      }
	  }
	else
	  {
	    assert(max_num == 1);
	  }

	remap_.resize(scc_count);
	bdd all_orig_neg = in_all_neg;
	bdd all_sup = bdd_support(all_orig_neg);

	for (unsigned n = 0; n < scc_count; ++n)
	  {
	    //std::cerr << "SCC #" << n << '\n';
867
	    if (!this->si->is_accepting_scc(n))
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
	      continue;

	    bdd all = used_acc[n];
	    while (all != bddfalse)
	      {
		bdd one = bdd_satoneset(all, all_sup, bddtrue);
		all -= one;
		bdd res = bddfalse;
		bdd resacc = bddfalse;
		while (one != bddtrue)
		  {
		    if (bdd_high(one) == bddfalse)
		      {
			one = bdd_low(one);
			continue;
		      }
		    int vn = bdd_var(one);
		    bdd v = bdd_ithvar(vn);
		    resacc |= bdd_exist(all_orig_neg, v) & v;
		    res |= acc_[remap_table[n][vn]];
		    one = bdd_high(one);
		  }
		int id = resacc.id();
		//std::cerr << resacc << " -> " << res << '\n';
		remap_[n][id] = res;
	      }
	  }
	return acc_pair{all, all_neg};
      }

898
      filtered_trans trans(unsigned src, unsigned dst, bdd cond, bdd acc)
899
      {
900
901
902
903
904
	bool keep;
	std::tie(keep, cond, acc) =
	  this->next_filter::trans(src, dst, cond, acc);

	if (keep && acc != bddfalse)
905
	  {
906
	    unsigned u = this->si->scc_of(src);
907
908
909
910
911
912
	    auto i = remap_[u].find(acc.id());
	    if (i != remap_[u].end())
	      acc = i->second;
	    else
	      acc = bddfalse;
	  }
913
	return filtered_trans{keep, cond, acc};
914
915
916
917
918
      }

    };


919
    template<class F, typename... Args>
920
    tgba_digraph* scc_filter_apply(const tgba_digraph* aut,
921
				   scc_info* given_si, Args&&... args)
922
923
924
925
926
927
    {
      // Compute scc_info if not supplied.
      scc_info* si = given_si;
      if (!si)
	si = new scc_info(aut);

928
      F filter(si, std::forward<Args>(args)...);
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943

      // Renumber all useful states.
      unsigned in_n = aut->num_states(); // Number of input states.
      unsigned out_n = 0;		 // Number of output states.
      std::vector<unsigned> inout; // Associate old states to new ones.
      inout.reserve(in_n);
      for (unsigned i = 0; i < in_n; ++i)
	if (filter.state(i))
	  inout.push_back(out_n++);
	else
	  inout.push_back(-1U);

      bdd_dict* bd = aut->get_dict();
      tgba_digraph* filtered = new tgba_digraph(bd);
      bd->register_all_variables_of(aut, filtered);
944
945
946
947
948
      {
	bdd all = aut->all_acceptance_conditions();
	bdd neg = aut->neg_acceptance_conditions();
	filtered->set_acceptance_conditions(filter.accsets(all, neg).first);
      }
949
      filtered->new_states(out_n);
950
951
952
953
954
      for (unsigned isrc = 0; isrc < in_n; ++isrc)
	{
	  unsigned osrc = inout[isrc];
	  if (osrc >= out_n)
	    continue;
955
	  for (auto& t: aut->out(isrc))
956
957
958
959
960
961
962
963
964
965
	    {
	      unsigned odst = inout[t.dst];
	      if (odst >= out_n)
		continue;
	      bool want;
	      bdd cond;
	      bdd acc;
	      std::tie(want, cond, acc) =
		filter.trans(isrc, t.dst, t.cond, t.acc);
	      if (want)
966
		filtered->new_transition(osrc, odst, cond, acc);
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
	    }
	}
      if (!given_si)
	delete si;
      // If the initial state has been filtered out, we don't attempt
      // to fix it.
      auto init = inout[aut->get_init_state_number()];
      if (init < out_n)
	filtered->set_init_state(init);
      return filtered;
    }


  }

  tgba_digraph*
  scc_filter_states(const tgba_digraph* aut, scc_info* given_si)
  {
985
    return scc_filter_apply<state_filter<>>(aut, given_si);
986
987
988
989
990
991
992
  }

  tgba_digraph*
  scc_filter(const tgba_digraph* aut, bool remove_all_useless,
	     scc_info* given_si)
  {
    if (remove_all_useless)
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
      return scc_filter_apply<state_filter
			      <acc_filter_all
			       <acc_filter_simplify<>>>>(aut, given_si);
    else
      return scc_filter_apply<state_filter
			      <acc_filter_some
			       <acc_filter_simplify<>>>>(aut, given_si);
  }

  tgba_digraph*
  scc_filter_susp(const tgba_digraph* aut, bool remove_all_useless,
		  bdd suspvars, bdd ignoredvars, bool early_susp,
		  scc_info* given_si)
  {
    if (remove_all_useless)
      return scc_filter_apply<susp_filter
			      <state_filter
			       <acc_filter_all
				<acc_filter_simplify<>>>>>(aut, given_si,
							   suspvars,
							   ignoredvars,
							   early_susp);
1015
    else
1016
1017
1018
1019
1020
1021
1022
      return scc_filter_apply<susp_filter
			      <state_filter
			       <acc_filter_some
				<acc_filter_simplify<>>>>>(aut, given_si,
							   suspvars,
							   ignoredvars,
							   early_susp);
1023
1024
  }

1025
}