mocha-model-checking 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. mocha/__init__.py +199 -0
  2. mocha/algorithms/__init__.py +159 -0
  3. mocha/algorithms/automata.py +205 -0
  4. mocha/algorithms/invariance.py +166 -0
  5. mocha/algorithms/ltl2gnba/__init__.py +75 -0
  6. mocha/algorithms/ltl2gnba/acceptance.py +199 -0
  7. mocha/algorithms/ltl2gnba/elementary_set_enumeration.py +360 -0
  8. mocha/algorithms/ltl2gnba/elementary_set_validation.py +312 -0
  9. mocha/algorithms/ltl2gnba/initial_states.py +116 -0
  10. mocha/algorithms/ltl2gnba/pipeline.py +137 -0
  11. mocha/algorithms/ltl2gnba/transitions.py +327 -0
  12. mocha/algorithms/ltl_model_checking.py +313 -0
  13. mocha/algorithms/ltl_satisfiability_validity.py +308 -0
  14. mocha/algorithms/ltl_transformations.py +291 -0
  15. mocha/algorithms/persistence.py +259 -0
  16. mocha/algorithms/reachability.py +143 -0
  17. mocha/algorithms/trace.py +22 -0
  18. mocha/io/__init__.py +20 -0
  19. mocha/io/ltl.py +195 -0
  20. mocha/io/schemas/__init__.py +1 -0
  21. mocha/io/schemas/transition-system.schema.json +95 -0
  22. mocha/io/transition_system.py +136 -0
  23. mocha/logic/__init__.py +5 -0
  24. mocha/logic/_syntax.py +8 -0
  25. mocha/logic/ltl.py +179 -0
  26. mocha/models/__init__.py +37 -0
  27. mocha/models/automaton.py +604 -0
  28. mocha/models/transition_system.py +535 -0
  29. mocha/py.typed +0 -0
  30. mocha/visualisation/__init__.py +55 -0
  31. mocha/visualisation/automaton.py +170 -0
  32. mocha/visualisation/invariance.py +84 -0
  33. mocha/visualisation/overlay.py +24 -0
  34. mocha/visualisation/persistence.py +48 -0
  35. mocha/visualisation/reachability.py +35 -0
  36. mocha/visualisation/transition_system.py +252 -0
  37. mocha_model_checking-0.1.0.dist-info/METADATA +587 -0
  38. mocha_model_checking-0.1.0.dist-info/RECORD +41 -0
  39. mocha_model_checking-0.1.0.dist-info/WHEEL +5 -0
  40. mocha_model_checking-0.1.0.dist-info/licenses/LICENCE +340 -0
  41. mocha_model_checking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,22 @@
