__init__.py 40.7 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2014-2018  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
import tempfile
37
from contextlib import suppress as _supress
38

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

42

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

46
    This is manly useful in Jupyter/IPython.
47

48 49
    Note that this function needs to be called before any automaton is
    displayed.  Afterwards it will have no effect (you should restart
50 51 52 53 54 55 56 57 58 59 60 61 62 63
    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')
64 65
    show_default : str
        default options for show()
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
66 67
    max_states : int
        maximum number of states in GraphViz output (default: 50)
68
    """
Etienne Renault's avatar
Etienne Renault committed
69
    import os
70

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

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

83

84 85 86 87
# 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.
88
if 'op_ff' not in globals():
89 90 91 92 93 94
    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'):
95
        globals()['op_' + i] = globals()[i]
96 97 98
        del globals()[i]


99 100
# 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
101

102

103 104 105 106 107
@_extend(twa, ta)
class twa:
    def _repr_svg_(self, opt=None):
        """Output the automaton as SVG"""
        ostr = ostringstream()
108 109 110
        if opt is None:
            global _show_default
            opt = _show_default
111 112 113 114 115
        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"""
116 117 118
        if opt is None:
            global _show_default
            opt = _show_default
119 120 121 122 123 124
        # 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))

125
    def highlight_states(self, states, color):
126 127 128 129 130 131 132 133
        """Highlight a list of states.  This can be a list of
        state numbers, or a list of Booleans."""
        for idx, val in enumerate(states):
            if type(val) is bool:
                if val:
                    self.highlight_state(idx, color)
            else:
                self.highlight_state(val, color)
134 135 136
        return self

    def highlight_edges(self, edges, color):
137 138 139 140 141 142 143 144
        """Highlight a list of edges.  This can be a list of
        edge numbers, or a list of Booleans."""
        for idx, val in enumerate(edges):
            if type(val) is bool:
                if val:
                    self.highlight_edge(idx, color)
            else:
                self.highlight_edge(val, color)
145
        return self
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

@_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()
167
        raise ValueError("unknown string format: " + format)
168

169 170 171 172 173 174 175 176 177 178 179 180 181
    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."""
182 183 184 185
        if type(str) == formula:
            self.this = str
        else:
            self.this = parse_formula(str)
186 187 188 189 190 191 192

    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
193
        return SVG(_str_to_svg(self.to_str('d')))
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

    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)
210 211 212 213
        elif format == 'dot' or format == 'd':
            ostr = ostringstream()
            print_dot_psl(ostr, self)
            return ostr.str().encode('utf-8')
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        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.
249 250
        - '[...]': rewrite away all the operators specified in brackets,
               using spot.unabbreviate().
251 252 253 254 255 256 257 258 259 260

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

        """

        syntax = 'f'
        parent = False
        escape = None

261 262
        form = self

263 264 265 266 267 268 269 270 271 272
        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
273 274 275 276 277 278
            elif c == '[':
                pos = spec.find(']')
                if pos < 0:
                    raise ValueError("unclosed bracket: [" + spec)
                form = form.unabbreviate(spec[0:pos])
                spec = spec[pos+1:]
279 280 281
            else:
                raise ValueError("unknown format specification: " + c + spec)

282
        s = form.to_str(syntax, parent)
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

        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)

301 302
    def traverse(self, func, *args):
        if func(self, *args):
303 304
            return
        for f in self:
305
            f.traverse(func, *args)
306

307
    def map(self, func, *args):
308 309 310 311 312
        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):
313
            return formula.unop(k, func(self[0], *args))
314 315
        if k in (op_Xor, op_Implies, op_Equiv, op_U, op_R, op_W,
                 op_M, op_EConcat, op_EConcatMarked, op_UConcat):
316
            return formula.binop(k, func(self[0], *args), func(self[1], *args))
317 318
        if k in (op_Or, op_OrRat, op_And, op_AndRat, op_AndNLM,
                 op_Concat, op_Fusion):
319
            return formula.multop(k, [func(x, *args) for x in self])
320
        if k in (op_Star, op_FStar):
