__init__.py 30.9 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2014, 2015, 2016  Laboratoire de
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Recherche et Développement de l'Epita (LRDE).
#
# 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/>.

20
21
22
23
24
25
26
27

import sys


if sys.hexversion < 0x03030000:
    sys.exit("This module requires Python 3.3 or newer")


28
from spot.impl import *
29
30
31
32
from spot.aux import \
     extend as _extend, \
     str_to_svg as _str_to_svg, \
     ostream_to_svg as _ostream_to_svg
33
import subprocess
34
35
import os
import signal
36

37

38
# The parrameters used by default when show() is called on an automaton.
39
_show_default = None
40

41

42
43
44
def setup(**kwargs):
    """Configure Spot for fancy display.

45
    This is manly useful in Jupyter/IPython.
46

47
48
    Note that this function needs to be called before any automaton is
    displayed.  Afterwards it will have no effect (you should restart
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    Python, or the Jupyter/IPython Kernel).

    Parameters
    ----------
    bullets : bool
        whether to display acceptance conditions as UTF8 bullets
        (default: True)
    fillcolor : str
        the color to use for states (default: '#ffffaa')
    size : str
        the width and height of the GraphViz output in inches
        (default: '10.2,5')
    font : str
        the font to use in the GraphViz output (default: 'Lato')
63
64
    show_default : str
        default options for show()
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
65
66
    max_states : int
        maximum number of states in GraphViz output (default: 50)
67
    """
Etienne Renault's avatar
Etienne Renault committed
68
    import os
69

70
71
    s = ('size="{}" edge[arrowhead=vee, arrowsize=.7]')
    os.environ['SPOT_DOTEXTRA'] = s.format(kwargs.get('size', '10.2,5'))
72
73

    bullets = 'B' if kwargs.get('bullets', True) else ''
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
74
    max_states = '<' + str(kwargs.get('max_states', 50))
75
76
77
    d = 'rf({})C({}){}'.format(kwargs.get('font', 'Lato'),
                               kwargs.get('fillcolor', '#ffffaa'),
                               bullets + max_states)
78
79
    global _show_default
    _show_default = kwargs.get('show_default', None)
80
81
    os.environ['SPOT_DOTDEFAULT'] = d

82

83
84
85
86
# In version 3.0.2, Swig puts strongly typed enum in the main
# namespace without prefixing them.  Latter versions fix this.  So we
# can remove for following hack once 3.0.2 is no longer used in our
# build farm.
87
if 'op_ff' not in globals():
88
89
90
91
92
93
    for i in ('ff', 'tt', 'eword', 'ap', 'Not', 'X', 'F', 'G',
              'Closure', 'NegClosure', 'NegClosureMarked',
              'Xor', 'Implies', 'Equiv', 'U', 'R', 'W', 'M',
              'EConcat', 'EConcatMarked', 'UConcat', 'Or',
              'OrRat', 'And', 'AndRat', 'AndNLM', 'Concat',
              'Fusion', 'Star', 'FStar'):
94
        globals()['op_' + i] = globals()[i]
95
96
97
        del globals()[i]


98
99
# Global BDD dict so that we do not have to create one in user code.
_bdd_dict = make_bdd_dict()
Etienne Renault's avatar
Etienne Renault committed
100

101

102
103
104
105
106
@_extend(twa, ta)
class twa:
    def _repr_svg_(self, opt=None):
        """Output the automaton as SVG"""
        ostr = ostringstream()
107
108
109
        if opt is None:
            global _show_default
            opt = _show_default
110
111
112
113
114
        print_dot(ostr, self, opt)
        return _ostream_to_svg(ostr)

    def show(self, opt=None):
        """Display the automaton as SVG, in the IPython/Jupyter notebook"""
115
116
117
        if opt is None:
            global _show_default
            opt = _show_default
118
119
120
121
122
123
        # Load the SVG function only if we need it. This way the
        # bindings can still be used outside of IPython if IPython is
        # not installed.
        from IPython.display import SVG
        return SVG(self._repr_svg_(opt))