1
+ """Generic support for recording algorithm executions."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Generic, TypeVar
5
+
6
+ Result = TypeVar("Result")
7
+ Step = TypeVar("Step")
8
+
9
+ __all__ = ["AlgorithmTrace"]
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AlgorithmTrace(Generic[Result, Step]):
14
+ """An algorithm result together with its immutable progress snapshots.
15
+
16
+ Attributes:
17
+ result: The final result returned by the analysis.
18
+ steps: Snapshots emitted during that analysis, in execution order.
19
+ """
20
+
21
+ result: Result
22
+ steps: tuple[Step, ...]
mocha/io/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Parsing and import/export helpers for formulas and transition systems."""
2
+
3
+ from .ltl import LTLParseError, parse_ltl
4
+ from .transition_system import (
5
+ from_dict,
6
+ load_transition_system,
7
+ save_transition_system,
8
+ to_dict,
9
+ validate_dict,
10
+ )
11
+
12
+ __all__ = [
13
+ "LTLParseError",
14
+ "parse_ltl",
15
+ "from_dict",
16
+ "load_transition_system",
17
+ "save_transition_system",
18
+ "to_dict",
19
+ "validate_dict",
20
+ ]
mocha/io/ltl.py ADDED
@@ -0,0 +1,195 @@
1
+ """Parse LTL text into immutable formula syntax trees."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ import json
8
+ import re
9
+
10
+ from mocha.logic._syntax import LTL_KEYWORDS as _KEYWORDS, LTL_TEMPORAL_CHAIN as _TEMPORAL_CHAIN
11
+ from mocha.logic.ltl import (
12
+ Always,
13
+ And,
14
+ BooleanConstant,
15
+ Equiv,
16
+ Eventually,
17
+ Implies,
18
+ LTLFormula,
19
+ Next,
20
+ Not,
21
+ Or,
22
+ Proposition,
23
+ Release,
24
+ Until,
25
+ WeakUntil,
26
+ propositions,
27
+ )
28
+
29
+
30
+ class LTLParseError(ValueError):
31
+ """Invalid LTL syntax, with a one-based source location."""
32
+
33
+ def __init__(self, source: str, position: int, message: str) -> None:
34
+ line = source.count("\n", 0, position) + 1
35
+ column = position - source.rfind("\n", 0, position)
36
+ self.position = position
37
+ self.line = line
38
+ self.column = column
39
+ super().__init__(f"{message} at line {line}, column {column}")
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class _Token:
44
+ kind: str
45
+ value: str
46
+ position: int
47
+
48
+
49
+ _TOKEN = re.compile(
50
+ r'(?P<quoted>"(?:\\.|[^"\\])*")'
51
+ r'|(?P<operator><->|->|&&|\|\||[!&|()¬∧∨→↔○◯□◇])'
52
+ r'|(?P<identifier>[A-Za-z_][A-Za-z_0-9]*)'
53
+ )
54
+ _UNARY = {"!": Not, "X": Next, "F": Eventually, "G": Always}
55
+ _BINARY = {
56
+ "<->": (1, Equiv),
57
+ "->": (2, Implies),
58
+ "|": (3, Or),
59
+ "&": (4, And),
60
+ "U": (5, Until),
61
+ "W": (5, WeakUntil),
62
+ "R": (5, Release),
63
+ }
64
+ _NON_ASSOCIATIVE = {"->", "U", "W", "R"}
65
+ _OPERATOR_ALIASES = {
66
+ "&&": "&", "||": "|", "¬": "!", "∧": "&", "∨": "|",
67
+ "→": "->", "↔": "<->", "○": "X", "◯": "X", "□": "G", "◇": "F",
68
+ }
69
+
70
+
71
+ def _tokenize(source: str) -> list[_Token]:
72
+ tokens: list[_Token] = []
73
+ position = 0
74
+ while position < len(source):
75
+ if source[position].isspace():
76
+ position += 1
77
+ continue
78
+ match = _TOKEN.match(source, position)
79
+ if match is None:
80
+ raise LTLParseError(source, position, "Unexpected character")
81
+ value = match.group()
82
+ if match.lastgroup == "quoted":
83
+ try:
84
+ value = json.loads(value)
85
+ except json.JSONDecodeError as error:
86
+ raise LTLParseError(
87
+ source, position, "Invalid quoted proposition"
88
+ ) from error
89
+ kind = "proposition"
90
+ elif match.lastgroup == "identifier":
91
+ if _TEMPORAL_CHAIN.fullmatch(value):
92
+ tokens.extend(_Token("keyword", operator, position + offset)
93
+ for offset, operator in enumerate(value))
94
+ position = match.end()
95
+ continue
96
+ if value not in _KEYWORDS:
97
+ raise LTLParseError(
98
+ source, position, "Proposition names must be enclosed in double quotes"
99
+ )
100
+ kind = "keyword"
101
+ else:
102
+ kind = "operator"
103
+ value = _OPERATOR_ALIASES.get(value, value)
104
+ tokens.append(_Token(kind, value, position))
105
+ position = match.end()
106
+ tokens.append(_Token("end", "", len(source)))
107
+ return tokens
108
+
109
+
110
+ class _Parser:
111
+ def __init__(self, source: str) -> None:
112
+ self.source = source
113
+ self.tokens = _tokenize(source)
114
+ self.index = 0
115
+
116
+ @property
117
+ def current(self) -> _Token:
118
+ return self.tokens[self.index]
119
+
120
+ def advance(self) -> _Token:
121
+ token = self.current
122
+ self.index += 1
123
+ return token
124
+
125
+ def expression(self, minimum_precedence: int = 1) -> LTLFormula:
126
+ token = self.advance()
127
+ if token.kind == "operator" and token.value == "(":
128
+ left = self.expression()
129
+ if self.current.value != ")":
130
+ raise LTLParseError(self.source, self.current.position, "Expected ')'")
131
+ self.advance()
132
+ elif token.kind == "proposition":
133
+ left = Proposition(token.value)
134
+ elif token.kind == "keyword" and token.value in {"true", "false"}:
135
+ left = BooleanConstant(token.value == "true")
136
+ elif token.kind in {"keyword", "operator"} and token.value in _UNARY:
137
+ left = _UNARY[token.value](self.expression(6))
138
+ else:
139
+ raise LTLParseError(self.source, token.position, "Expected a formula")
140
+
141
+ previous_precedence: int | None = None
142
+ while (
143
+ self.current.kind in {"keyword", "operator"}
144
+ and self.current.value in _BINARY
145
+ ):
146
+ precedence, constructor = _BINARY[self.current.value]
147
+ if precedence < minimum_precedence:
148
+ break
149
+ if precedence == previous_precedence and self.current.value in _NON_ASSOCIATIVE:
150
+ operators = "implications" if self.current.value == "->" else "U, W, or R"
151
+ raise LTLParseError(
152
+ self.source, self.current.position,
153
+ f"Parentheses are required when chaining {operators}",
154
+ )
155
+ self.advance()
156
+ left = constructor(left, self.expression(precedence + 1))
157
+ previous_precedence = precedence
158
+ return left
159
+
160
+ def parse(self) -> LTLFormula:
161
+ formula = self.expression()
162
+ if self.current.kind != "end":
163
+ raise LTLParseError(
164
+ self.source, self.current.position, "Unexpected token"
165
+ )
166
+ return formula
167
+
168
+
169
+ def parse_ltl(
170
+ source: str,
171
+ *,
172
+ atomic_propositions: Iterable[str] | None = None,
173
+ ) -> LTLFormula:
174
+ """Parse LTL, optionally checking names against a system's propositions.
175
+
176
+ Pass ``ts.atomic_propositions`` for a string-valued transition system.
177
+ All proposition names require double quotes, including single letters.
178
+ Runs consisting only of ``X``, ``F``, and ``G`` are unary operator chains
179
+ (``XX"p"``, ``GF("p")``). Boolean constants remain unquoted.
180
+ Chained implications and combinations of ``U``, ``W``, and ``R`` require
181
+ explicit parentheses. Boolean conjunction, disjunction, and equivalence
182
+ may be chained without parentheses and are grouped to the left.
183
+ Use ``formula.to_source()`` for serialization; ``str(formula)`` is display notation.
184
+ Syntax errors raise :class:`LTLParseError` with a line and column;
185
+ undeclared propositions raise ``ValueError``.
186
+ """
187
+ formula = _Parser(source).parse()
188
+ if atomic_propositions is not None:
189
+ unknown = propositions(formula) - frozenset(atomic_propositions)
190
+ if unknown:
191
+ raise ValueError(f"Unknown atomic propositions: {sorted(unknown)!r}")
192
+ return formula
193
+
194
+
195
+ __all__ = ["LTLParseError", "parse_ltl"]
@@ -0,0 +1 @@
1
+ """Package containing bundled JSON Schema resources."""
@@ -0,0 +1,95 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+
4
+ "title": "MoChA Transition System",
5
+ "description": "A labelled transition system used by the MoChA framework.",
6
+
7
+ "type": "object",
8
+ "additionalProperties": false,
9
+
10
+ "required": [
11
+ "schema_version",
12
+ "kind",
13
+ "states",
14
+ "actions",
15
+ "initial_states",
16
+ "atomic_propositions",
17
+ "labels",
18
+ "transitions"
19
+ ],
20
+
21
+ "properties": {
22
+ "schema_version": {
23
+ "const": 1
24
+ },
25
+
26
+ "kind": {
27
+ "const": "transition_system"
28
+ },
29
+
30
+ "states": {
31
+ "type": "array",
32
+ "items": {
33
+ "type": "string"
34
+ },
35
+ "uniqueItems": true
36
+ },
37
+
38
+ "actions": {
39
+ "type": "array",
40
+ "items": {
41
+ "type": "string"
42
+ },
43
+ "uniqueItems": true
44
+ },
45
+
46
+ "initial_states": {
47
+ "type": "array",
48
+ "items": {
49
+ "type": "string"
50
+ },
51
+ "uniqueItems": true
52
+ },
53
+
54
+ "atomic_propositions": {
55
+ "type": "array",
56
+ "items": {
57
+ "type": "string"
58
+ },
59
+ "uniqueItems": true
60
+ },
61
+
62
+ "labels": {
63
+ "type": "object",
64
+ "additionalProperties": {
65
+ "type": "array",
66
+ "items": {
67
+ "type": "string"
68
+ },
69
+ "uniqueItems": true
70
+ }
71
+ },
72
+
73
+ "transitions": {
74
+ "type": "array",
75
+ "items": {
76
+ "type": "array",
77
+ "minItems": 3,
78
+ "maxItems": 3,
79
+ "prefixItems": [
80
+ {
81
+ "type": "string"
82
+ },
83
+ {
84
+ "type": "string"
85
+ },
86
+ {
87
+ "type": "string"
88
+ }
89
+ ],
90
+ "items": false
91
+ },
92
+ "uniqueItems": true
93
+ }
94
+ }
95
+ }
@@ -0,0 +1,136 @@
1
+ """Read, write, and validate versioned JSON transition-system documents.
2
+
3
+ The document format represents string-valued transition systems with
4
+ the keys ``states``, ``actions``, ``initial_states``, ``atomic_propositions``,
5
+ ``labels``, and ``transitions``. Its JSON Schema validates document structure;
6
+ the model constructor additionally validates cross-references such as a
7
+ transition endpoint being a declared state.
8
+ """
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any, cast
13
+ from importlib.resources import files
14
+
15
+ from jsonschema import Draft202012Validator
16
+
17
+ from mocha.models.transition_system import TransitionSystem
18
+
19
+ _SCHEMA_PATH = (
20
+ files("mocha.io.schemas")
21
+ / "transition-system.schema.json"
22
+ )
23
+
24
+ with _SCHEMA_PATH.open(encoding="utf-8") as file:
25
+ _SCHEMA = json.load(file)
26
+
27
+ Draft202012Validator.check_schema(_SCHEMA)
28
+
29
+ _VALIDATOR = Draft202012Validator(_SCHEMA)
30
+
31
+
32
+ __all__ = [
33
+ "from_dict",
34
+ "load_transition_system",
35
+ "save_transition_system",
36
+ "to_dict",
37
+ "validate_dict",
38
+ ]
39
+
40
+
41
+ def validate_dict(data: object) -> None:
42
+ """Validate a decoded JSON document against the schema.
43
+
44
+ Raises :class:`jsonschema.ValidationError` when the document has an
45
+ unsupported version, an invalid shape, or invalid value types. This checks
46
+ structural constraints only; use :func:`from_dict` to also construct and
47
+ validate a transition system's component relationships.
48
+ """
49
+ _VALIDATOR.validate(data)
50
+
51
+
52
+ def to_dict(
53
+ ts: TransitionSystem[str, str, str],
54
+ ) -> dict[str, object]:
55
+ """Convert a string-valued transition system to a JSON-compatible dict.
56
+
57
+ Collections are sorted so identical systems produce deterministic output.
58
+ The returned document conforms to the version-1 transition-system schema.
59
+ """
60
+ return {
61
+ "schema_version": 1,
62
+ "kind": "transition_system",
63
+ "states": sorted(ts.states),
64
+ "actions": sorted(ts.actions),
65
+ "initial_states": sorted(ts.initial_states),
66
+ "atomic_propositions": sorted(ts.atomic_propositions),
67
+ "labels": {
68
+ state: sorted(ts.labels(state))
69
+ for state in sorted(ts.states)
70
+ },
71
+ "transitions": [
72
+ [source, action, target]
73
+ for source, action, target in sorted(ts.transitions())
74
+ ],
75
+ }
76
+
77
+
78
+ def from_dict(
79
+ data: object,
80
+ ) -> TransitionSystem[str, str, str]:
81
+ """Construct a transition system from a validated JSON-compatible dict.
82
+
83
+ The document is first checked against the JSON Schema, then passed to the
84
+ strict :meth:`TransitionSystem.from_components` constructor. Consequently,
85
+ malformed document structure raises ``ValidationError`` and invalid model
86
+ cross-references raise ``ValueError``.
87
+ """
88
+ validate_dict(data)
89
+
90
+ obj = cast(dict[str, Any], data)
91
+
92
+ transitions = [
93
+ tuple(transition)
94
+ for transition in obj["transitions"]
95
+ ]
96
+
97
+ return TransitionSystem.from_components(
98
+ states=obj["states"],
99
+ actions=obj["actions"],
100
+ transitions=transitions,
101
+ initial_states=obj["initial_states"],
102
+ atomic_propositions=obj["atomic_propositions"],
103
+ labels=obj["labels"],
104
+ )
105
+
106
+ def save_transition_system(
107
+ ts: TransitionSystem[str, str, str],
108
+ path: str | Path,
109
+ ) -> None:
110
+ """Write ``ts`` as UTF-8, indented JSON to ``path``.
111
+
112
+ Existing files at ``path`` are replaced. The output ends in a newline and
113
+ uses deterministic ordering supplied by :func:`to_dict`.
114
+ """
115
+ with Path(path).open("w", encoding="utf-8") as file:
116
+ json.dump(
117
+ to_dict(ts),
118
+ file,
119
+ indent=2,
120
+ ensure_ascii=False,
121
+ )
122
+ file.write("\n")
123
+
124
+
125
+ def load_transition_system(
126
+ path: str | Path,
127
+ ) -> TransitionSystem[str, str, str]:
128
+ """Load a UTF-8 JSON transition-system document from ``path``.
129
+
130
+ JSON parsing errors propagate as ``JSONDecodeError``; schema and model
131
+ validation errors propagate from :func:`from_dict`.
132
+ """
133
+ with Path(path).open("r", encoding="utf-8") as file:
134
+ data = json.load(file)
135
+
136
+ return from_dict(data)
@@ -0,0 +1,5 @@
1
+ """Temporal logic formulas, formatting, and transformations."""
2
+
3
+ from . import ltl
4
+
5
+ __all__ = ["ltl"]
mocha/logic/_syntax.py ADDED
@@ -0,0 +1,8 @@
1
+ """Shared lexical definitions for formula parsing and formatting."""
2
+
3
+ import re
4
+
5
+
6
+ LTL_KEYWORDS = {"true", "false", "X", "F", "G", "U", "W", "R"}
7
+
8
+ LTL_TEMPORAL_CHAIN = re.compile(r"[XFG]+")
mocha/logic/ltl.py ADDED
@@ -0,0 +1,179 @@
1
+ """Immutable LTL syntax trees and formatting.
2
+
3
+ Precedence, from strongest to weakest: ``! X F G``, ``U W R``, ``&``, ``|``,
4
+ ``->``, ``<->``. Chained implications and combinations of ``U``, ``W``, and
5
+ ``R`` require explicit parentheses. The other binary operators associate to
6
+ the left. Parentheses override precedence. Both ASCII and textbook Unicode
7
+ operator spellings are accepted; string output uses the latter.
8
+ Propositions must be double-quoted. ASCII unary temporal operators may be
9
+ adjacent, as in ``XX"p"`` or ``GF("p")``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ import json
16
+ import re
17
+
18
+ from ._syntax import LTL_KEYWORDS as _KEYWORDS, LTL_TEMPORAL_CHAIN as _TEMPORAL_CHAIN
19
+
20
+
21
+ class LTLFormula:
22
+ """Base type for an LTL syntax tree."""
23
+
24
+ def __str__(self) -> str:
25
+ """Return textbook display notation; use to_source() for parser input."""
26
+ return _format_formula(self)
27
+
28
+ def to_source(self) -> str:
29
+ """Serialize with quoted propositions for :func:`mocha.io.ltl.parse_ltl`."""
30
+ return _format_formula(self, quote_propositions=True)
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class BooleanConstant(LTLFormula):
35
+ value: bool
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class Proposition(LTLFormula):
40
+ name: str
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class Not(LTLFormula):
45
+ operand: LTLFormula
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Next(LTLFormula):
50
+ operand: LTLFormula
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class Eventually(LTLFormula):
55
+ operand: LTLFormula
56
+
57
+
58
+ @dataclass(frozen=True, slots=True)
59
+ class Always(LTLFormula):
60
+ operand: LTLFormula
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class And(LTLFormula):
65
+ left: LTLFormula
66
+ right: LTLFormula
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class Or(LTLFormula):
71
+ left: LTLFormula
72
+ right: LTLFormula
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class Implies(LTLFormula):
77
+ left: LTLFormula
78
+ right: LTLFormula
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class Equiv(LTLFormula):
83
+ left: LTLFormula
84
+ right: LTLFormula
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class Until(LTLFormula):
89
+ left: LTLFormula
90
+ right: LTLFormula
91
+
92
+
93
+ @dataclass(frozen=True, slots=True)
94
+ class WeakUntil(LTLFormula):
95
+ left: LTLFormula
96
+ right: LTLFormula
97
+
98
+
99
+ @dataclass(frozen=True, slots=True)
100
+ class Release(LTLFormula):
101
+ left: LTLFormula
102
+ right: LTLFormula
103
+
104
+
105
+ _UnaryFormula = Not | Next | Eventually | Always
106
+ _BinaryFormula = And | Or | Implies | Equiv | Until | WeakUntil | Release
107
+
108
+
109
+ _BINARY_PRINT: dict[type[_BinaryFormula], tuple[int, str, bool]] = {
110
+ And: (4, "∧", False),
111
+ Or: (3, "∨", False),
112
+ Implies: (2, "→", True),
113
+ Equiv: (1, "↔", False),
114
+ Until: (5, "U", True),
115
+ WeakUntil: (5, "W", True),
116
+ Release: (5, "R", True),
117
+ }
118
+ _UNARY_PRINT: dict[type[_UnaryFormula], str] = {
119
+ Not: "¬", Next: "◯", Eventually: "◇", Always: "□",
120
+ }
121
+
122
+
123
+ def _format_formula(
124
+ formula: LTLFormula, minimum_precedence: int = 0, *, quote_propositions: bool = False,
125
+ ) -> str:
126
+ if isinstance(formula, BooleanConstant):
127
+ return "true" if formula.value else "false"
128
+ if isinstance(formula, Proposition):
129
+ if not quote_propositions and re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", formula.name) and (
130
+ formula.name not in _KEYWORDS
131
+ and not _TEMPORAL_CHAIN.fullmatch(formula.name)
132
+ ):
133
+ return formula.name
134
+ return json.dumps(formula.name, ensure_ascii=False)
135
+ for unary_type, symbol in _UNARY_PRINT.items():
136
+ if isinstance(formula, unary_type):
137
+ result = symbol + _format_formula(formula.operand, 6, quote_propositions=quote_propositions)
138
+ return f"({result})" if 6 < minimum_precedence else result
139
+ for binary_type, (precedence, symbol, non_associative) in _BINARY_PRINT.items():
140
+ if isinstance(formula, binary_type):
141
+ left_minimum = precedence + 1 if non_associative else precedence
142
+ right_minimum = precedence + 1
143
+ left = _format_formula(formula.left, left_minimum, quote_propositions=quote_propositions)
144
+ right = _format_formula(formula.right, right_minimum, quote_propositions=quote_propositions)
145
+ result = f"{left} {symbol} {right}"
146
+ return f"({result})" if precedence < minimum_precedence else result
147
+ raise TypeError(f"Unknown LTL formula node: {type(formula).__name__}")
148
+
149
+
150
+ def complement(formula: LTLFormula) -> LTLFormula:
151
+ """Negate a formula, cancelling an outer negation or flipping a constant.
152
+
153
+ Other formulas are wrapped in ``Not`` without further normalization.
154
+ """
155
+ if isinstance(formula, Not):
156
+ return formula.operand
157
+ if isinstance(formula, BooleanConstant):
158
+ return BooleanConstant(not formula.value)
159
+ return Not(formula)
160
+
161
+
162
+ def propositions(formula: LTLFormula) -> frozenset[str]:
163
+ """Return the atomic proposition names referenced by a formula."""
164
+ if isinstance(formula, Proposition):
165
+ return frozenset({formula.name})
166
+ if isinstance(formula, BooleanConstant):
167
+ return frozenset()
168
+ if isinstance(formula, (Not, Next, Eventually, Always)):
169
+ return propositions(formula.operand)
170
+ if isinstance(formula, (And, Or, Implies, Equiv, Until, WeakUntil, Release)):
171
+ return propositions(formula.left) | propositions(formula.right)
172
+ raise TypeError(f"Unknown LTL formula node: {type(formula).__name__}")
173
+
174
+
175
+ __all__ = [
176
+ "Always", "And", "BooleanConstant", "Equiv", "Eventually", "Implies",
177
+ "LTLFormula", "Next", "Not", "Or", "Proposition",
178
+ "Release", "Until", "WeakUntil", "complement", "propositions",
179
+ ]