321 322
            return formula.bunop(k, func(self[0], *args),
                                 self.min(), self.max())
323
        raise ValueError("unknown type of formula")
324

325

326
def automata(*sources, timeout=None, ignore_abort=True,
327
             trust_hoa=True, no_sid=False, debug=False):
328 329
    """Read automata from a list of sources.

330 331 332 333
    Parameters
    ----------
    *sources : list of str
        These sources can be either commands (end with `|`),
Clément Gillard's avatar
Clément Gillard committed
334
        textual representations of automata (contain `\n`),
335
        or filenames (else).
336
    timeout : int, optional
337 338
        Number of seconds to wait for the result of a command.
        If None (the default), not limit is used.
339 340 341 342
    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.
343 344 345
    trust_hoa : bool, optional
        If True (the default), supported HOA properies that
        cannot be easily verified are trusted.
346 347 348 349
    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.
350 351
    debug : bool, optional
        Whether to run the parser in debug mode.
352 353 354

    Notes
    -----
355 356 357

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

359 360 361 362 363 364
    .. _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
365

366
    If an argument ends with a `|`, then this argument is interpreted as
367
    a shell command, and the output of that command (without the `|`)
368 369 370 371 372 373
    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.
374 375 376 377

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

378
        for aut in spot.automata(filename, command, ...):
379 380
            # do something with aut

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    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.
398
    """
399

400 401 402
    o = automaton_parser_options()
    o.debug = debug
    o.ignore_abort = ignore_abort
403
    o.trust_hoa = trust_hoa
404
    o.raise_errors = True
405
    for filename in sources:
406
        try:
407
            p = None
408
            proc = None
409
            if filename[-1] == '|':
410 411 412
                setsid_maybe = None
                if not no_sid:
                    setsid_maybe = os.setsid
413 414 415 416
                # 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,
417 418
                                        preexec_fn=
                                        None if no_sid else os.setsid,
419 420
                                        universal_newlines=True,
                                        stdout=subprocess.PIPE)
421 422
                if timeout is None:
                    p = automaton_stream_parser(proc.stdout.fileno(),
423
                                                filename, o)
424
                else:
425 426 427 428 429 430 431
                    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
432 433 434 435 436
                    else:
                        ret = proc.wait()
                        if ret:
                            raise subprocess.CalledProcessError(ret,
                                                                filename[:-1])
437 438
                    finally:
                        proc = None
439
                    p = automaton_stream_parser(out, filename, o)
440
            elif '\n' in filename:
441
                p = automaton_stream_parser(filename, "<string>", o)
442
            else:
443
                p = automaton_stream_parser(filename, o)
444
            a = True
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
            # Using proc as a context manager ensures that proc.stdout will be
            # closed on exit, and the process will be properly waited for.
            # This is important when running tools that produce an infinite
            # stream of automata and that must be killed once the generator
            # returned by spot.automata() is destroyed.  Otherwise, _supress()
            # is just a dummy context manager that does nothing (Python 3.7
            # introduces nullcontext() for this purpose, but at the time of
            # writing we support Python 3.4).
            mgr = proc if proc else _supress()
            with mgr:
                while a:
                    # This returns None when we reach the end of the file.
                    a = p.parse(_bdd_dict).aut
                    if a:
                        yield a
460
        finally:
461
            # Make sure we destroy the parser (p) and the subprocess
462
            # (prop) in the correct order.
463
            del p
464
            if proc is not None:
465
                ret = proc.returncode
466
                del proc
467 468 469
                # Do not complain about the exit code if we are already raising
                # an exception.
                if ret and sys.exc_info()[0] is None:
470
                    raise subprocess.CalledProcessError(ret, filename[:-1])
471
    # deleting o explicitly now prevents Python 3.5 from
472 473 474 475 476
    # 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
477 478
    return

479

480
def automaton(filename, **kwargs):
481 482
    """Read a single automaton from a file.

483
    See `spot.automata` for a list of supported formats."""
484
    try:
485
        return next(automata(filename, **kwargs))
486 487
    except StopIteration:
        raise RuntimeError("Failed to read automaton from {}".format(filename))
488

489