124
125
126
127
128
129
130
131
132
    def highlight_states(self, states, color):
        for state in states:
            self.highlight_state(state, color)
        return self

    def highlight_edges(self, edges, color):
        for edge in edges:
            self.highlight_edge(edge, color)
        return self
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

@_extend(twa)
class twa:
    def to_str(a, format='hoa', opt=None):
        format = format.lower()
        if format == 'hoa':
            ostr = ostringstream()
            print_hoa(ostr, a, opt)
            return ostr.str()
        if format == 'dot':
            ostr = ostringstream()
            print_dot(ostr, a, opt)
            return ostr.str()
        if format == 'spin':
            ostr = ostringstream()
            print_never_claim(ostr, a, opt)
            return ostr.str()
        if format == 'lbtt':
            ostr = ostringstream()
            print_lbtt(ostr, a, opt)
            return ostr.str()
154
        raise ValueError("unknown string format: " + format)
155

156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    def save(a, filename, format='hoa', opt=None, append=False):
        with open(filename, 'a' if append else 'w') as f:
            s = a.to_str(format, opt)
            f.write(s)
            if s[-1] != '\n':
                f.write('\n')
        return a


@_extend(formula)
class formula:
    def __init__(self, str):
        """Parse the given string to create a formula."""
        self.this = parse_formula(str)

    def show_ast(self):
        """Display the syntax tree of the formula."""
        # Load the SVG function only if we need it. This way the bindings
        # can still be used outside of IPython if IPython is not
        # installed.
        from IPython.display import SVG
177
        return SVG(_str_to_svg(self.to_str('d')))
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

    def to_str(self, format='spot', parenth=False):
        if format == 'spot' or format == 'f':
            return str_psl(self, parenth)
        elif format == 'spin' or format == 's':
            return str_spin_ltl(self, parenth)
        elif format == 'utf8' or format == '8':
            return str_utf8_psl(self, parenth)
        elif format == 'lbt' or format == 'l':
            return str_lbt_ltl(self)
        elif format == 'wring' or format == 'w':
            return str_wring_ltl(self)
        elif format == 'latex' or format == 'x':
            return str_latex_psl(self, parenth)
        elif format == 'sclatex' or format == 'X':
            return str_sclatex_psl(self, parenth)
194
195
196
197
        elif format == 'dot' or format == 'd':
            ostr = ostringstream()
            print_dot_psl(ostr, self)
            return ostr.str().encode('utf-8')
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
        else:
            raise ValueError("unknown string format: " + format)

    def __format__(self, spec):
        """Format the formula according to `spec`.

        Parameters
        ----------
        spec : str, optional
            a list of letters that specify how the formula
            should be formatted.

        Supported specifiers
        --------------------

        - 'f': use Spot's syntax (default)
        - '8': use Spot's syntax in UTF-8 mode
        - 's': use Spin's syntax
        - 'l': use LBT's syntax
        - 'w': use Wring's syntax
        - 'x': use LaTeX output
        - 'X': use self-contained LaTeX output

        Add some of those letters for additional options:

        - 'p': use full parentheses
        - 'c': escape the formula for CSV output (this will
               enclose the formula in double quotes, and escape
               any included double quotes)
        - 'h': escape the formula for HTML output
        - 'd': escape double quotes and backslash,
               for use in C-strings (the outermost double
               quotes are *not* added)
        - 'q': quote and escape for shell output, using single
               quotes or double quotes depending on the contents.
233
234
        - '[...]': rewrite away all the operators specified in brackets,
               using spot.unabbreviate().
235
236
237
238
239
240
241
242
243
244

        - ':spec': pass the remaining specification to the
                   formating function for strings.

        """

        syntax = 'f'
        parent = False
        escape = None

245
246
        form = self

