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.
- mocha/__init__.py +199 -0
- mocha/algorithms/__init__.py +159 -0
- mocha/algorithms/automata.py +205 -0
- mocha/algorithms/invariance.py +166 -0
- mocha/algorithms/ltl2gnba/__init__.py +75 -0
- mocha/algorithms/ltl2gnba/acceptance.py +199 -0
- mocha/algorithms/ltl2gnba/elementary_set_enumeration.py +360 -0
- mocha/algorithms/ltl2gnba/elementary_set_validation.py +312 -0
- mocha/algorithms/ltl2gnba/initial_states.py +116 -0
- mocha/algorithms/ltl2gnba/pipeline.py +137 -0
- mocha/algorithms/ltl2gnba/transitions.py +327 -0
- mocha/algorithms/ltl_model_checking.py +313 -0
- mocha/algorithms/ltl_satisfiability_validity.py +308 -0
- mocha/algorithms/ltl_transformations.py +291 -0
- mocha/algorithms/persistence.py +259 -0
- mocha/algorithms/reachability.py +143 -0
- mocha/algorithms/trace.py +22 -0
- mocha/io/__init__.py +20 -0
- mocha/io/ltl.py +195 -0
- mocha/io/schemas/__init__.py +1 -0
- mocha/io/schemas/transition-system.schema.json +95 -0
- mocha/io/transition_system.py +136 -0
- mocha/logic/__init__.py +5 -0
- mocha/logic/_syntax.py +8 -0
- mocha/logic/ltl.py +179 -0
- mocha/models/__init__.py +37 -0
- mocha/models/automaton.py +604 -0
- mocha/models/transition_system.py +535 -0
- mocha/py.typed +0 -0
- mocha/visualisation/__init__.py +55 -0
- mocha/visualisation/automaton.py +170 -0
- mocha/visualisation/invariance.py +84 -0
- mocha/visualisation/overlay.py +24 -0
- mocha/visualisation/persistence.py +48 -0
- mocha/visualisation/reachability.py +35 -0
- mocha/visualisation/transition_system.py +252 -0
- mocha_model_checking-0.1.0.dist-info/METADATA +587 -0
- mocha_model_checking-0.1.0.dist-info/RECORD +41 -0
- mocha_model_checking-0.1.0.dist-info/WHEEL +5 -0
- mocha_model_checking-0.1.0.dist-info/licenses/LICENCE +340 -0
- mocha_model_checking-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""LTL normal forms and traces of their local rewrite steps.
|
|
2
|
+
|
|
3
|
+
Formula types and formatting live in :mod:`mocha.logic.ltl`. These
|
|
4
|
+
transformations require no automaton construction or decision procedures.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from mocha.logic.ltl import (
|
|
12
|
+
Always, And, BooleanConstant, Equiv, Eventually, Implies,
|
|
13
|
+
LTLFormula, Next, Not, Or, Proposition, Release, Until, WeakUntil,
|
|
14
|
+
complement,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from .trace import AlgorithmTrace
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class LTLRewriteStep:
|
|
22
|
+
"""One immutable snapshot in a formula transformation.
|
|
23
|
+
|
|
24
|
+
``formula`` is the entire formula after the rewrite. ``path`` locates the
|
|
25
|
+
replaced subformula in the preceding snapshot, using ``operand``, ``left``,
|
|
26
|
+
and ``right`` as path components. The initial snapshot has rule ``initial``
|
|
27
|
+
and no local ``before`` or ``after`` formula.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
iteration: int
|
|
31
|
+
rule: str
|
|
32
|
+
formula: LTLFormula
|
|
33
|
+
path: tuple[str, ...]
|
|
34
|
+
before: LTLFormula | None
|
|
35
|
+
after: LTLFormula | None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_Mode = Literal["core", "weak_until", "release"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _local_rewrite(
|
|
42
|
+
formula: LTLFormula,
|
|
43
|
+
mode: _Mode,
|
|
44
|
+
) -> tuple[str, LTLFormula] | None:
|
|
45
|
+
"""Apply one rule at the current node, before visiting its children."""
|
|
46
|
+
if isinstance(formula, Not):
|
|
47
|
+
operand = formula.operand
|
|
48
|
+
if isinstance(operand, BooleanConstant):
|
|
49
|
+
return "negate_constant", complement(operand)
|
|
50
|
+
if isinstance(operand, Not):
|
|
51
|
+
return "double_negation", complement(operand)
|
|
52
|
+
if mode != "core":
|
|
53
|
+
if isinstance(operand, And):
|
|
54
|
+
return "de_morgan_and", Or(Not(operand.left), Not(operand.right))
|
|
55
|
+
if isinstance(operand, Or):
|
|
56
|
+
return "de_morgan_or", And(Not(operand.left), Not(operand.right))
|
|
57
|
+
if isinstance(operand, Next):
|
|
58
|
+
return "negate_next", Next(Not(operand.operand))
|
|
59
|
+
if isinstance(operand, Until):
|
|
60
|
+
if mode == "release":
|
|
61
|
+
return "negate_until", Release(
|
|
62
|
+
Not(operand.left), Not(operand.right)
|
|
63
|
+
)
|
|
64
|
+
not_right = Not(operand.right)
|
|
65
|
+
return "negate_until", WeakUntil(
|
|
66
|
+
And(operand.left, not_right),
|
|
67
|
+
And(Not(operand.left), not_right),
|
|
68
|
+
)
|
|
69
|
+
if isinstance(operand, WeakUntil):
|
|
70
|
+
not_right = Not(operand.right)
|
|
71
|
+
return "negate_weak_until", Until(
|
|
72
|
+
And(operand.left, not_right),
|
|
73
|
+
And(Not(operand.left), not_right),
|
|
74
|
+
)
|
|
75
|
+
if isinstance(operand, Release):
|
|
76
|
+
return "negate_release", Until(
|
|
77
|
+
Not(operand.left), Not(operand.right)
|
|
78
|
+
)
|
|
79
|
+
if isinstance(operand, Eventually):
|
|
80
|
+
negative_child = Not(operand.operand)
|
|
81
|
+
if mode == "weak_until":
|
|
82
|
+
return "negate_eventually", WeakUntil(
|
|
83
|
+
negative_child, BooleanConstant(False)
|
|
84
|
+
)
|
|
85
|
+
return "negate_eventually", Release(
|
|
86
|
+
BooleanConstant(False), negative_child
|
|
87
|
+
)
|
|
88
|
+
if isinstance(operand, Always):
|
|
89
|
+
return "negate_always", Until(
|
|
90
|
+
BooleanConstant(True), Not(operand.operand)
|
|
91
|
+
)
|
|
92
|
+
if isinstance(operand, Implies):
|
|
93
|
+
return "negate_implication", And(
|
|
94
|
+
operand.left, Not(operand.right)
|
|
95
|
+
)
|
|
96
|
+
if isinstance(operand, Equiv):
|
|
97
|
+
return "negate_equivalence", Or(
|
|
98
|
+
And(operand.left, Not(operand.right)),
|
|
99
|
+
And(Not(operand.left), operand.right),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if mode == "core":
|
|
103
|
+
if isinstance(formula, Or):
|
|
104
|
+
return "eliminate_or", Not(And(Not(formula.left), Not(formula.right)))
|
|
105
|
+
if isinstance(formula, Implies):
|
|
106
|
+
return "eliminate_implication", Not(
|
|
107
|
+
And(formula.left, Not(formula.right))
|
|
108
|
+
)
|
|
109
|
+
if isinstance(formula, Equiv):
|
|
110
|
+
return "eliminate_equivalence", And(
|
|
111
|
+
Not(And(formula.left, Not(formula.right))),
|
|
112
|
+
Not(And(formula.right, Not(formula.left))),
|
|
113
|
+
)
|
|
114
|
+
if isinstance(formula, Eventually):
|
|
115
|
+
return "eliminate_eventually", Until(
|
|
116
|
+
BooleanConstant(True), formula.operand
|
|
117
|
+
)
|
|
118
|
+
if isinstance(formula, Always):
|
|
119
|
+
return "eliminate_always", Not(
|
|
120
|
+
Until(BooleanConstant(True), Not(formula.operand))
|
|
121
|
+
)
|
|
122
|
+
if isinstance(formula, WeakUntil):
|
|
123
|
+
not_right = Not(formula.right)
|
|
124
|
+
return "eliminate_weak_until", Not(Until(
|
|
125
|
+
And(formula.left, not_right),
|
|
126
|
+
And(Not(formula.left), not_right),
|
|
127
|
+
))
|
|
128
|
+
if isinstance(formula, Release):
|
|
129
|
+
return "eliminate_release", Not(Until(
|
|
130
|
+
Not(formula.left), Not(formula.right)
|
|
131
|
+
))
|
|
132
|
+
else:
|
|
133
|
+
if isinstance(formula, Implies):
|
|
134
|
+
return "eliminate_implication", Or(Not(formula.left), formula.right)
|
|
135
|
+
if isinstance(formula, Equiv):
|
|
136
|
+
return "eliminate_equivalence", Or(
|
|
137
|
+
And(formula.left, formula.right),
|
|
138
|
+
And(Not(formula.left), Not(formula.right)),
|
|
139
|
+
)
|
|
140
|
+
if isinstance(formula, Eventually):
|
|
141
|
+
return "eliminate_eventually", Until(
|
|
142
|
+
BooleanConstant(True), formula.operand
|
|
143
|
+
)
|
|
144
|
+
if isinstance(formula, Always):
|
|
145
|
+
if mode == "weak_until":
|
|
146
|
+
return "eliminate_always", WeakUntil(
|
|
147
|
+
formula.operand, BooleanConstant(False)
|
|
148
|
+
)
|
|
149
|
+
return "eliminate_always", Release(
|
|
150
|
+
BooleanConstant(False), formula.operand
|
|
151
|
+
)
|
|
152
|
+
if isinstance(formula, WeakUntil) and mode == "release":
|
|
153
|
+
return "eliminate_weak_until", Release(
|
|
154
|
+
formula.right, Or(formula.left, formula.right)
|
|
155
|
+
)
|
|
156
|
+
if isinstance(formula, Release) and mode == "weak_until":
|
|
157
|
+
return "eliminate_release", WeakUntil(
|
|
158
|
+
And(Not(formula.left), formula.right),
|
|
159
|
+
And(formula.left, formula.right),
|
|
160
|
+
)
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _first_rewrite(
|
|
165
|
+
formula: LTLFormula,
|
|
166
|
+
mode: _Mode,
|
|
167
|
+
) -> tuple[LTLFormula, tuple[str, ...], str, LTLFormula, LTLFormula] | None:
|
|
168
|
+
"""Find the first rewrite and embed it in the entire current formula."""
|
|
169
|
+
local = _local_rewrite(formula, mode)
|
|
170
|
+
if local is not None:
|
|
171
|
+
rule, replacement = local
|
|
172
|
+
return replacement, (), rule, formula, replacement
|
|
173
|
+
|
|
174
|
+
if isinstance(formula, (Not, Next, Eventually, Always)):
|
|
175
|
+
nested = _first_rewrite(formula.operand, mode)
|
|
176
|
+
if nested is None:
|
|
177
|
+
return None
|
|
178
|
+
child, path, rule, before, after = nested
|
|
179
|
+
return replace(formula, operand=child), ("operand",) + path, rule, before, after
|
|
180
|
+
if isinstance(formula, (And, Or, Implies, Equiv, Until, WeakUntil, Release)):
|
|
181
|
+
for side in ("left", "right"):
|
|
182
|
+
nested = _first_rewrite(getattr(formula, side), mode)
|
|
183
|
+
if nested is not None:
|
|
184
|
+
child, path, rule, before, after = nested
|
|
185
|
+
return (replace(formula, **{side: child}),
|
|
186
|
+
(side,) + path, rule, before, after)
|
|
187
|
+
return None
|
|
188
|
+
if isinstance(formula, (BooleanConstant, Proposition)):
|
|
189
|
+
return None
|
|
190
|
+
raise TypeError(f"Unknown LTL formula node: {type(formula).__name__}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _transform(
|
|
194
|
+
formula: LTLFormula,
|
|
195
|
+
mode: _Mode,
|
|
196
|
+
on_step: Callable[[LTLRewriteStep], None] | None,
|
|
197
|
+
) -> LTLFormula:
|
|
198
|
+
if on_step is not None:
|
|
199
|
+
on_step(LTLRewriteStep(0, "initial", formula, (), None, None))
|
|
200
|
+
current = formula
|
|
201
|
+
iteration = 0
|
|
202
|
+
while rewrite := _first_rewrite(current, mode):
|
|
203
|
+
current, path, rule, before, after = rewrite
|
|
204
|
+
iteration += 1
|
|
205
|
+
if on_step is not None:
|
|
206
|
+
on_step(LTLRewriteStep(iteration, rule, current, path, before, after))
|
|
207
|
+
return current
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def normalize_ltl(
|
|
211
|
+
formula: LTLFormula,
|
|
212
|
+
*,
|
|
213
|
+
on_step: Callable[[LTLRewriteStep], None] | None = None,
|
|
214
|
+
) -> LTLFormula:
|
|
215
|
+
"""Rewrite a formula using only ``&``, ``!``, ``X``, and ``U``.
|
|
216
|
+
|
|
217
|
+
Boolean constants and atomic propositions remain as leaves. This is an
|
|
218
|
+
operator normalization, not positive normal form: negation may still apply
|
|
219
|
+
to an ``Until`` formula. The result is equivalent on infinite words and
|
|
220
|
+
applying this function again leaves it unchanged. ``on_step`` receives an
|
|
221
|
+
initial snapshot and one snapshot after every local rewrite.
|
|
222
|
+
"""
|
|
223
|
+
return _transform(formula, "core", on_step)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def to_weak_until_pnf(
|
|
227
|
+
formula: LTLFormula,
|
|
228
|
+
*,
|
|
229
|
+
on_step: Callable[[LTLRewriteStep], None] | None = None,
|
|
230
|
+
) -> LTLFormula:
|
|
231
|
+
"""Return weak-until PNF: negation only on atoms, using ``U`` and ``W``.
|
|
232
|
+
|
|
233
|
+
Other permitted nodes are Boolean constants, propositions, ``And``,
|
|
234
|
+
``Or``, and ``Next``. This follows Definition 5.20 in *Principles of Model
|
|
235
|
+
Checking*. The result is equivalent to ``formula`` on infinite words.
|
|
236
|
+
``on_step`` receives an initial snapshot and each local rewrite.
|
|
237
|
+
"""
|
|
238
|
+
return _transform(formula, "weak_until", on_step)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def to_release_pnf(
|
|
242
|
+
formula: LTLFormula,
|
|
243
|
+
*,
|
|
244
|
+
on_step: Callable[[LTLRewriteStep], None] | None = None,
|
|
245
|
+
) -> LTLFormula:
|
|
246
|
+
"""Return release PNF: negation only on atoms, using ``U`` and ``R``.
|
|
247
|
+
|
|
248
|
+
Other permitted nodes are Boolean constants, propositions, ``And``,
|
|
249
|
+
``Or``, and ``Next``. This follows Definition 5.23 in *Principles of Model
|
|
250
|
+
Checking*. The result is equivalent to ``formula`` on infinite words.
|
|
251
|
+
``on_step`` receives an initial snapshot and each local rewrite.
|
|
252
|
+
"""
|
|
253
|
+
return _transform(formula, "release", on_step)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def trace_normalize_ltl(
|
|
257
|
+
formula: LTLFormula,
|
|
258
|
+
) -> AlgorithmTrace[LTLFormula, LTLRewriteStep]:
|
|
259
|
+
"""Return the core-operator formula and every local rewrite snapshot."""
|
|
260
|
+
steps: list[LTLRewriteStep] = []
|
|
261
|
+
result = normalize_ltl(formula, on_step=steps.append)
|
|
262
|
+
return AlgorithmTrace(result=result, steps=tuple(steps))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def trace_weak_until_pnf(
|
|
266
|
+
formula: LTLFormula,
|
|
267
|
+
) -> AlgorithmTrace[LTLFormula, LTLRewriteStep]:
|
|
268
|
+
"""Return weak-until PNF and every local rewrite snapshot."""
|
|
269
|
+
steps: list[LTLRewriteStep] = []
|
|
270
|
+
result = to_weak_until_pnf(formula, on_step=steps.append)
|
|
271
|
+
return AlgorithmTrace(result=result, steps=tuple(steps))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def trace_release_pnf(
|
|
275
|
+
formula: LTLFormula,
|
|
276
|
+
) -> AlgorithmTrace[LTLFormula, LTLRewriteStep]:
|
|
277
|
+
"""Return release PNF and every local rewrite snapshot."""
|
|
278
|
+
steps: list[LTLRewriteStep] = []
|
|
279
|
+
result = to_release_pnf(formula, on_step=steps.append)
|
|
280
|
+
return AlgorithmTrace(result=result, steps=tuple(steps))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
__all__ = [
|
|
284
|
+
"LTLRewriteStep",
|
|
285
|
+
"normalize_ltl",
|
|
286
|
+
"to_release_pnf",
|
|
287
|
+
"to_weak_until_pnf",
|
|
288
|
+
"trace_normalize_ltl",
|
|
289
|
+
"trace_release_pnf",
|
|
290
|
+
"trace_weak_until_pnf",
|
|
291
|
+
]
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Persistence checking by nested depth-first search."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Callable, Generic, Hashable, TypeVar
|
|
5
|
+
|
|
6
|
+
from mocha.algorithms.trace import AlgorithmTrace
|
|
7
|
+
from mocha.models.transition_system import TransitionSystem
|
|
8
|
+
|
|
9
|
+
State = TypeVar("State", bound=Hashable)
|
|
10
|
+
Action = TypeVar("Action", bound=Hashable)
|
|
11
|
+
AtomicProposition = TypeVar("AtomicProposition", bound=Hashable)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class PersistenceResult(Generic[State]):
|
|
16
|
+
"""The result of checking the persistence property ``◇□Φ``.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
satisfies: Whether every infinite run eventually remains in states
|
|
20
|
+
satisfying the proposition.
|
|
21
|
+
counterexample: A finite lasso-shaped prefix of a violating run, or
|
|
22
|
+
``None`` if the property holds. Its final state repeats the state
|
|
23
|
+
at which the cycle begins.
|
|
24
|
+
loop_start: The cycle's first position in ``counterexample``, or
|
|
25
|
+
``None`` if there is no counterexample.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
satisfies: bool
|
|
29
|
+
counterexample: tuple[State, ...] | None = None
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def loop_start(self) -> int | None:
|
|
33
|
+
"""Index of the repeated cycle state, or ``None`` without a lasso."""
|
|
34
|
+
if self.counterexample is None:
|
|
35
|
+
return None
|
|
36
|
+
return max(
|
|
37
|
+
(index for index, state in enumerate(self.counterexample[:-1])
|
|
38
|
+
if state == self.counterexample[-1]),
|
|
39
|
+
default=None,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class PersistenceStep(Generic[State]):
|
|
45
|
+
"""A nested-DFS configuration used in persistence checking.
|
|
46
|
+
|
|
47
|
+
The fields correspond directly to the notation in *Principles of Model Checking*:
|
|
48
|
+
``outer_visited`` is ``R``, ``outer_stack`` is ``U``, ``inner_visited`` is
|
|
49
|
+
``T``, and ``inner_stack`` is ``V``. Every snapshot records the state after
|
|
50
|
+
its operation has taken effect.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
operation: The initialization, push, pop, or cycle-discovery event.
|
|
54
|
+
state: The state involved in the operation, if any.
|
|
55
|
+
outer_visited: States visited by the outer DFS.
|
|
56
|
+
outer_stack: Current outer DFS stack, from bottom to top.
|
|
57
|
+
inner_visited: States visited by all inner DFS calls so far.
|
|
58
|
+
inner_stack: Current inner DFS stack, from bottom to top.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
operation: str
|
|
62
|
+
state: State | None
|
|
63
|
+
outer_visited: frozenset[State]
|
|
64
|
+
outer_stack: tuple[State, ...]
|
|
65
|
+
inner_visited: frozenset[State]
|
|
66
|
+
inner_stack: tuple[State, ...]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cycle_check(
|
|
70
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
71
|
+
start: State,
|
|
72
|
+
visited: set[State],
|
|
73
|
+
*,
|
|
74
|
+
on_step: Callable[[str, State, tuple[State, ...]], None] | None = None,
|
|
75
|
+
) -> tuple[State, ...] | None:
|
|
76
|
+
"""Find a cycle through ``start`` using depth-first search.
|
|
77
|
+
|
|
78
|
+
This is Algorithm 7, "Cycle detection", from *Principles of Model
|
|
79
|
+
Checking*. ``visited`` is the algorithm's set ``T`` and is mutated in
|
|
80
|
+
place. Persistence checking retains it between searches, as Algorithm 8
|
|
81
|
+
requires for nested DFS. When supplied, ``on_step`` receives each inner
|
|
82
|
+
stack operation after it has occurred.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
ts: The transition system to search.
|
|
86
|
+
start: The state that must lie on the discovered cycle.
|
|
87
|
+
visited: States already visited by the inner DFS.
|
|
88
|
+
on_step: Optional callback receiving an operation, its state, and the
|
|
89
|
+
resulting inner stack.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
A cycle from ``start`` back to ``start``, including both occurrences
|
|
93
|
+
of ``start``, or ``None`` if no such cycle is found.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
ValueError: If ``start`` is not a state of ``ts``.
|
|
97
|
+
"""
|
|
98
|
+
if start not in ts.states:
|
|
99
|
+
raise ValueError(f"Unknown state {start!r}")
|
|
100
|
+
|
|
101
|
+
stack: list[State] = [start]
|
|
102
|
+
visited.add(start)
|
|
103
|
+
|
|
104
|
+
def report(operation: str, state: State) -> None:
|
|
105
|
+
if on_step is not None:
|
|
106
|
+
on_step(operation, state, tuple(stack))
|
|
107
|
+
|
|
108
|
+
report("inner_push", start)
|
|
109
|
+
|
|
110
|
+
while stack:
|
|
111
|
+
state = stack[-1]
|
|
112
|
+
|
|
113
|
+
if start in ts.post(state):
|
|
114
|
+
report("cycle_found", start)
|
|
115
|
+
return tuple(stack + [start])
|
|
116
|
+
|
|
117
|
+
unvisited_successors = ts.post(state) - visited
|
|
118
|
+
if unvisited_successors:
|
|
119
|
+
successor = next(iter(unvisited_successors))
|
|
120
|
+
stack.append(successor)
|
|
121
|
+
visited.add(successor)
|
|
122
|
+
report("inner_push", successor)
|
|
123
|
+
else:
|
|
124
|
+
popped_state = stack.pop()
|
|
125
|
+
report("inner_pop", popped_state)
|
|
126
|
+
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def check_persistence(
|
|
131
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
132
|
+
proposition: AtomicProposition,
|
|
133
|
+
*,
|
|
134
|
+
on_step: Callable[[PersistenceStep[State]], None] | None = None,
|
|
135
|
+
) -> PersistenceResult[State]:
|
|
136
|
+
"""Check whether ``ts`` satisfies the persistence property ``◇□Φ``.
|
|
137
|
+
|
|
138
|
+
This implements Algorithm 8, "Persistence checking by nested depth-first
|
|
139
|
+
search", from *Principles of Model Checking*. The outer DFS finds reachable
|
|
140
|
+
states. Once it finishes a state not satisfying ``Φ``, the inner DFS checks
|
|
141
|
+
whether that state lies on a reachable cycle. The inner visited set is
|
|
142
|
+
deliberately shared across calls, exactly as in the algorithm.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
ts: A finite transition system without terminal states.
|
|
146
|
+
proposition: The atomic proposition ``Φ`` that must eventually hold
|
|
147
|
+
forever on every run.
|
|
148
|
+
on_step: Optional callback receiving the initial configuration and
|
|
149
|
+
every outer or inner DFS stack operation.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
A successful result, or a lasso-shaped counterexample to ``◇□Φ``.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: If ``proposition`` is undeclared or ``ts`` has a terminal
|
|
156
|
+
state.
|
|
157
|
+
"""
|
|
158
|
+
if proposition not in ts.atomic_propositions:
|
|
159
|
+
raise ValueError(f"Unknown atomic proposition {proposition!r}")
|
|
160
|
+
if not ts.is_non_blocking():
|
|
161
|
+
raise ValueError(
|
|
162
|
+
"Persistence checking requires a transition system without "
|
|
163
|
+
"terminal states"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
outer_visited: set[State] = set()
|
|
167
|
+
outer_stack: list[State] = []
|
|
168
|
+
inner_visited: set[State] = set()
|
|
169
|
+
|
|
170
|
+
def report(
|
|
171
|
+
operation: str,
|
|
172
|
+
state: State | None = None,
|
|
173
|
+
inner_stack: tuple[State, ...] = (),
|
|
174
|
+
) -> None:
|
|
175
|
+
if on_step is not None:
|
|
176
|
+
on_step(
|
|
177
|
+
PersistenceStep(
|
|
178
|
+
operation=operation,
|
|
179
|
+
state=state,
|
|
180
|
+
outer_visited=frozenset(outer_visited),
|
|
181
|
+
outer_stack=tuple(outer_stack),
|
|
182
|
+
inner_visited=frozenset(inner_visited),
|
|
183
|
+
inner_stack=inner_stack,
|
|
184
|
+
)
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
report("initialize")
|
|
188
|
+
|
|
189
|
+
while unvisited_initial_states := ts.initial_states - outer_visited:
|
|
190
|
+
initial_state = next(iter(unvisited_initial_states))
|
|
191
|
+
outer_stack.append(initial_state)
|
|
192
|
+
outer_visited.add(initial_state)
|
|
193
|
+
report("outer_push", initial_state)
|
|
194
|
+
|
|
195
|
+
while outer_stack:
|
|
196
|
+
state = outer_stack[-1]
|
|
197
|
+
unvisited_successors = ts.post(state) - outer_visited
|
|
198
|
+
|
|
199
|
+
if unvisited_successors:
|
|
200
|
+
successor = next(iter(unvisited_successors))
|
|
201
|
+
outer_stack.append(successor)
|
|
202
|
+
outer_visited.add(successor)
|
|
203
|
+
report("outer_push", successor)
|
|
204
|
+
continue
|
|
205
|
+
|
|
206
|
+
popped_state = outer_stack.pop()
|
|
207
|
+
report("outer_pop", popped_state)
|
|
208
|
+
if proposition in ts.labels(state):
|
|
209
|
+
continue
|
|
210
|
+
|
|
211
|
+
cycle = cycle_check(
|
|
212
|
+
ts,
|
|
213
|
+
state,
|
|
214
|
+
inner_visited,
|
|
215
|
+
on_step=lambda operation, inner_state, inner_stack: report(
|
|
216
|
+
operation,
|
|
217
|
+
inner_state,
|
|
218
|
+
inner_stack,
|
|
219
|
+
),
|
|
220
|
+
)
|
|
221
|
+
if cycle is not None:
|
|
222
|
+
return PersistenceResult(
|
|
223
|
+
satisfies=False,
|
|
224
|
+
counterexample=tuple(outer_stack + list(cycle)),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
return PersistenceResult(satisfies=True)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def trace_persistence(
|
|
231
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
232
|
+
proposition: AtomicProposition,
|
|
233
|
+
) -> AlgorithmTrace[PersistenceResult[State], PersistenceStep[State]]:
|
|
234
|
+
"""Run persistence checking and retain every nested-DFS configuration.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
ts: A finite transition system without terminal states.
|
|
238
|
+
proposition: The atomic proposition ``Φ`` that must eventually hold
|
|
239
|
+
forever on every run.
|
|
240
|
+
|
|
241
|
+
Returns:
|
|
242
|
+
The persistence result and snapshots suitable for a worked solution.
|
|
243
|
+
|
|
244
|
+
Raises:
|
|
245
|
+
ValueError: If ``proposition`` is undeclared or ``ts`` has a terminal
|
|
246
|
+
state.
|
|
247
|
+
"""
|
|
248
|
+
steps: list[PersistenceStep[State]] = []
|
|
249
|
+
result = check_persistence(ts, proposition, on_step=steps.append)
|
|
250
|
+
return AlgorithmTrace(result=result, steps=tuple(steps))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
__all__ = [
|
|
254
|
+
"PersistenceResult",
|
|
255
|
+
"PersistenceStep",
|
|
256
|
+
"check_persistence",
|
|
257
|
+
"cycle_check",
|
|
258
|
+
"trace_persistence",
|
|
259
|
+
]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Reachability analysis for transition systems."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Generic, Callable
|
|
5
|
+
|
|
6
|
+
from mocha.algorithms.trace import AlgorithmTrace
|
|
7
|
+
from mocha.models.transition_system import (
|
|
8
|
+
Action,
|
|
9
|
+
AtomicProposition,
|
|
10
|
+
State,
|
|
11
|
+
TransitionSystem,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ReachabilityResult",
|
|
16
|
+
"ReachabilityStep",
|
|
17
|
+
"compute_reachable_states",
|
|
18
|
+
"reduce_to_reachable",
|
|
19
|
+
"trace_reachability",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class ReachabilityResult(Generic[State]):
|
|
25
|
+
"""The fixed-point result of a reachability analysis.
|
|
26
|
+
|
|
27
|
+
Attributes:
|
|
28
|
+
reachable_states: Every state reachable from an initial state,
|
|
29
|
+
including the initial states themselves.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
reachable_states: frozenset[State]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class ReachabilityStep(Generic[State]):
|
|
37
|
+
"""An immutable snapshot of one reachability expansion.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
iteration: Zero for the initial-state snapshot and incremented after
|
|
41
|
+
each expansion that discovers at least one state.
|
|
42
|
+
reachable_states: The states known to be reachable at this iteration.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
iteration: int
|
|
46
|
+
reachable_states: frozenset[State]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def compute_reachable_states(
|
|
50
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
51
|
+
*,
|
|
52
|
+
on_step: Callable[[ReachabilityStep[State]], None] | None = None,
|
|
53
|
+
) -> ReachabilityResult[State]:
|
|
54
|
+
"""Find every state reachable from an initial state.
|
|
55
|
+
|
|
56
|
+
``on_step`` receives an initial snapshot, followed by one snapshot for
|
|
57
|
+
every expansion that discovers new states. The callback is not called for
|
|
58
|
+
the final expansion that reaches the fixed point.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
ts: The transition system to analyse.
|
|
62
|
+
on_step: Optional callback for progress snapshots.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
The complete set of reachable states.
|
|
66
|
+
"""
|
|
67
|
+
reachable_states = set(ts.initial_states)
|
|
68
|
+
iteration = 0
|
|
69
|
+
|
|
70
|
+
if on_step is not None:
|
|
71
|
+
on_step(
|
|
72
|
+
ReachabilityStep(
|
|
73
|
+
iteration=iteration,
|
|
74
|
+
reachable_states=frozenset(reachable_states),
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
while True:
|
|
79
|
+
successors: set[State] = set()
|
|
80
|
+
|
|
81
|
+
for state in reachable_states:
|
|
82
|
+
successors.update(ts.post(state))
|
|
83
|
+
|
|
84
|
+
new_reachable = reachable_states | successors
|
|
85
|
+
|
|
86
|
+
if new_reachable == reachable_states:
|
|
87
|
+
break
|
|
88
|
+
|
|
89
|
+
reachable_states = new_reachable
|
|
90
|
+
iteration += 1
|
|
91
|
+
|
|
92
|
+
if on_step is not None:
|
|
93
|
+
on_step(
|
|
94
|
+
ReachabilityStep(
|
|
95
|
+
iteration=iteration,
|
|
96
|
+
reachable_states=frozenset(reachable_states),
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
return ReachabilityResult(
|
|
101
|
+
reachable_states=frozenset(reachable_states),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def reduce_to_reachable(
|
|
106
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
107
|
+
) -> TransitionSystem[State, Action, AtomicProposition]:
|
|
108
|
+
"""Return a new system containing only states reachable from initial states.
|
|
109
|
+
|
|
110
|
+
Retain their labels, initial-state membership, and transitions between
|
|
111
|
+
them. All declared actions and atomic propositions are preserved.
|
|
112
|
+
With no initial states, the result has no states or transitions.
|
|
113
|
+
The input system is not modified.
|
|
114
|
+
"""
|
|
115
|
+
reachable = compute_reachable_states(ts).reachable_states
|
|
116
|
+
return ts.induced_subsystem(reachable)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def trace_reachability(
|
|
120
|
+
ts: TransitionSystem[State, Action, AtomicProposition],
|
|
121
|
+
) -> AlgorithmTrace[
|
|
122
|
+
ReachabilityResult[State],
|
|
123
|
+
ReachabilityStep[State],
|
|
124
|
+
]:
|
|
125
|
+
"""Run reachability analysis and retain every reported step.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
ts: The transition system to analyse.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
An analysis result together with its initial and expansion snapshots.
|
|
132
|
+
"""
|
|
133
|
+
steps: list[ReachabilityStep[State]] = []
|
|
134
|
+
|
|
135
|
+
result = compute_reachable_states(
|
|
136
|
+
ts,
|
|
137
|
+
on_step=steps.append,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return AlgorithmTrace(
|
|
141
|
+
result=result,
|
|
142
|
+
steps=tuple(steps),
|
|
143
|
+
)
|