490
def _postproc_translate_options(obj, default_type, *args):
491
    type_name_ = None
492
    type_ = None
493
    pref_name_ = None
494
    pref_ = None
495
    optm_name_ = None
496 497 498 499
    optm_ = None
    comp_ = 0
    unam_ = 0
    sbac_ = 0
500
    colo_ = 0
501 502

    def type_set(val):
503 504
        nonlocal type_, type_name_
        if type_ is not None and type_name_ != val:
505
            raise ValueError("type cannot be both {} and {}"
506
                             .format(type_name_, val))
507 508
        elif val == 'generic':
            type_ = postprocessor.Generic
509 510 511 512
        elif val == 'tgba':
            type_ = postprocessor.TGBA
        elif val == 'ba':
            type_ = postprocessor.BA
513 514 515 516 517
        elif val == 'cobuchi' or val == 'nca':
            type_ = postprocessor.CoBuchi
        elif val == 'dca':
            type_ = postprocessor.CoBuchi
            pref_ = postprocessor.Deterministic
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        elif val == 'parity min odd':
            type_ = postprocessor.ParityMinOdd
        elif val == 'parity min even':
            type_ = postprocessor.ParityMinEven
        elif val == 'parity max odd':
            type_ = postprocessor.ParityMaxOdd
        elif val == 'parity max even':
            type_ = postprocessor.ParityMaxEven
        elif val == 'parity min':
            type_ = postprocessor.ParityMin
        elif val == 'parity max':
            type_ = postprocessor.ParityMax
        elif val == 'parity odd':
            type_ = postprocessor.ParityOdd
        elif val == 'parity even':
            type_ = postprocessor.ParityEven
        elif val == 'parity':
            type_ = postprocessor.Parity
536
        else:
537 538
            assert(val == 'monitor')
            type_ = postprocessor.Monitor
539
        type_name_ = val
540 541

    def pref_set(val):
542 543
        nonlocal pref_, pref_name_
        if pref_ is not None and pref_name_ != val:
544
            raise ValueError("preference cannot be both {} and {}"
545
                             .format(pref_name, val))
546 547 548 549 550 551 552
        elif val == 'small':
            pref_ = postprocessor.Small
        elif val == 'deterministic':
            pref_ = postprocessor.Deterministic
        else:
            assert(val == 'any')
            pref_ = postprocessor.Any
553
        pref_name_ = val
554 555

    def optm_set(val):
556 557
        nonlocal optm_, optm_name_
        if optm_ is not None and optm_name_ != val:
558
            raise ValueError("optimization level cannot be both {} and {}"
559
                             .format(optm_name_, val))
560
        if val == 'high':
561
            optm_ = postprocessor.High
562
        elif val.startswith('med'):
563 564
            optm_ = postprocessor.Medium
        else:
565
            assert(val == 'low')
566
            optm_ = postprocessor.Low
567
        optm_name_ = val
568 569

    def misc_set(val):
570 571 572 573
        nonlocal comp_, unam_, sbac_, colo_
        if val == 'colored':
            colo_ = postprocessor.Colored
        elif val == 'complete':
574 575 576
            comp_ = postprocessor.Complete
        elif val == 'sbacc' or val == 'state-based-acceptance':
            sbac_ = postprocessor.SBAcc
577
        else:
578 579 580 581
            assert(val == 'unambiguous')
            unam_ = postprocessor.Unambiguous

    options = {
582
        'any': pref_set,
583
        'ba': type_set,
584
        'cobuchi': type_set,
585
        'colored': misc_set,
586 587
        'complete': misc_set,
        'dca': type_set,
588
        'deterministic': pref_set,
589
        'generic': type_set,
590 591
        'high': optm_set,
        'low': optm_set,
592 593
        'medium': optm_set,
        'monitor': type_set,
594
        'nca': type_set,
595 596 597 598 599 600 601 602 603
        'parity even': type_set,
        'parity max even': type_set,
        'parity max odd': type_set,
        'parity max': type_set,
        'parity min even': type_set,
        'parity min odd': type_set,
        'parity min': type_set,
        'parity odd': type_set,
        'parity': type_set,
604
        'sbacc': misc_set,
605 606 607 608
        'small': pref_set,
        'statebasedacceptance': misc_set,
        'tgba': type_set,
        'unambiguous': misc_set,
609 610 611 612 613 614 615
    }

    for arg in args:
        arg = arg.lower()
        fn = options.get(arg)
        if fn:
            fn(arg)