247
248
249
250
251
252
253
254
255
256
        while spec:
            c, spec = spec[0], spec[1:]
            if c in ('f', 's', '8', 'l', 'w', 'x', 'X'):
                syntax = c
            elif c == 'p':
                parent = True
            elif c in ('c', 'd', 'h', 'q'):
                escape = c
            elif c == ':':
                break
257
258
259
260
261
262
            elif c == '[':
                pos = spec.find(']')
                if pos < 0:
                    raise ValueError("unclosed bracket: [" + spec)
                form = form.unabbreviate(spec[0:pos])
                spec = spec[pos+1:]
263
264
265
            else:
                raise ValueError("unknown format specification: " + c + spec)

266
        s = form.to_str(syntax, parent)
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

        if escape == 'c':
            o = ostringstream()
            escape_rfc4180(o, s)
            s = '"' + o.str() + '"'
        elif escape == 'd':
            s = escape_str(s)
        elif escape == 'h':
            o = ostringstream()
            escape_html(o, s)
            s = o.str()
        elif escape == 'q':
            o = ostringstream()
            quote_shell_string(o, s)
            s = o.str()

        return s.__format__(spec)

    def traverse(self, func):
        if func(self):
            return
        for f in self:
            f.traverse(func)

    def map(self, func):
        k = self.kind()
        if k in (op_ff, op_tt, op_eword, op_ap):
            return self
        if k in (op_Not, op_X, op_F, op_G, op_Closure,
                 op_NegClosure, op_NegClosureMarked):
            return formula.unop(k, func(self[0]))
        if k in (op_Xor, op_Implies, op_Equiv, op_U, op_R, op_W,
                 op_M, op_EConcat, op_EConcatMarked, op_UConcat):
            return formula.binop(k, func(self[0]), func(self[1]))
        if k in (op_Or, op_OrRat, op_And, op_AndRat, op_AndNLM,
                 op_Concat, op_Fusion):
            return formula.multop(k, [func(x) for x in self])
        if k in (op_Star, op_FStar):
            return formula.bunop(k, func(self[0]), self.min(), self.max())
        raise ValueError("unknown type of formula")
307

308

309
def automata(*sources, timeout=None, ignore_abort=True,
310
             trust_hoa=True, no_sid=False, debug=False):
311
312
    """Read automata from a list of sources.

313
314
315
316
317
318
    Parameters
    ----------
    *sources : list of str
        These sources can be either commands (end with `|`),
        textual represantations of automata (contain `\n`),
        or filenames (else).
319
    timeout : int, optional
320
321
        Number of seconds to wait for the result of a command.
        If None (the default), not limit is used.
322
323
324
325
    ignore_abort : bool, optional
        If True (the default), skip HOA atomata that ends with
        `--ABORT--`, and return the next automaton in the stream.
        If False, aborted automata are reported as syntax errors.
326
327
328
    trust_hoa : bool, optional
        If True (the default), supported HOA properies that
        cannot be easily verified are trusted.
329
330
331
332
    no_sid : bool, optional
        When an automaton is obtained from a subprocess, this
        subprocess is started from a shell with its own session
        group (the default) unless no_sid is set to True.
333
334
    debug : bool, optional
        Whether to run the parser in debug mode.
335
336
337

    Notes
    -----
338
339
340

    The automata can be written in the `HOA format`_, as `never
    claims`_, in `LBTT's format`_, or in `ltl2dstar's format`_.
341

342
343
344
345
346
347
    .. _HOA format: http://adl.github.io/hoaf/
    .. _never claims: http://spinroot.com/spin/Man/never.html
    .. _LBTT's format:
       http://www.tcs.hut.fi/Software/lbtt/doc/html/Format-for-automata.html
    .. _ltl2dstar's format:
       http://www.ltl2dstar.de/docs/ltl2dstar.html#output-format-dstar
348

349
    If an argument ends with a `|`, then this argument is interpreted as
350
    a shell command, and the output of that command (without the `|`)
351
352
353
354
355
356
    is parsed.

    If an argument contains a newline, then it is interpreted as
    actual contents to be parsed.

    Otherwise, the argument is assumed to be a filename.
357
358
359
360

    The result of this function is a generator on all the automata
    objects read from these sources.  The typical usage is::

361
        for aut in spot.automata(filename, command, ...):
362
363
            # do something with aut

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    When the source is a command, and no `timeout` is specified,
    parsing is done straight out of the pipe connecting the
    command.  So

        for aut in spot.automata('randaut -H -n 10 2 |'):
            process(aut)

    will call `process(aut)` on each automaton as soon as it is output by
    `randaut`, and without waiting for `randaut` to terminate.

    However if `timeout` is passed, then `automata()` will wait for
    the entire command to terminate before parsing its entire output.
    If one command takes more than `timeout` seconds,
    `subprocess.TimeoutExpired` is raised.

    If any command terminates with a non-zero error,
    `subprocess.CalledProcessError` is raised.
381
    """
