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,313 @@
1
+ """Check universal LTL properties through automata and persistence search.
2
+
3
+ The negated property is translated to a Büchi automaton and combined with the
4
+ transition system. A reachable accepting cycle gives an infinite run violating
5
+ the property. Results retain both the automaton product used for the proof and
6
+ the counterexample projected onto the original system's states.
7
+
8
+ Use ``check_ltl(system, property)`` for the verdict and construction results, or
9
+ ``trace_check_ltl`` to retain the detailed steps. Formula interpretation starts
10
+ at the initial state's label. Failed checks return a finite prefix and cycle
11
+ representing an infinite violating path through the original system.
12
+ """
13
+
14
+ import builtins
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+ from enum import Enum
18
+ from typing import Final, Generic, Hashable, Literal, TypeVar, cast
19
+
20
+ from mocha.logic.ltl import LTLFormula, Not, propositions
21
+ from mocha.models.automaton import NBA
22
+ from mocha.models.transition_system import TransitionSystem
23
+
24
+ from .automata import gnba_to_nba, transition_system_automaton_product
25
+ from .ltl_transformations import LTLRewriteStep
26
+ from .persistence import PersistenceResult, PersistenceStep, check_persistence
27
+ from .ltl2gnba.acceptance import AcceptanceStep
28
+ from .ltl2gnba.elementary_set_enumeration import ElementaryTableStep
29
+ from .ltl2gnba.initial_states import InitialStateStep
30
+ from .ltl2gnba.pipeline import LTLToGNBAResult, LTLToGNBAStep, ltl_to_gnba
31
+ from .ltl2gnba.transitions import ElementarySet, TransitionRelationStep, Valuation
32
+ from .trace import AlgorithmTrace
33
+
34
+ State = TypeVar("State", bound=Hashable)
35
+ Action = TypeVar("Action", bound=Hashable)
36
+ NBAState = tuple[ElementarySet, int]
37
+ _ProductState = tuple[State, NBAState]
38
+
39
+ _ModelCheckingStage = Literal[
40
+ "negation", "translation", "nba_conversion", "product", "emptiness", "verdict",
41
+ ]
42
+
43
+
44
+ class _SearchMarker(Enum):
45
+ NONACCEPTING = "nonaccepting"
46
+ SINK_STATE = "sink_state"
47
+ SINK_ACTION = "sink_action"
48
+
49
+
50
+ _SearchState = _ProductState[State] | Literal[_SearchMarker.SINK_STATE]
51
+ _SearchProposition = NBAState | Literal[_SearchMarker.NONACCEPTING]
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class LTLModelCheckingStep(Generic[State]):
56
+ """A globally numbered model-checking event with optional nested details.
57
+
58
+ ``iteration`` counts from zero across all stages, and ``message`` explains
59
+ the event. ``stage`` identifies negation, translation, NBA conversion,
60
+ product construction, emptiness search, or the verdict. ``detail`` is the
61
+ negated formula for negation, an ``LTLToGNBAStep`` for translation, or a
62
+ ``PersistenceStep`` for DFS events; announcements can have no detail.
63
+ Nested events keep their original stage-specific iteration numbers.
64
+ """
65
+
66
+ iteration: int
67
+ stage: _ModelCheckingStage
68
+ message: str
69
+ detail: LTLFormula | LTLToGNBAStep | PersistenceStep[_SearchState[State]] | None = None
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class LTLModelCheckingResult(Generic[State]):
74
+ """A verdict and, when false, a lasso of original transition-system states.
75
+
76
+ ``emptiness`` is the persistence result on the search product.
77
+ ``counterexample`` projects its lasso onto original transition-system
78
+ states, retaining the same ``loop_start``. The prefix before that index
79
+ is followed by the infinitely repeated cycle. ``product_counterexample``
80
+ preserves the NBA components as proof of acceptance. ``counterexample``,
81
+ ``product_counterexample``, and ``loop_start`` are ``None`` when the property
82
+ holds; the construction and emptiness results remain available.
83
+
84
+ Attributes:
85
+ satisfies: Whether every infinite run from an initial state satisfies
86
+ the original ``property``.
87
+ property: Original input property, before negation or normalization.
88
+ negated_formula: Explicit negation of the property before normalization.
89
+ translation: GNBA construction for the negated property.
90
+ nba: Equivalent NBA recognizing words that violate the property.
91
+ product: Product of the system, projected to the property's proposition
92
+ names, and the NBA. States pair an original state with an NBA state.
93
+ search_product: Separate product copy with non-accepting states marked
94
+ and any dead ends completed by a non-accepting sink for DFS.
95
+ emptiness: Persistence-search result whose verdict matches ``satisfies``.
96
+ counterexample: Original-state lasso with its final state repeating the
97
+ state at ``loop_start``, or ``None`` when the property holds.
98
+ loop_start: Zero-based start of the repeating cycle, or ``None``.
99
+
100
+ To recover the infinite state path, take ``counterexample[:loop_start]``
101
+ once and repeat ``counterexample[loop_start:-1]`` forever. The last entry
102
+ closes the loop and is not an additional cycle position. Apply the system's
103
+ labels to those states to obtain the violating word, starting with the
104
+ initial state's label. Although the result is frozen, its stored automaton
105
+ and transition systems remain mutable.
106
+ """
107
+
108
+ satisfies: bool
109
+ property: LTLFormula
110
+ negated_formula: LTLFormula
111
+ translation: LTLToGNBAResult
112
+ nba: NBA[NBAState, Valuation]
113
+ product: TransitionSystem[_ProductState[State], Hashable, NBAState]
114
+ search_product: TransitionSystem[_SearchState[State], Hashable, _SearchProposition]
115
+ emptiness: PersistenceResult[_SearchState[State]]
116
+ counterexample: tuple[State, ...] | None
117
+ loop_start: int | None
118
+
119
+ @builtins.property
120
+ def product_counterexample(self) -> tuple[_ProductState[State], ...] | None:
121
+ """The accepting product lasso before projection, or ``None`` if satisfied.
122
+
123
+ Each state pairs an original system state with an NBA state. The last
124
+ entry repeats the product state at ``loop_start``; projecting the first
125
+ component gives ``counterexample`` with the same cycle boundary.
126
+ """
127
+ # The non-accepting sink only loops on itself and cannot occur in a
128
+ # violating persistence lasso, so every entry is an ordinary product state.
129
+ return cast(tuple[_ProductState[State], ...] | None, self.emptiness.counterexample)
130
+
131
+
132
+ def check_ltl(
133
+ system: TransitionSystem[State, Action, str],
134
+ property: LTLFormula,
135
+ *,
136
+ on_step: Callable[[LTLModelCheckingStep[State]], None] | None = None,
137
+ ) -> LTLModelCheckingResult[State]:
138
+ """Check whether every infinite run of ``system`` satisfies ``property``.
139
+
140
+ The pipeline explicitly constructs the negation of ``property``, translates that formula to
141
+ a GNBA, converts it to an NBA, forms the standard product, and uses
142
+ ``check_persistence`` to detect a reachable accepting cycle. A cycle gives a
143
+ counterexample to the original property. The system must be non-blocking
144
+ and its proposition names must be strings. Formula names must be declared
145
+ in the system.
146
+
147
+ The product sees only propositions in the formula. Projecting the system's
148
+ labels onto these names makes the NBA alphabet exactly 2^AP while leaving
149
+ the original states, actions, transitions, and initial states unchanged.
150
+
151
+ Formula evaluation begins at the initial state's label: an atomic formula
152
+ concerns that state, while NEXT concerns its successor. The returned
153
+ counterexample contains system states, with a repeated final endpoint and
154
+ a zero-based loop index as documented by ``LTLModelCheckingResult``. The
155
+ chosen counterexample need not be shortest or unique.
156
+
157
+ Args:
158
+ system: Transition system with string proposition names and no terminal
159
+ states, including among unreachable states. It is not modified.
160
+ property: LTL formula interpreted from the first state of each initial
161
+ run. Derived operators are normalized automatically. Every formula
162
+ proposition must be declared in ``system.atomic_propositions``.
163
+ on_step: Optional synchronous callback receiving globally numbered
164
+ events from negation through the verdict, including nested
165
+ translation details and persistence DFS snapshots.
166
+
167
+ Returns:
168
+ The verdict and construction results. A failed property includes an
169
+ original-state counterexample lasso and its zero-based loop boundary.
170
+ With no initial runs, the property holds vacuously.
171
+
172
+ Raises:
173
+ TypeError: If a declared system proposition name is not a string.
174
+ ValueError: If the formula uses an undeclared proposition or the system
175
+ contains a terminal state.
176
+ """
177
+ if any(not isinstance(name, str) for name in system.atomic_propositions):
178
+ raise TypeError("LTL model checking requires string atomic proposition names")
179
+ used = propositions(property)
180
+ undeclared = used - system.atomic_propositions
181
+ if undeclared:
182
+ raise ValueError(f"Unknown atomic propositions: {sorted(undeclared)!r}")
183
+ if not system.is_non_blocking():
184
+ raise ValueError("LTL model checking requires a transition system without terminal states")
185
+
186
+ iteration = 0
187
+
188
+ def report(
189
+ stage: _ModelCheckingStage,
190
+ message: str,
191
+ detail: LTLFormula | LTLToGNBAStep | PersistenceStep[_SearchState[State]] | None = None,
192
+ ) -> None:
193
+ nonlocal iteration
194
+ if on_step is not None:
195
+ on_step(LTLModelCheckingStep(iteration, stage, message, detail))
196
+ iteration += 1
197
+
198
+ negated = Not(property)
199
+ report("negation", f"Negate the property: ¬({property}) = {negated}.", negated)
200
+
201
+ def describe_translation(step: LTLToGNBAStep) -> str:
202
+ detail = step.detail
203
+ if isinstance(detail, LTLRewriteStep):
204
+ return f"Normalize ({detail.rule}): {detail.formula}."
205
+ if isinstance(detail, ElementaryTableStep):
206
+ return f"Elementary sets ({detail.rule}): {detail.message} ({len(detail.table.rows)} rows.)"
207
+ if isinstance(detail, InitialStateStep):
208
+ return detail.message
209
+ if isinstance(detail, TransitionRelationStep):
210
+ names = ", ".join(f"B{i + 1}" for i in sorted(detail.targets))
211
+ symbol = "{" + ", ".join(sorted(detail.input)) + "}" if detail.input else "∅"
212
+ return f"Transitions from B{detail.source_index + 1} on {symbol}: {{{names}}}."
213
+ if isinstance(detail, AcceptanceStep):
214
+ if detail.condition is None:
215
+ return detail.message
216
+ names = ", ".join(f"B{i + 1}" for i in sorted(detail.condition.state_indices))
217
+ return f"Acceptance for ({detail.condition.formula}): {{{names}}}."
218
+ return f"GNBA translation: {step.stage}."
219
+
220
+ translation = ltl_to_gnba(
221
+ negated, on_step=lambda step: report("translation", describe_translation(step), step)
222
+ )
223
+ nba = gnba_to_nba(translation.automaton)
224
+ report("nba_conversion", f"Convert the GNBA to an NBA with {len(nba.states)} states.")
225
+ projected = TransitionSystem[State, Hashable, str].from_components(
226
+ states=system.states,
227
+ actions=system.actions,
228
+ transitions=system.transitions(),
229
+ initial_states=system.initial_states,
230
+ atomic_propositions=used,
231
+ labels={state: system.labels(state) & used for state in system.states},
232
+ )
233
+ product = transition_system_automaton_product(projected, nba)
234
+ report("product", f"Build the product after projecting labels onto {sorted(used)!r}; "
235
+ f"it has {len(product.states)} states and {len(product.initial_states)} initial states.")
236
+ state_numbers = {state: index + 1 for index, state in enumerate(translation.elementary_sets.elementary_sets)}
237
+
238
+ # Persistence checks for a cycle outside Φ. Let Φ hold precisely at the
239
+ # non-accepting product states; a violation is an accepting cycle. The
240
+ # standard product can have dead ends even when the original TS is total.
241
+ # Complete those ends with a non-accepting sink for the persistence search.
242
+ nonaccepting: Final = _SearchMarker.NONACCEPTING
243
+ sink: Final = _SearchMarker.SINK_STATE
244
+ sink_action: Final = _SearchMarker.SINK_ACTION
245
+ search_product = TransitionSystem[
246
+ _SearchState[State], Hashable, _SearchProposition,
247
+ ].from_components(
248
+ states=product.states, actions=product.actions,
249
+ transitions=product.transitions(), initial_states=product.initial_states,
250
+ atomic_propositions=(*product.atomic_propositions, nonaccepting),
251
+ labels={state: (*product.labels(state), nonaccepting)
252
+ if state[1] not in nba.accepting_states else product.labels(state)
253
+ for state in product.states},
254
+ )
255
+ terminal = product.terminal_states
256
+ if terminal:
257
+ search_product.add_state(sink, labels={nonaccepting})
258
+ for state in terminal:
259
+ search_product.add_transition(state, sink_action, sink)
260
+ search_product.add_transition(sink, sink_action, sink)
261
+ report("emptiness", "Mark non-accepting product states with Φ and use the persistence "
262
+ "nested DFS to find a cycle outside Φ. Complete dead ends with a non-accepting sink.")
263
+
264
+ def describe_emptiness(step: PersistenceStep[_SearchState[State]]) -> str:
265
+ if step.state is None:
266
+ return "Initialize persistence nested DFS on the prepared product."
267
+ if step.state is sink:
268
+ label = "the non-accepting sink"
269
+ else:
270
+ ts_state, (elementary, counter) = step.state
271
+ label = f"({ts_state!r}, B{state_numbers[elementary]}, round {counter})"
272
+ if step.operation == "cycle_found":
273
+ return f"Inner DFS found an accepting cycle through {label}."
274
+ return f"{step.operation.replace('_', ' ').capitalize()} at {label}."
275
+
276
+ emptiness = check_persistence(
277
+ search_product, nonaccepting,
278
+ on_step=(
279
+ (lambda step: report("emptiness", describe_emptiness(step), step))
280
+ if on_step is not None else None
281
+ ),
282
+ )
283
+ # As in product_counterexample, the accepting lasso cannot visit the sink.
284
+ product_counterexample = cast(tuple[_ProductState[State], ...] | None, emptiness.counterexample)
285
+ counterexample = (
286
+ tuple(state for state, _ in product_counterexample)
287
+ if product_counterexample is not None else None
288
+ )
289
+ satisfies = emptiness.satisfies
290
+ verdict = "holds" if satisfies else "fails; the accepting product cycle gives a counterexample"
291
+ report("verdict", f"The LTL property {verdict}.")
292
+ return LTLModelCheckingResult(
293
+ satisfies, property, negated, translation, nba, product, search_product,
294
+ emptiness, counterexample, emptiness.loop_start,
295
+ )
296
+
297
+
298
+ def trace_check_ltl(
299
+ system: TransitionSystem[State, Action, str], property: LTLFormula,
300
+ ) -> AlgorithmTrace[LTLModelCheckingResult[State], LTLModelCheckingStep[State]]:
301
+ """Check the property and retain every construction and search event in memory.
302
+
303
+ Inputs and validation requirements match ``check_ltl``. The trace's
304
+ ``result`` contains the verdict and optional counterexample; ``steps``
305
+ collects the callback events in global order, retaining the detailed
306
+ translation records and persistence DFS snapshots.
307
+ """
308
+ steps: list[LTLModelCheckingStep[State]] = []
309
+ result = check_ltl(system, property, on_step=steps.append)
310
+ return AlgorithmTrace(result, tuple(steps))
311
+
312
+
313
+ __all__ = ["LTLModelCheckingResult", "LTLModelCheckingStep", "check_ltl", "trace_check_ltl"]
@@ -0,0 +1,308 @@
1
+ """Check LTL satisfiability and validity using Büchi automaton emptiness.
2
+
3
+ Satisfiability asks whether some infinite valuation word satisfies a formula;
4
+ validity asks whether every such word does. Both checks normalize formulas
5
+ during translation and expose construction and search details through optional
6
+ callbacks. Satisfying words and validity counterexamples use a finite prefix
7
+ followed by an infinitely repeated nonempty loop.
8
+ """
9
+
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from enum import Enum
13
+ from typing import Final, Literal, cast
14
+
15
+ from mocha.algorithms.trace import AlgorithmTrace
16
+ from mocha.logic.ltl import LTLFormula, Not
17
+ from mocha.models.automaton import NBA
18
+ from mocha.models.transition_system import TransitionSystem
19
+
20
+ from .automata import gnba_to_nba
21
+ from .ltl2gnba.pipeline import LTLToGNBAResult, LTLToGNBAStep, ltl_to_gnba
22
+ from .ltl2gnba.transitions import ElementarySet, Valuation
23
+ from .persistence import PersistenceResult, PersistenceStep, check_persistence
24
+
25
+ NBAState = tuple[ElementarySet, int]
26
+
27
+ _SatisfiabilityStage = Literal["translation", "nba_conversion", "emptiness", "verdict"]
28
+ _ValidityStage = Literal["negation", "satisfiability", "verdict"]
29
+
30
+
31
+ class _SearchMarker(Enum):
32
+ NONACCEPTING = "nonaccepting"
33
+ SINK_STATE = "sink_state"
34
+ SINK_ACTION = "sink_action"
35
+
36
+
37
+ _SearchState = NBAState | Literal[_SearchMarker.SINK_STATE]
38
+ _SearchAction = Valuation | Literal[_SearchMarker.SINK_ACTION]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class LTLSatisfiabilityStep:
43
+ """A stage of Algorithm 12 in *Principles of Model Checking*, retaining the detailed translation or DFS step.
44
+
45
+ ``iteration`` is zero-based across the whole check. ``stage`` distinguishes
46
+ GNBA translation, NBA conversion, emptiness search, and the final verdict;
47
+ ``message`` explains the event. ``detail`` retains an ``LTLToGNBAStep`` for
48
+ translation events or a ``PersistenceStep`` for DFS events, and is ``None``
49
+ for stage announcements without a detailed event.
50
+ """
51
+
52
+ iteration: int
53
+ stage: _SatisfiabilityStage
54
+ message: str
55
+ detail: LTLToGNBAStep | PersistenceStep[_SearchState] | None = None
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class LTLSatisfiabilityResult:
60
+ """An NBA emptiness verdict and, if satisfiable, an accepted lasso.
61
+
62
+ ``run`` ends by repeating the state at ``loop_start``. ``witness`` has one
63
+ valuation for each transition in the run. Thus the infinite word is
64
+ ``witness[:loop_start]`` followed by ``witness[loop_start:]`` forever.
65
+
66
+ Attributes:
67
+ satisfiable: Whether at least one infinite word satisfies the formula.
68
+ formula: Original input, before translation normalizes it.
69
+ translation: GNBA construction, including the normalized formula.
70
+ nba: Equivalent NBA with states (elementary set, acceptance round).
71
+ search_system: NBA transition graph prepared for persistence search,
72
+ with non-accepting states marked and dead ends completed by a sink.
73
+ emptiness: Persistence result; ``satisfies`` is true exactly when the
74
+ NBA language is empty, the opposite of ``satisfiable``.
75
+ run: Accepting NBA lasso, including its repeated final state.
76
+ witness: Valuation word labelling the run, excluding any extra letter
77
+ for the repeated endpoint. Each valuation is a set of true names.
78
+ loop_start: Zero-based start of the repeating portion in run and word.
79
+
80
+ ``run``, ``witness``, and ``loop_start`` are all ``None`` when unsatisfiable.
81
+ The result is frozen, but its automaton and transition system are mutable.
82
+ """
83
+
84
+ satisfiable: bool
85
+ formula: LTLFormula
86
+ translation: LTLToGNBAResult
87
+ nba: NBA[NBAState, Valuation]
88
+ search_system: TransitionSystem[_SearchState, _SearchAction, _SearchMarker]
89
+ emptiness: PersistenceResult[_SearchState]
90
+ run: tuple[NBAState, ...] | None
91
+ witness: tuple[Valuation, ...] | None
92
+ loop_start: int | None
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class LTLValidityStep:
97
+ """A negation, satisfiability, or verdict step of validity checking.
98
+
99
+ ``iteration`` counts from zero across the validity check, and ``message``
100
+ explains the event. ``detail`` is the negated formula for ``negation``, a
101
+ nested ``LTLSatisfiabilityStep`` for ``satisfiability``, or ``None`` for the
102
+ final ``verdict``. Nested steps retain their own iteration numbers.
103
+ """
104
+
105
+ iteration: int
106
+ stage: _ValidityStage
107
+ message: str
108
+ detail: LTLFormula | LTLSatisfiabilityStep | None = None
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class LTLValidityResult:
113
+ """Validity of a formula, with a word falsifying it when it is invalid.
114
+
115
+ ``valid`` means that every infinite valuation word satisfies ``formula``.
116
+ ``negated_formula`` is its explicit negation before normalization, and
117
+ ``satisfiability`` contains the check of that negation. Its satisfying
118
+ witness, exposed as ``counterexample``, falsifies the original formula.
119
+ The counterexample and ``loop_start`` are ``None`` when the formula is valid.
120
+ """
121
+
122
+ valid: bool
123
+ formula: LTLFormula
124
+ negated_formula: LTLFormula
125
+ satisfiability: LTLSatisfiabilityResult
126
+
127
+ @property
128
+ def counterexample(self) -> tuple[Valuation, ...] | None:
129
+ """A falsifying word whose suffix from ``loop_start`` repeats forever."""
130
+ return self.satisfiability.witness
131
+
132
+ @property
133
+ def loop_start(self) -> int | None:
134
+ """Zero-based start of the counterexample's loop, or ``None`` if valid."""
135
+ return self.satisfiability.loop_start
136
+
137
+
138
+ def check_ltl_satisfiability(
139
+ formula: LTLFormula,
140
+ *,
141
+ on_step: Callable[[LTLSatisfiabilityStep], None] | None = None,
142
+ ) -> LTLSatisfiabilityResult:
143
+ """Apply Algorithm 12 from *Principles of Model Checking* to ``formula``.
144
+
145
+ Translate the formula to an NBA and test for a reachable accepting cycle.
146
+ The existing persistence nested DFS finds such a cycle when its proposition
147
+ marks precisely the non-accepting states. Dead ends lead to a non-accepting
148
+ sink so that the search system remains non-blocking.
149
+
150
+ Args:
151
+ formula: LTL formula to test. Translation normalizes derived operators
152
+ automatically; no transition system or declared alphabet is needed.
153
+ on_step: Optional synchronous callback receiving globally numbered
154
+ translation events, conversion and search announcements, detailed
155
+ persistence DFS events, and the final verdict.
156
+
157
+ Returns:
158
+ The construction and emptiness results, plus an accepted NBA run and
159
+ valuation word when satisfiable. The alphabet is the powerset of the
160
+ formula's proposition names. ``loop_start`` identifies the nonempty
161
+ repeating suffix of the finite witness word.
162
+ """
163
+ iteration = 0
164
+
165
+ def report(
166
+ stage: _SatisfiabilityStage,
167
+ message: str,
168
+ detail: LTLToGNBAStep | PersistenceStep[_SearchState] | None = None,
169
+ ) -> None:
170
+ nonlocal iteration
171
+ if on_step is not None:
172
+ on_step(LTLSatisfiabilityStep(iteration, stage, message, detail))
173
+ iteration += 1
174
+
175
+ translation = ltl_to_gnba(
176
+ formula,
177
+ on_step=lambda step: report("translation", f"GNBA translation: {step.stage}.", step),
178
+ )
179
+ nba = gnba_to_nba(translation.automaton)
180
+ report("nba_conversion", f"Convert the GNBA to an NBA with {len(nba.states)} states.")
181
+
182
+ nonaccepting: Final = _SearchMarker.NONACCEPTING
183
+ sink: Final = _SearchMarker.SINK_STATE
184
+ sink_action: Final = _SearchMarker.SINK_ACTION
185
+ search_system = TransitionSystem[_SearchState, _SearchAction, _SearchMarker].from_components(
186
+ states=nba.states,
187
+ actions=nba.alphabet,
188
+ transitions=((edge.source, edge.symbol, edge.target) for edge in nba.transitions()),
189
+ initial_states=nba.initial_states,
190
+ atomic_propositions={nonaccepting},
191
+ labels={state: {nonaccepting} if state not in nba.accepting_states else set()
192
+ for state in nba.states},
193
+ )
194
+ terminal_states = search_system.terminal_states
195
+ if terminal_states:
196
+ search_system.add_state(sink, labels={nonaccepting})
197
+ search_system.add_transition(sink, sink_action, sink)
198
+ for state in terminal_states:
199
+ search_system.add_transition(state, sink_action, sink)
200
+ report("emptiness", "Search for a reachable accepting cycle with persistence nested DFS.")
201
+ emptiness = check_persistence(
202
+ search_system,
203
+ nonaccepting,
204
+ on_step=(
205
+ (lambda step: report("emptiness", step.operation.replace("_", " ").capitalize(), step))
206
+ if on_step is not None else None
207
+ ),
208
+ )
209
+
210
+ # The non-accepting sink only loops on itself, so an accepting lasso
211
+ # cannot visit it. The cast records this invariant without changing the run.
212
+ run = cast(tuple[NBAState, ...] | None, emptiness.counterexample)
213
+ if run is None:
214
+ witness = None
215
+ loop_start = None
216
+ else:
217
+ ordered_alphabet = sorted(nba.alphabet, key=lambda value: tuple(sorted(value)))
218
+ witness = tuple(
219
+ next(symbol for symbol in ordered_alphabet if target in nba.post(source, symbol))
220
+ for source, target in zip(run, run[1:])
221
+ )
222
+ loop_start = max(index for index, state in enumerate(run[:-1]) if state == run[-1])
223
+ satisfiable = not emptiness.satisfies
224
+ report("verdict", "The formula is satisfiable." if satisfiable else "The formula is unsatisfiable.")
225
+ return LTLSatisfiabilityResult(
226
+ satisfiable, formula, translation, nba, search_system, emptiness,
227
+ run, witness, loop_start,
228
+ )
229
+
230
+
231
+ def trace_ltl_satisfiability(
232
+ formula: LTLFormula,
233
+ ) -> AlgorithmTrace[LTLSatisfiabilityResult, LTLSatisfiabilityStep]:
234
+ """Check satisfiability and retain all translation and search callback events.
235
+
236
+ Accepts the same formulas as ``check_ltl_satisfiability``. ``result`` contains
237
+ the verdict and optional witness, and ``steps`` holds the complete ordered
238
+ trace, including detailed persistence DFS snapshots, in memory.
239
+ """
240
+ steps: list[LTLSatisfiabilityStep] = []
241
+ result = check_ltl_satisfiability(formula, on_step=steps.append)
242
+ return AlgorithmTrace(result, tuple(steps))
243
+
244
+
245
+ def check_ltl_validity(
246
+ formula: LTLFormula,
247
+ *,
248
+ on_step: Callable[[LTLValidityStep], None] | None = None,
249
+ ) -> LTLValidityResult:
250
+ """Check validity by testing whether the negated formula is unsatisfiable.
251
+
252
+ Args:
253
+ formula: LTL formula that should hold on every infinite valuation word.
254
+ Its explicit negation is normalized during satisfiability checking.
255
+ on_step: Optional synchronous callback receiving the initial negation,
256
+ wrapped satisfiability events, and the final verdict, with one
257
+ global zero-based sequence across all these events.
258
+
259
+ Returns:
260
+ The validity verdict and the satisfiability result for the negation.
261
+ If invalid, ``counterexample`` gives a valuation word falsifying the
262
+ input; its suffix starting at ``loop_start`` repeats infinitely.
263
+ """
264
+ iteration = 0
265
+
266
+ def report(
267
+ stage: _ValidityStage,
268
+ message: str,
269
+ detail: LTLFormula | LTLSatisfiabilityStep | None = None,
270
+ ) -> None:
271
+ nonlocal iteration
272
+ if on_step is not None:
273
+ on_step(LTLValidityStep(iteration, stage, message, detail))
274
+ iteration += 1
275
+
276
+ negated = Not(formula)
277
+ report("negation", f"Negate the formula: {negated}.", negated)
278
+ satisfiability = check_ltl_satisfiability(
279
+ negated,
280
+ on_step=(
281
+ (lambda step: report("satisfiability", step.message, step))
282
+ if on_step is not None else None
283
+ ),
284
+ )
285
+ valid = not satisfiability.satisfiable
286
+ report("verdict", "The formula is valid." if valid else "The formula is not valid.")
287
+ return LTLValidityResult(valid, formula, negated, satisfiability)
288
+
289
+
290
+ def trace_ltl_validity(
291
+ formula: LTLFormula,
292
+ ) -> AlgorithmTrace[LTLValidityResult, LTLValidityStep]:
293
+ """Check validity and retain the negation, satisfiability, and verdict events.
294
+
295
+ ``result`` is the verdict from ``check_ltl_validity``; ``steps`` retains all
296
+ callback events in global order, including nested translation and search
297
+ details from the satisfiability check of the negated formula.
298
+ """
299
+ steps: list[LTLValidityStep] = []
300
+ result = check_ltl_validity(formula, on_step=steps.append)
301
+ return AlgorithmTrace(result, tuple(steps))
302
+
303
+
304
+ __all__ = [
305
+ "LTLSatisfiabilityResult", "LTLSatisfiabilityStep", "LTLValidityResult", "LTLValidityStep",
306
+ "check_ltl_satisfiability", "check_ltl_validity",
307
+ "trace_ltl_satisfiability", "trace_ltl_validity",
308
+ ]