616
        else:
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
            # 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)))

634
    if type_ is None:
635
        type_ = default_type
636
    if pref_ is None:
637
        pref_ = postprocessor.Small
638
    if optm_ is None:
639 640
        optm_ = postprocessor.High

641
    obj.set_type(type_)
642
    obj.set_pref(pref_ | comp_ | unam_ | sbac_ | colo_)
643
    obj.set_level(optm_)
644

645

646
def translate(formula, *args, dict=_bdd_dict):
647 648 649 650 651 652
    """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:
653 654 655
    - at most one in 'TGBA', 'BA', or 'Monitor', 'generic',
      'parity', 'parity min odd', 'parity min even',
      'parity max odd', 'parity max even' (type of automaton to
656
      build), 'coBuchi'
657 658 659 660
    - at most one in 'Small', 'Deterministic', 'Any'
      (preferred characteristics of the produced automaton)
    - at most one in 'Low', 'Medium', 'High'
      (optimization level)
661 662 663
    - any combination of 'Complete', 'Unambiguous',
      'StateBasedAcceptance' (or 'SBAcc' for short), and
      'Colored' (only for parity acceptance)
664 665 666

    The default corresponds to 'tgba', 'small' and 'high'.
    """
667
    a = translator(dict)
668 669 670
    _postproc_translate_options(a, postprocessor.TGBA, *args)
    if type(formula) == str:
        formula = parse_formula(formula)
671
    return a.run(formula)
672

673

674
formula.translate = translate
675

676

677
def postprocess(automaton, *args, formula=None):
678 679 680 681 682 683 684 685
    """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:
686 687 688
    - at most one in 'Generic', 'TGBA', 'BA', or 'Monitor',
      'parity', 'parity min odd', 'parity min even',
      'parity max odd', 'parity max even' (type of automaton to
689
      build), 'coBuchi'
690 691 692 693
    - at most one in 'Small', 'Deterministic', 'Any'
      (preferred characteristics of the produced automaton)
    - at most one in 'Low', 'Medium', 'High'
      (optimization level)
694 695 696
    - any combination of 'Complete', 'StateBasedAcceptance'
      (or 'SBAcc' for short), and 'Colored (only for parity
      acceptance)
697 698

    The default corresponds to 'generic', 'small' and 'high'.
699 700 701 702

    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.
703 704 705 706 707
    """
    p = postprocessor()
    if type(automaton) == str:
        automaton = globals()['automaton'](automaton)
    _postproc_translate_options(p, postprocessor.Generic, *args)
708
    return p.run(automaton, formula)
709 710 711 712


twa.postprocess = postprocess

713 714 715 716
# 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.
717
def _add_twa_graph(meth):
718 719
    setattr(twa_graph, meth, (lambda self, *args, **kwargs:
                              globals()[meth](self, *args, **kwargs)))
720

721 722 723 724
for meth in ('scc_filter', 'scc_filter_states',
             'is_deterministic', 'is_unambiguous'):
    _add_twa_graph(meth)

725 726 727 728 729 730 731 732 733 734 735 736 737
# 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)

738

739 740 741 742 743 744 745
# 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)
746

747 748 749
    def nfiltf(self, *args, **kwargs):
        it = filter(lambda f: not getattr(f, fun)(*args, **kwargs), self)
        return formulaiterator(it)
750

751
    if fun[:3] == 'is_':
752
        notfun = 'is_not_' + fun[3:]
753
    elif fun[:4] == 'has_':
754
        notfun = 'has_no_' + fun[4:]
755 756 757 758 759
    else:
        notfun = 'not_' + fun
    setattr(formulaiterator, fun, filtf)
    setattr(formulaiterator, notfun, nfiltf)

760 761 762 763