382

383
384
385
    o = automaton_parser_options()
    o.debug = debug
    o.ignore_abort = ignore_abort
386
    o.trust_hoa = trust_hoa
387
    o.raise_errors = True
388
    for filename in sources:
389
        try:
390
            p = None
391
            proc = None
392
            if filename[-1] == '|':
393
394
395
                setsid_maybe = None
                if not no_sid:
                    setsid_maybe = os.setsid
396
397
398
399
                # universal_newlines for str output instead of bytes
                # when the pipe is read from Python (which happens
                # when timeout is set).
                proc = subprocess.Popen(filename[:-1], shell=True,
400
401
                                        preexec_fn=
                                        None if no_sid else os.setsid,
402
403
                                        universal_newlines=True,
                                        stdout=subprocess.PIPE)
404
405
                if timeout is None:
                    p = automaton_stream_parser(proc.stdout.fileno(),
406
                                                filename, o)
407
                else:
408
409
410
411
412
413
414
                    try:
                        out, err = proc.communicate(timeout=timeout)
                    except subprocess.TimeoutExpired:
                        # Using subprocess.check_output() with timeout
                        # would just kill the shell, not its children.
                        os.killpg(proc.pid, signal.SIGKILL)
                        raise
415
416
417
418
419
                    else:
                        ret = proc.wait()
                        if ret:
                            raise subprocess.CalledProcessError(ret,
                                                                filename[:-1])
420
421
                    finally:
                        proc = None
422
                    p = automaton_stream_parser(out, filename, o)
423
            elif '\n' in filename:
424
                p = automaton_stream_parser(filename, "<string>", o)
425
            else:
426
                p = automaton_stream_parser(filename, o)
427
428
            a = True
            while a:
429
                # This returns None when we reach the end of the file.
430
                a = p.parse(_bdd_dict).aut
431
432
433
                if a:
                    yield a
        finally:
434
435
            # Make sure we destroy the parser (p) and the subprocess
            # (prop) in the correct order...
436
            del p
437
            if proc is not None:
438
439
                if not a:
                    # We reached the end of the stream.  Wait for the
440
                    # process to finish, so that we get its exit code.
441
442
443
                    ret = proc.wait()
                else:
                    # if a != None, we probably got there through an
444
                    # exception, and the subprocess might still be
445
446
447
                    # running.  Check if an exit status is available
                    # just in case.
                    ret = proc.poll()
448
449
                del proc
                if ret:
450
                    raise subprocess.CalledProcessError(ret, filename[:-1])
451
452
453
454
455
456
    # deleting o explicitely now prevents Python 3.5 from
    # reporting the following error: "<built-in function
    # delete_automaton_parser_options> returned a result with
    # an error set".  It's not clear to me if the bug is in Python
    # or Swig.  At least it's related to the use of generators.
    del o
457
458
    return

459

460
def automaton(filename, **kwargs):
461
462
    """Read a single automaton from a file.

463
    See `spot.automata` for a list of supported formats."""
