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,166 @@
1
+ """Invariant checking for labelled transition systems."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Generic, Iterable, 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
+ "InvariantResult",
16
+ "InvariantStep",
17
+ "check_invariant",
18
+ "trace_invariant",
19
+ ]
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class InvariantResult(Generic[State]):
24
+ """The result of checking an invariant over reachable states.
25
+
26
+ Attributes:
27
+ satisfies: Whether every reachable state belongs to the requested
28
+ invariant set.
29
+ counterexample: A path from an initial state to a violating state, or
30
+ ``None`` when ``satisfies`` is true.
31
+ """
32
+
33
+ satisfies: bool
34
+ counterexample: tuple[State, ...] | None = None
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class InvariantStep(Generic[State]):
39
+ """An immutable snapshot produced while checking an invariant.
40
+
41
+ Attributes:
42
+ current_state: The reachable state currently being checked.
43
+ visited: All states examined through and including ``current_state``.
44
+ satisfies_invariant: Whether ``current_state`` belongs to the
45
+ invariant set.
46
+ """
47
+
48
+ current_state: State
49
+ visited: frozenset[State]
50
+ satisfies_invariant: bool
51
+
52
+ def check_invariant(
53
+ ts: TransitionSystem[State, Action, AtomicProposition],
54
+ invariant_states: Iterable[State],
55
+ *,
56
+ on_step: Callable[[InvariantStep[State]], None] | None = None,
57
+ ) -> InvariantResult[State]:
58
+ """Check that every reachable state belongs to an invariant set.
59
+
60
+ Exploration starts from all initial states. If a reachable state is absent
61
+ from ``invariant_states``, the result includes a path from an initial state
62
+ to that state. Unreachable states do not affect the result.
63
+
64
+ Args:
65
+ ts: The transition system to analyse.
66
+ invariant_states: States in which the invariant holds.
67
+ on_step: Optional callback invoked for each examined reachable state.
68
+
69
+ Returns:
70
+ A successful result, or a counterexample path to the first violating
71
+ state encountered.
72
+
73
+ Raises:
74
+ ValueError: If ``invariant_states`` contains a state outside ``ts``.
75
+ """
76
+ invariant_states = set(invariant_states)
77
+
78
+ unknown = invariant_states - ts.states
79
+ if unknown:
80
+ raise ValueError(
81
+ f"Invariant contains unknown states: {unknown!r}"
82
+ )
83
+
84
+ visited: set[State] = set()
85
+ initial_states = ts.initial_states
86
+ to_explore: list[State] = list(initial_states)
87
+
88
+ predecessor: dict[State, State] = {
89
+ state: state
90
+ for state in initial_states
91
+ }
92
+
93
+ while to_explore:
94
+ state = to_explore.pop()
95
+
96
+ if state in visited:
97
+ continue
98
+
99
+ visited.add(state)
100
+
101
+ satisfies = state in invariant_states
102
+
103
+ if on_step is not None:
104
+ on_step(
105
+ InvariantStep(
106
+ current_state=state,
107
+ visited=frozenset(visited),
108
+ satisfies_invariant=satisfies,
109
+ )
110
+ )
111
+
112
+ if not satisfies:
113
+ path: list[State] = [state]
114
+ current = state
115
+
116
+ while current not in initial_states:
117
+ current = predecessor[current]
118
+ path.append(current)
119
+
120
+ path.reverse()
121
+
122
+ return InvariantResult(
123
+ satisfies=False,
124
+ counterexample=tuple(path),
125
+ )
126
+
127
+ for successor in ts.post(state):
128
+ if successor not in visited and successor not in predecessor:
129
+ predecessor[successor] = state
130
+ to_explore.append(successor)
131
+
132
+ return InvariantResult(
133
+ satisfies=True,
134
+ )
135
+
136
+ def trace_invariant(
137
+ ts: TransitionSystem[State, Action, AtomicProposition],
138
+ invariant_states: Iterable[State],
139
+ ) -> AlgorithmTrace[
140
+ InvariantResult[State],
141
+ InvariantStep[State],
142
+ ]:
143
+ """Run invariant checking and retain every exploration step.
144
+
145
+ Args:
146
+ ts: The transition system to analyse.
147
+ invariant_states: States in which the invariant holds.
148
+
149
+ Returns:
150
+ The invariant result and one snapshot per examined state.
151
+
152
+ Raises:
153
+ ValueError: If ``invariant_states`` contains a state outside ``ts``.
154
+ """
155
+ steps: list[InvariantStep[State]] = []
156
+
157
+ result = check_invariant(
158
+ ts,
159
+ invariant_states,
160
+ on_step=steps.append,
161
+ )
162
+
163
+ return AlgorithmTrace(
164
+ result=result,
165
+ steps=tuple(steps),
166
+ )
@@ -0,0 +1,75 @@
1
+ """Educational stages of LTL-to-GNBA translation and their traceable results.
2
+
3
+ Use ``ltl_to_gnba`` for automatic normalization and the complete construction,
4
+ or call the elementary-set, initial-state, transition, and acceptance stages
5
+ individually. Elementary-set checking and enumeration require an already
6
+ normalized formula. Initial-state, transition, and acceptance construction each
7
+ take that formula and an explicit collection of elementary sets in the caller's
8
+ chosen order, without requiring an enumeration or another stage's result.
9
+ ``trace_*`` helpers collect the corresponding callback events in an
10
+ ``AlgorithmTrace`` with a final result and an ordered tuple of steps.
11
+
12
+ ``check_elementary_set_collection`` separately checks a computed solution for
13
+ invalid states, duplicates, and omissions. It recomputes the full enumeration;
14
+ component construction only validates individual states and duplicates.
15
+ """
16
+
17
+ from .acceptance import (
18
+ AcceptanceCondition, AcceptanceDecision, AcceptanceResult, AcceptanceStep,
19
+ compute_acceptance_sets, trace_acceptance_sets,
20
+ )
21
+ from .initial_states import (
22
+ InitialStateStep, InitialStatesResult, compute_initial_states, trace_initial_states,
23
+ )
24
+ from .pipeline import LTLToGNBAResult, LTLToGNBAStep, ltl_to_gnba, trace_ltl_to_gnba
25
+ from .elementary_set_validation import (
26
+ ElementarySetResult,
27
+ ElementarySetViolation,
28
+ check_elementary_set,
29
+ ElementarySetCollectionResult,
30
+ check_elementary_set_collection,
31
+ validate_elementary_set_collection,
32
+ )
33
+ from .elementary_set_enumeration import (
34
+ ElementarySetEnumeration,
35
+ ElementaryTable,
36
+ ElementaryTableChange,
37
+ ElementaryTableRow,
38
+ ElementaryTableStep,
39
+ enumerate_elementary_sets,
40
+ trace_elementary_sets,
41
+ )
42
+ from .transitions import (
43
+ TransitionRestriction,
44
+ TransitionRelationResult,
45
+ TransitionRelationStep,
46
+ TransitionRelationTable,
47
+ compute_transition_relation,
48
+ trace_transition_relation,
49
+ )
50
+
51
+ __all__ = [
52
+ "AcceptanceCondition", "AcceptanceDecision", "AcceptanceResult", "AcceptanceStep",
53
+ "compute_acceptance_sets", "trace_acceptance_sets",
54
+ "InitialStateStep", "InitialStatesResult", "compute_initial_states", "trace_initial_states",
55
+ "LTLToGNBAResult", "LTLToGNBAStep", "ltl_to_gnba", "trace_ltl_to_gnba",
56
+ "TransitionRestriction",
57
+ "TransitionRelationResult",
58
+ "TransitionRelationStep",
59
+ "TransitionRelationTable",
60
+ "compute_transition_relation",
61
+ "trace_transition_relation",
62
+ "ElementarySetEnumeration",
63
+ "ElementarySetResult",
64
+ "ElementarySetViolation",
65
+ "ElementaryTable",
66
+ "ElementaryTableChange",
67
+ "ElementaryTableRow",
68
+ "ElementaryTableStep",
69
+ "check_elementary_set",
70
+ "ElementarySetCollectionResult",
71
+ "check_elementary_set_collection",
72
+ "validate_elementary_set_collection",
73
+ "enumerate_elementary_sets",
74
+ "trace_elementary_sets",
75
+ ]
@@ -0,0 +1,199 @@
1
+ """Build generalized Büchi acceptance sets that discharge UNTIL obligations.
2
+
3
+ Local elementary-set and transition rules can keep an UNTIL obligation pending
4
+ forever. One acceptance set per UNTIL formula rules out such runs by requiring
5
+ infinitely many states where the obligation is absent or its right operand
6
+ holds. Decisions retain the supplied state order for explanations.
7
+ """
8
+
9
+ from collections.abc import Callable, Iterable
10
+ from dataclasses import dataclass
11
+ from typing import Literal
12
+
13
+ from mocha.logic.ltl import LTLFormula, Until
14
+
15
+ from ..trace import AlgorithmTrace
16
+ from .elementary_set_validation import _validate_elementary_sets
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class AcceptanceDecision:
21
+ """Explain one state's membership in a particular UNTIL acceptance set.
22
+
23
+ ``state_index`` is the zero-based position of ``state`` in the supplied
24
+ collection; display labels add one to obtain B1, B2, etc. ``included`` says
25
+ whether the state belongs to this acceptance set. ``reason`` distinguishes
26
+ an absent obligation (``until_absent``), a fulfilled obligation
27
+ (``right_present``), and an unfulfilled obligation (``until_pending``).
28
+ ``message`` provides the corresponding explanation for display.
29
+ """
30
+
31
+ state_index: int
32
+ state: frozenset[LTLFormula]
33
+ included: bool
34
+ reason: Literal["until_absent", "right_present", "until_pending"]
35
+ message: str
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class AcceptanceCondition:
40
+ """The generalized Büchi set associated with one ``formula`` of form ψ U χ.
41
+
42
+ ``accepting_states`` contains exactly the elementary sets B for which
43
+ ψ U χ is absent or χ is present. ``state_indices`` identifies those same
44
+ states by their zero-based positions in the supplied collection. An
45
+ accepting infinite run must visit this set infinitely often.
46
+ """
47
+
48
+ formula: Until
49
+ accepting_states: frozenset[frozenset[LTLFormula]]
50
+ state_indices: frozenset[int]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class AcceptanceStep:
55
+ """One UNTIL acceptance set, with a decision for every elementary set.
56
+
57
+ If no UNTIL occurs, a single explanatory step has ``condition=None``.
58
+ Its ``decisions`` tuple is empty. Otherwise, decisions follow the original
59
+ elementary-set order and ``condition`` contains the resulting acceptance
60
+ set. ``iteration`` is zero-based, following UNTIL formulas sorted by their
61
+ string representations; ``message`` explains the membership rule.
62
+ """
63
+
64
+ iteration: int
65
+ condition: AcceptanceCondition | None
66
+ decisions: tuple[AcceptanceDecision, ...]
67
+ message: str
68
+
69
+ def to_markdown(self) -> str:
70
+ """Render the rule, per-state decisions, and resulting set using B labels.
71
+
72
+ An empty acceptance set is rendered as ``F = {}``. The no-UNTIL step
73
+ instead renders only its explanation, since it defines no set.
74
+ """
75
+ lines = [self.message, ""]
76
+ lines.extend(f"- {decision.message}" for decision in self.decisions)
77
+ if self.condition is not None:
78
+ names = ", ".join(f"B{i + 1}" for i in sorted(self.condition.state_indices))
79
+ lines.extend(["", f"F = {{{names}}}."])
80
+ return "\n".join(lines).rstrip()
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class AcceptanceResult:
85
+ """Retain the ordered acceptance conditions and expose their GNBA family.
86
+
87
+ ``conditions`` has one entry per UNTIL formula, sorted by formula string,
88
+ even when several entries have identical accepting states. With no UNTIL
89
+ formulas it is empty. ``accepting_sets`` deduplicates equal state sets for
90
+ use in the automaton without losing the per-formula explanations here.
91
+ """
92
+
93
+ conditions: tuple[AcceptanceCondition, ...]
94
+
95
+ @property
96
+ def accepting_sets(self) -> frozenset[frozenset[frozenset[LTLFormula]]]:
97
+ """Return the distinct acceptance sets, preserving any empty member set."""
98
+ return frozenset(condition.accepting_states for condition in self.conditions)
99
+
100
+
101
+ def compute_acceptance_sets(
102
+ formula: LTLFormula,
103
+ elementary_sets: Iterable[Iterable[LTLFormula]],
104
+ *,
105
+ on_step: Callable[[AcceptanceStep], None] | None = None,
106
+ ) -> AcceptanceResult:
107
+ """For each ψ U χ, build F = {B | ψ U χ ∉ B or χ ∈ B}.
108
+
109
+ These sets must each be visited infinitely often; they are not terminal
110
+ states. With no UNTIL subformulas the acceptance family is empty, so every
111
+ infinite run meets it. This differs from a family containing an empty set,
112
+ which no run can meet. Indices retain the elementary-set order (zero-based).
113
+
114
+ The formula's closure supplies the UNTIL obligations, including those whose
115
+ positive formula is absent from every supplied state. Each state is checked
116
+ and frozen, and duplicates are rejected before callbacks begin. No
117
+ enumeration, completeness check, initial-state selection, or transition
118
+ construction is performed. For the full GNBA, supply all elementary sets.
119
+ A subset, including an empty collection, yields acceptance sets restricted
120
+ to those states; completeness can be verified separately with
121
+ ``check_elementary_set_collection``.
122
+
123
+ Args:
124
+ formula: Formula already normalized by ``normalize_ltl``. Its closure
125
+ determines the UNTIL formulas, independently of the supplied states.
126
+ elementary_sets: Iterable of states containing formula objects, checked
127
+ with ``check_elementary_set``. Double negations and negated constants
128
+ are simplified as in the checker. Use a list or tuple for predictable
129
+ state indices; input iterators are consumed once.
130
+ on_step: Optional synchronous callback, called once per UNTIL formula
131
+ in formula-string order with all state decisions. With no UNTIL
132
+ formulas, it receives one explanatory step with no condition.
133
+
134
+ Returns:
135
+ One condition per UNTIL formula, retaining duplicate state sets so that
136
+ each obligation can be inspected independently.
137
+
138
+ Raises:
139
+ TypeError: If the formula or a state member has the wrong type.
140
+ ValueError: If the formula is not normalized, a state is not elementary,
141
+ or states are duplicated after simplifying equivalent spellings.
142
+ """
143
+ closure, states = _validate_elementary_sets(formula, elementary_sets)
144
+ untils = sorted((node for node in closure if isinstance(node, Until)), key=str)
145
+ conditions = []
146
+ for iteration, node in enumerate(untils):
147
+ decisions = []
148
+ indices = set()
149
+ for index, state in enumerate(states):
150
+ reason: Literal["until_absent", "right_present", "until_pending"]
151
+ if node not in state:
152
+ included, reason = True, "until_absent"
153
+ explanation = f"({node}) is absent; there is no pending obligation."
154
+ elif node.right in state:
155
+ included, reason = True, "right_present"
156
+ explanation = f"({node.right}) is present; the UNTIL obligation is fulfilled."
157
+ else:
158
+ included, reason = False, "until_pending"
159
+ explanation = f"({node}) is present but ({node.right}) is absent; the obligation is pending."
160
+ if included:
161
+ indices.add(index)
162
+ action = "Include" if included else "Exclude"
163
+ decisions.append(AcceptanceDecision(index, state, included, reason,
164
+ f"{action} B{index + 1}: {explanation}"))
165
+ condition = AcceptanceCondition(node,
166
+ frozenset(states[i] for i in indices),
167
+ frozenset(indices))
168
+ conditions.append(condition)
169
+ if on_step is not None:
170
+ on_step(AcceptanceStep(iteration, condition, tuple(decisions),
171
+ f"For ({node}), include B in F if the UNTIL formula is absent "
172
+ f"or its right operand ({node.right}) is present."))
173
+ if not untils and on_step is not None:
174
+ on_step(AcceptanceStep(0, None, (),
175
+ "There are no UNTIL formulas. The acceptance family is empty; "
176
+ "every infinite run satisfies its acceptance condition."))
177
+ return AcceptanceResult(tuple(conditions))
178
+
179
+
180
+ def trace_acceptance_sets(
181
+ formula: LTLFormula,
182
+ elementary_sets: Iterable[Iterable[LTLFormula]],
183
+ ) -> AlgorithmTrace[AcceptanceResult, AcceptanceStep]:
184
+ """Collect the acceptance result and all membership explanations in order.
185
+
186
+ Inputs and validation match ``compute_acceptance_sets``. The trace has one
187
+ step per UNTIL formula in the input's closure, or one explanatory step if
188
+ none occur. Each step's state decisions follow supplied order. Collection
189
+ completeness is a separate check.
190
+ """
191
+ steps: list[AcceptanceStep] = []
192
+ result = compute_acceptance_sets(formula, elementary_sets, on_step=steps.append)
193
+ return AlgorithmTrace(result, tuple(steps))
194
+
195
+
196
+ __all__ = [
197
+ "AcceptanceCondition", "AcceptanceDecision", "AcceptanceResult", "AcceptanceStep",
198
+ "compute_acceptance_sets", "trace_acceptance_sets",
199
+ ]