# 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.
764 765 766
def _addmap(fun):
    def mapf(self, *args, **kwargs):
        return formulaiterator(map(lambda f: getattr(f, fun)(*args, **kwargs),
767 768
                                   self))
    setattr(formula, fun,
769 770
            lambda self, *args, **kwargs:
            globals()[fun](self, *args, **kwargs))
771 772
    setattr(formulaiterator, fun, mapf)

773 774

def randltl(ap, n=-1, **kwargs):
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
    """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 = {
801 802 803 804
        "ltl": OUTPUTLTL,
        "psl": OUTPUTPSL,
        "bool": OUTPUTBOOL,
        "sere": OUTPUTSERE
805 806 807 808 809
    }

    if isinstance(ap, list):
        aprops = atomic_prop_set()
        for elt in ap:
810
            aprops.insert(formula.ap(elt))
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
        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,
834
                          boolean_priorities)
835 836 837 838 839

    dump_priorities = kwargs.get("dump_priorities", False)
    if dump_priorities:
        dumpstream = ostringstream()
        if output == OUTPUTLTL:
840 841
            print('Use argument ltl_priorities=STRING to set the following '
                  'LTL priorities:\n')
842 843 844
            rg.dump_ltl_priorities(dumpstream)
            print(dumpstream.str())
        elif output == OUTPUTBOOL:
845 846
            print('Use argument boolean_priorities=STRING to set the '
                  'following Boolean formula priorities:\n')
847 848 849 850
            rg.dump_bool_priorities(dumpstream)
            print(dumpstream.str())
        elif output == OUTPUTPSL or output == OUTPUTSERE:
            if output != OUTPUTSERE:
851 852
                print('Use argument ltl_priorities=STRING to set the '
                      'following LTL priorities:\n')
853 854
                rg.dump_psl_priorities(dumpstream)
                print(dumpstream.str())
855 856
            print('Use argument sere_priorities=STRING to set the '
                  'following SERE priorities:\n')
857 858
            rg.dump_sere_priorities(dumpstream)
            print(dumpstream.str())
859 860
            print('Use argument boolean_priorities=STRING to set the '
                  'following Boolean formula priorities:\n')
861 862 863 864 865 866
            rg.dump_sere_bool_priorities(dumpstream)
            print(dumpstream.str())
        else:
            sys.stderr.write("internal error: unknown type of output")
        return

867 868 869 870 871
    class _randltliterator:
        def __init__(self, rg, n):
            self.rg = rg
            self.i = 0
            self.n = n
872

873 874
        def __iter__(self):
            return self
875

876 877 878 879
        def __next__(self):
            if self.i == self.n:
                raise StopIteration
            f = self.rg.next()
880
            if f is None:
881 882 883 884 885 886 887 888
                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))
889

890

891 892 893
def simplify(f, **kwargs):
    level = kwargs.get('level', None)
    if level is not None:
894
        return tl_simplifier(tl_simplifier_options(level)).simplify(f)
895 896 897 898

    basics = kwargs.get('basics', True)
    synt_impl = kwargs.get('synt_impl', True)
    event_univ = kwargs.get('event_univ', True)
899 900
    cont_checks = kwargs.get('containment_checks', False)
    cont_checks_stronger = kwargs.get('containment_checks_stronger', False)
901 902 903 904 905
    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)

906
    simp_opts = tl_simplifier_options(basics,
907 908
                                       synt_impl,
                                       event_univ,
909 910
                                       cont_checks,
                                       cont_checks_stronger,
911 912 913 914
                                       nenoform_stop_on_boolean,
                                       reduce_size_strictly,
                                       boolean_to_isop,
                                       favor_event_univ)
915
    return tl_simplifier(simp_opts).simplify(f)
916

917

918
for fun in dir(formula):
919 920
    if (callable(getattr(formula, fun)) and (fun[:3] == 'is_' or
                                             fun[:4] == 'has_')):
921 922
        _addfilter(fun)

923
for fun in ['remove_x', 'relabel', 'relabel_bse',
924 925
            'simplify', 'unabbreviate', 'negative_normal_form',
            'mp_class', 'nesting_depth']:
926
    _addmap(fun)
927 928 929 930 931 932



# Better interface to the corresponding C++ function.
def sat_minimize(aut, acc=None, colored=False,
                 state_based=False, states=0,
933
                 max_states=0, sat_naive=False, sat_langmap=False,
934 935
                 sat_incr=0, sat_incr_steps=0,
                 display_log=False, return_log=False):
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
    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)
951 952 953 954 955 956 957
    if sat_naive:
        args += ',sat-naive'
    if sat_langmap:
        args += ',sat-langmap'
    if sat_incr:
        args += ',sat-incr=' + str(sat_incr)
        args += ',sat-incr-steps=' + str(sat_incr_steps)
958
    from spot.impl import sat_minimize as sm
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976

    if display_log or return_log:
        import pandas as pd
        with tempfile.NamedTemporaryFile(dir='.', suffix='.satlog') as t:
            args += ',log="{}"'.format(t.name)
            aut = sm(aut, args, state_based)
            dfrm = pd.read_csv(t.name, dtype=object)
            if display_log:
                # old versions of ipython do not import display by default
                from IPython.display import display
                del dfrm['automaton']
                display(dfrm)
            if return_log:
                return aut, dfrm
            else:
                return aut
    else:
        return sm(aut, args, state_based)
977

978

979 980 981
def parse_word(word, dic=_bdd_dict):
    from spot.impl import parse_word as pw
    return pw(word, dic)
982

983 984 985
def bdd_to_formula(b, dic=_bdd_dict):
    from spot.impl import bdd_to_formula as bf
    return bf(b, dic)
986

987 988 989
def language_containment_checker(dic=_bdd_dict):
    from spot.impl import language_containment_checker as c
    return c(dic)
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053


def mp_hierarchy_svg(cl=None):
    """
    Return an some string containing an SVG picture of the Manna &
    Pnueli hierarchy, highlighting class `cl` if given.

    If not None, `cl` should be one of 'TPROGSB'.  For convenience,
    if `cl` is an instance of `spot.formula`, it is replaced by
    `mp_class(cl)`.

    """
    if type(cl)==formula:
        cl = mp_class(cl)
    ch = None
    coords = {
        'T': '110,35',
        'R': '40,80',
        'P': '175,80',
        'O': '110,140',
        'S': '40,160',
        'G': '175,160',
        'B': '110,198',
    }
    if cl in coords:
        highlight='''<g transform="translate({})">
    <line x1="-10" y1="-10" x2="10" y2="10" stroke="red" stroke-width="5" />
    <line x1="-10" y1="10" x2="10" y2="-10" stroke="red" stroke-width="5" />
    </g>'''.format(coords[cl])
    else:
        highlight=''
    return '''
<svg height="210" width="220" xmlns="http://www.w3.org/2000/svg" version="1.1">
<polygon points="20,0 200,120 200,210 20,210" fill="cyan" opacity=".2" />
<polygon points="20,120 155,210 20,210" fill="cyan" opacity=".2" />
<polygon points="200,0 20,120 20,210 200,210" fill="magenta" opacity=".15" />
<polygon points="200,120 65,210 200,210" fill="magenta" opacity=".15" />
''' + highlight + '''
<g text-anchor="middle" font-size="14">
<text x="110" y="20">Reactivity</text>
<text x="60" y="65">Recurrence</text>
<text x="160" y="65">Persistence</text>
<text x="110" y="125">Obligation</text>
<text x="60" y="185">Safety</text>
<text x="160" y="185">Guarantee</text>
</g>
<g font-size="14">
<text text-anchor="begin" transform="rotate(-90,18,210)" x="18" y="210" fill="gray">Monitor</text>
<text text-anchor="end" transform="rotate(-90,18,0)" x="18" y="0" fill="gray">Deterministic Büchi</text>
<text text-anchor="begin" transform="rotate(-90,214,210)" x="214" y="210" fill="gray">Terminal Büchi</text>
<text text-anchor="end" transform="rotate(-90,214,0)" x="214" y="0" fill="gray">Weak Büchi</text>
</g>
</svg>'''


def show_mp_hierarchy(cl):
    """
    Return a picture of the Manna & Pnueli hierarchy as an SVG object
    in the IPython/Jupyter.
    """
    from IPython.display import SVG
    return SVG(mp_hierarchy_svg(cl))

formula.show_mp_hierarchy = show_mp_hierarchy
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

@_extend(twa_word)
class twa_word:
    def as_svg(self):
        """
        Build an SVG picture representing the word as a collection of
        signals for each atomic proposition.
        """
        # Get the list of atomic proposition used
        sup = buddy.bddtrue
        for cond in list(self.prefix) + list(self.cycle):
            sup = sup & buddy.bdd_support(cond)
        ap = []
        while sup != buddy.bddtrue:
            a = buddy.bdd_var(sup)
            ap.append(a)
            sup = buddy.bdd_high(sup)

        # Prepare canvas
        psize = len(self.prefix)
        csize = len(self.cycle)
        d = {
            'endprefix': 50 * psize,
            'endcycle': 50 * (psize + csize),
            'w': 50 * (psize + csize * 2),
            'height': 50 * len(ap),
            'height2': 50 * len(ap) + 10,
            'h3': 50 * len(ap) + 12,
            'bgcolor': '#f4f4f4',
            'bgl': 'stroke="white" stroke-width="4"',
            'bgt': 'stroke="white" stroke-width="1"',
            'txt': 'text-anchor="start" font-size="20"',
            'red': 'stroke="#ff0000" stroke-width="2"',
            'sml': 'text-anchor="start" font-size="10"'
            }
        txt = '''
<svg height="{h3}" width="{w}" xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="0" y="0" width="{w}" height="{height}" fill="{bgcolor}"/>
<line x1="{endprefix}" y1="0" x2="{endprefix}" y2="{height}"
      stroke="white" stroke-width="4"/>
<line x1="{endcycle}" y1="0" x2="{endcycle}" y2="{height}"
      stroke="white" stroke-width="4"/>
'''.format(**d)

        # Iterate over all used atomic propositions, and fill each line
        l = list(self.prefix) + list(self.cycle) + list(self.cycle)
        bd = self.get_dict()
        for ypos, a in enumerate(ap):
            pa = buddy.bdd_ithvar(a)
            na = buddy.bdd_nithvar(a)
            name = bdd_format_formula(bd, pa)
            # Whether the last state was down (-1), up (1), or unknown (0)
            last = 0
            txt += ('<line x1="0" y1="{y}" x2="{w}" y2="{y}" {bgl}/>'
                    .format(y=ypos*50, **d))
            txt += ('<text x="{x}" y="{y}" {txt}>{name}</text>'
                    .format(x=3, y=ypos*50+30, name=name, **d))
            for xpos, step in enumerate(l):
                if buddy.bdd_implies(step, pa):
                    cur = 1
                elif buddy.bdd_implies(step, na):
                    cur = -1
                else:
                    cur = 0
                txt += ('<line x1="{x}" y1="{y1}" x2="{x}" y2="{y2}" {bgt}/>'
                        .format(x=(xpos+1)*50, y1=ypos*50, y2=ypos*50+50, **d))
                if cur != 0:
                    if last == -cur:
                        txt += \
                        ('<line x1="{x}" y1="{y1}" x2="{x}" y2="{y2}" {red}/>'
                             .format(x=xpos*50, y1=ypos*50+5,
                                     y2=ypos*50+45, **d))
                    txt += \
                    ('<line x1="{x1}" y1="{y}" x2="{x2}" y2="{y}" {red}/>'
                         .format(x1=xpos*50, x2=(xpos+1)*50,
                                 y=ypos*50+25-20*cur, **d))
                last = cur
        if psize > 0:
            txt += '<text x="0" y="{height2}" {sml}>prefix</text>'.format(**d)
        txt += '''<text x="{endprefix}" y="{height2}" {sml}>cycle</text>
<text x="{endcycle}" y="{height2}" {sml}>cycle</text>'''.format(**d)
        return txt + '</svg>'

    def show(self):
        """
        Display the word as an SVG picture of signals.
        """
        from IPython.display import SVG
        return SVG(self.as_svg())