464
    try:
465
        return next(automata(filename, **kwargs))
466
467
    except StopIteration:
        raise RuntimeError("Failed to read automaton from {}".format(filename))
468

469

470
def _postproc_translate_options(obj, default_type, *args):
471
472
473
474
475
476
477
478
479
    type_ = None
    pref_ = None
    optm_ = None
    comp_ = 0
    unam_ = 0
    sbac_ = 0

    def type_set(val):
        nonlocal type_
480
        if type_ is not None and type_ != val:
481
482
            raise ValueError("type cannot be both {} and {}"
                             .format(type_, val))
483
484
        elif val == 'generic':
            type_ = postprocessor.Generic
485
486
487
488
        elif val == 'tgba':
            type_ = postprocessor.TGBA
        elif val == 'ba':
            type_ = postprocessor.BA
489
        else:
490
491
492
493
494
            assert(val == 'monitor')
            type_ = postprocessor.Monitor

    def pref_set(val):
        nonlocal pref_
495
        if pref_ is not None and pref_ != val:
496
497
498
499
500
501
502
503
504
505
506
507
            raise ValueError("preference cannot be both {} and {}"
                             .format(pref_, val))
        elif val == 'small':
            pref_ = postprocessor.Small
        elif val == 'deterministic':
            pref_ = postprocessor.Deterministic
        else:
            assert(val == 'any')
            pref_ = postprocessor.Any

    def optm_set(val):
        nonlocal optm_
508
        if optm_ is not None and optm_ != val:
509
510
            raise ValueError("optimization level cannot be both {} and {}"
                             .format(optm_, val))
511
        if val == 'high':
512
            optm_ = postprocessor.High
513
        elif val.startswith('med'):
514
515
            optm_ = postprocessor.Medium
        else:
516
            assert(val == 'low')
517
518
519
520
521
522
523
524
            optm_ = postprocessor.Low

    def misc_set(val):
        nonlocal comp_, unam_, sbac_
        if val == 'complete':
            comp_ = postprocessor.Complete
        elif val == 'sbacc' or val == 'state-based-acceptance':
            sbac_ = postprocessor.SBAcc
525
        else:
526
527
528
529
530
531
532
            assert(val == 'unambiguous')
            unam_ = postprocessor.Unambiguous

    options = {
        'tgba': type_set,
        'ba': type_set,
        'monitor': type_set,
533
        'generic': type_set,
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
        'small': pref_set,
        'deterministic': pref_set,
        'any': pref_set,
        'high': optm_set,
        'medium': optm_set,
        'low': optm_set,
        'complete': misc_set,
        'unambiguous': misc_set,
        'statebasedacceptance': misc_set,
        'sbacc': misc_set,
    }

    for arg in args:
        arg = arg.lower()
        fn = options.get(arg)
        if fn:
            fn(arg)
551
        else:
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
            # arg is not an know option, but maybe it is a prefix of
            # one of them
            compat = []
            f = None
            for key, fn in options.items():
                if key.startswith(arg):
                    compat.append(key)
                    f = fn
            lc = len(compat)
            if lc == 1:
                f(compat[0])
            elif lc < 1:
                raise ValueError("unknown option '{}'".format(arg))
            else:
                raise ValueError("ambiguous option '{}' is prefix of {}"
                                 .format(arg, str(compat)))

569
    if type_ is None:
570
        type_ = default_type
571
    if pref_ is None:
572
        pref_ = postprocessor.Small
573
    if optm_ is None:
574
575
        optm_ = postprocessor.High

576
577
578
    obj.set_type(type_)
    obj.set_pref(pref_ | comp_ | unam_ | sbac_)
    obj.set_level(optm_)
579

580

581
def translate(formula, *args, dict=_bdd_dict):
582
583
584
585
586
587
    """Translate a formula into an automaton.

    Keep in mind that 'Deterministic' expresses just a preference that
    may not be satisfied.

    The optional arguments should be strings among the following:
588
    - at most one in 'TGBA', 'BA', or 'Monitor', 'generic'
589
590
591
592
593
594
595
596
597
598
      (type of automaton to build)
    - at most one in 'Small', 'Deterministic', 'Any'
      (preferred characteristics of the produced automaton)
    - at most one in 'Low', 'Medium', 'High'
      (optimization level)
    - any combination of 'Complete', 'Unambiguous', and
      'StateBasedAcceptance' (or 'SBAcc' for short)

    The default corresponds to 'tgba', 'small' and 'high'.
    """
599
    a = translator(dict)
600
601
602
    _postproc_translate_options(a, postprocessor.TGBA, *args)
    if type(formula) == str:
        formula = parse_formula(formula)
603
    return a.run(formula)
604

605

606
formula.translate = translate
607

608

609
def postprocess(automaton, *args, formula=None):
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
    """Post process an automaton.

    This applies a number of simlification algorithms, depending on
    the options supplied. Keep in mind that 'Deterministic' expresses
    just a preference that may not be satisfied if the input is
    not already 'Deterministic'.

    The optional arguments should be strings among the following:
    - at most one in 'Generic', 'TGBA', 'BA', or 'Monitor'
      (type of automaton to build)
    - at most one in 'Small', 'Deterministic', 'Any'
      (preferred characteristics of the produced automaton)
    - at most one in 'Low', 'Medium', 'High'
      (optimization level)
    - any combination of 'Complete' and 'StateBasedAcceptance'
      (or 'SBAcc' for short)

    The default corresponds to 'generic', 'small' and 'high'.
628
629
630
631

    If a formula denoted by this automaton is known, pass it to as the
    optional `formula` argument; it can help some algorithms by
    providing an easy way to complement the automaton.
632
633
634
635
636
    """
    p = postprocessor()
    if type(automaton) == str:
        automaton = globals()['automaton'](automaton)
    _postproc_translate_options(p, postprocessor.Generic, *args)
637
    return p.run(automaton, formula)
638
639
640
641


twa.postprocess = postprocess

642
643
644
645
# Wrap C++-functions into lambdas so that they get converted into
# instance methods (i.e., self passed as first argument
# automatically), because only used-defined functions are converted as
# instance methods.
646
def _add_twa_graph(meth):
647
648
    setattr(twa_graph, meth, (lambda self, *args, **kwargs:
                              globals()[meth](self, *args, **kwargs)))
649

650
651
652
653
for meth in ('scc_filter', 'scc_filter_states',
             'is_deterministic', 'is_unambiguous'):
    _add_twa_graph(meth)

654
655
656
657
658
659
660
661
662
663
664
665
666
# Wrapper around a formula iterator to which we add some methods of formula
# (using _addfilter and _addmap), so that we can write things like
# formulas.simplify().is_X_free().
class formulaiterator:
    def __init__(self, formulas):
        self._formulas = formulas

    def __iter__(self):
        return self

    def __next__(self):
        return next(self._formulas)

667

668
669
670
671
672
673
674
# fun shoud be a predicate and should be a method of formula.
# _addfilter adds this predicate as a filter whith the same name in
# formulaiterator.
def _addfilter(fun):
    def filtf(self, *args, **kwargs):
        it = filter(lambda f: getattr(f, fun)(*args, **kwargs), self)
        return formulaiterator(it)
675

676
677
678
    def nfiltf(self, *args, **kwargs):
        it = filter(lambda f: not getattr(f, fun)(*args, **kwargs), self)
        return formulaiterator(it)
679

680
    if fun[:3] == 'is_':
681
        notfun = 'is_not_' + fun[3:]
682
    elif fun[:4] == 'has_':
683
        notfun = 'has_no_' + fun[4:]
684
685
686
687
688
    else:
        notfun = 'not_' + fun
    setattr(formulaiterator, fun, filtf)
    setattr(formulaiterator, notfun, nfiltf)

689
690
691
692

# fun should be a function taking a formula as its first parameter and
# returning a formula.  _addmap adds this function as a method of
# formula and formulaiterator.
693
694
695
def _addmap(fun):
    def mapf(self, *args, **kwargs):
        return formulaiterator(map(lambda f: getattr(f, fun)(*args, **kwargs),
696
697
                                   self))
    setattr(formula, fun,
698
699
            lambda self, *args, **kwargs:
            globals()[fun](self, *args, **kwargs))
700
701
    setattr(formulaiterator, fun, mapf)

702
703

def randltl(ap, n=-1, **kwargs):
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
    """Generate random formulas.

    Returns a random formula iterator.

    ap: the number of atomic propositions used to generate random formulas.

    n: number of formulas to generate, or unbounded if n < 0.

    **kwargs:
    seed: seed for the random number generator (0).
    output: can be 'ltl', 'psl', 'bool' or 'sere' ('ltl').
    allow_dups: allow duplicate formulas (False).
    tree_size: tree size of the formulas generated, before mandatory
    simplifications (15)
    boolean_priorities: set priorities for Boolean formulas.
    ltl_priorities: set priorities for LTL formulas.
    sere_priorities: set priorities for SERE formulas.
    dump_priorities: show current priorities, do not generate any formula.
    simplify:
      0           No rewriting
      1           basic rewritings and eventual/universal rules
      2           additional syntactic implication rules
      3 (default) better implications using containment
    """
    opts = option_map()
    output_map = {
730
731
732
733
        "ltl": OUTPUTLTL,
        "psl": OUTPUTPSL,
        "bool": OUTPUTBOOL,
        "sere": OUTPUTSERE
734
735
736
737
738
    }

    if isinstance(ap, list):
        aprops = atomic_prop_set()
        for elt in ap:
739
            aprops.insert(formula.ap(elt))
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
        ap = aprops
    ltl_priorities = kwargs.get("ltl_priorities", None)
    sere_priorities = kwargs.get("sere_priorities", None)
    boolean_priorities = kwargs.get("boolean_priorities", None)
    output = output_map[kwargs.get("output", "ltl")]
    opts.set("output", output)
    opts.set("seed", kwargs.get("seed", 0))
    tree_size = kwargs.get("tree_size", 15)
    if isinstance(tree_size, tuple):
        tree_size_min, tree_size_max = tree_size
    else:
        tree_size_min = tree_size_max = tree_size
    opts.set("tree_size_min", tree_size_min)
    opts.set("tree_size_max", tree_size_max)
    opts.set("unique", not kwargs.get("allow_dups", False))
    opts.set("wf", kwargs.get("weak_fairness", False))
    simpl_level = kwargs.get("simplify", 0)
    if simpl_level > 3 or simpl_level < 0:
        sys.stderr.write('invalid simplification level: ' + simpl_level)
        return
    opts.set("simplification_level", simpl_level)

    rg = randltlgenerator(ap, opts, ltl_priorities, sere_priorities,
763
                          boolean_priorities)
764
765
766
767
768

    dump_priorities = kwargs.get("dump_priorities", False)
    if dump_priorities:
        dumpstream = ostringstream()
        if output == OUTPUTLTL:
769
770
            print('Use argument ltl_priorities=STRING to set the following '
                  'LTL priorities:\n')
771
772
773
            rg.dump_ltl_priorities(dumpstream)
            print(dumpstream.str())
        elif output == OUTPUTBOOL:
774
775
            print('Use argument boolean_priorities=STRING to set the '
                  'following Boolean formula priorities:\n')
776
777
778
779
            rg.dump_bool_priorities(dumpstream)
            print(dumpstream.str())
        elif output == OUTPUTPSL or output == OUTPUTSERE:
            if output != OUTPUTSERE:
780
781
                print('Use argument ltl_priorities=STRING to set the '
                      'following LTL priorities:\n')
782
783
                rg.dump_psl_priorities(dumpstream)
                print(dumpstream.str())
784
785
            print('Use argument sere_priorities=STRING to set the '
                  'following SERE priorities:\n')
786
787
            rg.dump_sere_priorities(dumpstream)
            print(dumpstream.str())
788
789
            print('Use argument boolean_priorities=STRING to set the '
                  'following Boolean formula priorities:\n')
790
791
792
793
794
795
            rg.dump_sere_bool_priorities(dumpstream)
            print(dumpstream.str())
        else:
            sys.stderr.write("internal error: unknown type of output")
        return

796
797
798
799
800
    class _randltliterator:
        def __init__(self, rg, n):
            self.rg = rg
            self.i = 0
            self.n = n
801

802
803
        def __iter__(self):
            return self
804

805
806
807
808
        def __next__(self):
            if self.i == self.n:
                raise StopIteration
            f = self.rg.next()
809
            if f is None:
810
811
812
813
814
815
816
817
                sys.stderr.write("Warning: could not generate a new "
                                 "unique formula after {} trials.\n"
                                 .format(MAX_TRIALS))
                raise StopIteration
            self.i += 1
            return f

    return formulaiterator(_randltliterator(rg, n))
818

819

820
821
822
def simplify(f, **kwargs):
    level = kwargs.get('level', None)
    if level is not None:
823
        return tl_simplifier(tl_simplifier_options(level)).simplify(f)
824
825
826
827

    basics = kwargs.get('basics', True)
    synt_impl = kwargs.get('synt_impl', True)
    event_univ = kwargs.get('event_univ', True)
828
829
    cont_checks = kwargs.get('containment_checks', False)
    cont_checks_stronger = kwargs.get('containment_checks_stronger', False)
830
831
832
833
834
    nenoform_stop_on_boolean = kwargs.get('nenoform_stop_on_boolean', False)
    reduce_size_strictly = kwargs.get('reduce_size_strictly', False)
    boolean_to_isop = kwargs.get('boolean_to_isop', False)
    favor_event_univ = kwargs.get('favor_event_univ', False)

835
    simp_opts = tl_simplifier_options(basics,
836
837
                                       synt_impl,
                                       event_univ,
838
839
                                       cont_checks,
                                       cont_checks_stronger,
840
841
842
843
                                       nenoform_stop_on_boolean,
                                       reduce_size_strictly,
                                       boolean_to_isop,
                                       favor_event_univ)
844
    return tl_simplifier(simp_opts).simplify(f)
845

846

847
for fun in dir(formula):
848
849
    if (callable(getattr(formula, fun)) and (fun[:3] == 'is_' or
                                             fun[:4] == 'has_')):
850
851
        _addfilter(fun)

852
853
for fun in ['remove_x', 'relabel', 'relabel_bse',
            'simplify', 'unabbreviate']:
854
    _addmap(fun)
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878



# Better interface to the corresponding C++ function.
def sat_minimize(aut, acc=None, colored=False,
                 state_based=False, states=0,
                 max_states=0, dichotomy=False):
    args=''
    if acc is not None:
        if type(acc) is not str:
            raise ValueError("argument 'acc' should be a string")
        args += ',acc="' + acc + '"'
    if colored:
        args += ',colored'
    if states:
        if type(states) is not int or states < 0:
            raise ValueError("argument 'states' should be a positive integer")
        args += ',states=' + str(states)
    if max_states:
        if type(max_states) is not int or max_states < 0:
            raise ValueError("argument 'states' should be a positive integer")
        args += ',max-states=' + str(max_states)
    if dichotomy:
        args += ',dichotomy';
879
    from spot.impl import sat_minimize as sm
880
    return sm(aut, args, state_based)
881
882
883
884

def parse_word(word, dic=_bdd_dict):
    from spot.impl import parse_word as pw
    return pw(word, dic)
885
886
887
888

def language_containment_checker(dic=_bdd_dict):
    from spot.impl import language_containment_checker as c
    return c(dic)