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,116 @@
1
+ """Select GNBA initial states from a formula and supplied elementary sets.
2
+
3
+ An elementary set is initial exactly when it contains the normalized input
4
+ formula. Decisions cover every supplied state and preserve its position,
5
+ including states that are not selected or are unreachable in the final GNBA.
6
+ """
7
+
8
+ from collections.abc import Callable, Iterable
9
+ from dataclasses import dataclass
10
+
11
+ from mocha.logic.ltl import LTLFormula
12
+
13
+ from ..trace import AlgorithmTrace
14
+ from .elementary_set_validation import _validate_elementary_sets
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class InitialStateStep:
19
+ """Explain whether one elementary set is an initial state.
20
+
21
+ ``iteration`` and ``state_index`` both give the zero-based position of
22
+ ``state`` in the supplied collection. Its display name is B followed by
23
+ that index plus one. ``is_initial`` records membership of the normalized
24
+ input formula in the state, and ``message`` explains the resulting decision.
25
+ """
26
+
27
+ iteration: int
28
+ state_index: int
29
+ state: frozenset[LTLFormula]
30
+ is_initial: bool
31
+ message: str
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class InitialStatesResult:
36
+ """Initial states selected for the normalized ``formula``.
37
+
38
+ ``initial_states`` contains the elementary sets that include the formula;
39
+ ``state_indices`` identifies those same sets by zero-based positions in
40
+ the supplied collection. Both collections can be empty, for example for
41
+ the constant false formula.
42
+ """
43
+
44
+ formula: LTLFormula
45
+ initial_states: frozenset[frozenset[LTLFormula]]
46
+ state_indices: frozenset[int]
47
+
48
+
49
+ def compute_initial_states(
50
+ formula: LTLFormula,
51
+ elementary_sets: Iterable[Iterable[LTLFormula]],
52
+ *,
53
+ on_step: Callable[[InitialStateStep], None] | None = None,
54
+ ) -> InitialStatesResult:
55
+ """Select exactly the elementary sets containing the normalized formula.
56
+
57
+ State indices are zero-based and retain supplied order as B1, B2, etc.
58
+ Each state is validated and frozen before callbacks begin; duplicate states
59
+ are rejected. No enumeration, completeness check, transition construction,
60
+ or reachability filtering is performed. For the full GNBA, the caller must
61
+ supply all elementary sets. Subsets and empty collections are accepted for
62
+ partial analysis; completeness can be verified separately using
63
+ ``check_elementary_set_collection``.
64
+
65
+ Args:
66
+ formula: Formula already normalized by ``normalize_ltl``. Membership of
67
+ this formula determines which supplied elementary sets are initial.
68
+ elementary_sets: Iterable of states containing formula objects, checked
69
+ using ``check_elementary_set``. Double negations and negated constants
70
+ are simplified as in the checker. Use a list or tuple for predictable
71
+ state indices; input iterators are consumed once.
72
+ on_step: Optional synchronous callback receiving one decision per
73
+ elementary set, in supplied order, including excluded states.
74
+
75
+ Returns:
76
+ The normalized formula, selected states, and their original indices.
77
+
78
+ Raises:
79
+ TypeError: If the formula or a state member has the wrong type.
80
+ ValueError: If the formula is not normalized, a state is not elementary,
81
+ or states are duplicated after simplifying equivalent spellings.
82
+ """
83
+ _, states = _validate_elementary_sets(formula, elementary_sets)
84
+ indices = set()
85
+ for index, state in enumerate(states):
86
+ selected = formula in state
87
+ if selected:
88
+ indices.add(index)
89
+ if on_step is not None:
90
+ membership = "contains" if selected else "does not contain"
91
+ status = "initial" if selected else "not initial"
92
+ on_step(InitialStateStep(
93
+ index, index, state, selected,
94
+ f"B{index + 1} {membership} ({formula}), so it is {status}.",
95
+ ))
96
+ return InitialStatesResult(formula,
97
+ frozenset(states[i] for i in indices),
98
+ frozenset(indices))
99
+
100
+
101
+ def trace_initial_states(
102
+ formula: LTLFormula,
103
+ elementary_sets: Iterable[Iterable[LTLFormula]],
104
+ ) -> AlgorithmTrace[InitialStatesResult, InitialStateStep]:
105
+ """Return the initial-state selection and retain every membership decision.
106
+
107
+ Inputs and validation match ``compute_initial_states``. Steps follow the
108
+ supplied order, with one decision per state, including noninitial states.
109
+ Collection completeness is a separate check.
110
+ """
111
+ steps: list[InitialStateStep] = []
112
+ result = compute_initial_states(formula, elementary_sets, on_step=steps.append)
113
+ return AlgorithmTrace(result, tuple(steps))
114
+
115
+
116
+ __all__ = ["InitialStateStep", "InitialStatesResult", "compute_initial_states", "trace_initial_states"]
@@ -0,0 +1,137 @@
1
+ """Translate LTL to a GNBA while preserving the details of each construction stage.
2
+
3
+ The pipeline normalizes the formula, enumerates elementary sets, selects initial
4
+ states, derives transitions, and builds UNTIL acceptance sets. Stage callbacks
5
+ share one global sequence number while retaining their original local details.
6
+ Each construction stage is also available as an independent function.
7
+ """
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from typing import Literal
12
+
13
+ from mocha.logic.ltl import LTLFormula
14
+
15
+ from ..ltl_transformations import LTLRewriteStep, normalize_ltl
16
+ from mocha.models.automaton import GNBA
17
+
18
+ from ..trace import AlgorithmTrace
19
+ from .acceptance import AcceptanceResult, AcceptanceStep, compute_acceptance_sets
20
+ from .elementary_set_enumeration import ElementarySetEnumeration, ElementaryTableStep, enumerate_elementary_sets
21
+ from .initial_states import InitialStatesResult, InitialStateStep, compute_initial_states
22
+ from .transitions import (
23
+ ElementarySet, Valuation, TransitionRelationResult, TransitionRelationStep, compute_transition_relation,
24
+ )
25
+
26
+ StageName = Literal["normalization", "elementary_sets", "initial_states", "transitions", "acceptance"]
27
+ StageDetail = LTLRewriteStep | ElementaryTableStep | InitialStateStep | TransitionRelationStep | AcceptanceStep
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class LTLToGNBAStep:
32
+ """A construction event with both global ordering and local stage detail.
33
+
34
+ ``iteration`` counts from zero across the entire translation. ``stage``
35
+ identifies normalization, elementary-set enumeration, initial-state
36
+ selection, transitions, or acceptance. ``detail`` is the original immutable
37
+ event from that stage, including its own local iteration number.
38
+ """
39
+
40
+ iteration: int
41
+ stage: StageName
42
+ detail: StageDetail
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class LTLToGNBAResult:
47
+ """The assembled GNBA and the results used to construct it.
48
+
49
+ Attributes:
50
+ formula: Original input, before normalization.
51
+ normalized_formula: Equivalent formula in the construction's core syntax.
52
+ elementary_sets: All elementary states over the normalized closure,
53
+ including states that are not initial or reachable.
54
+ initial_states: States containing the normalized formula.
55
+ transition_relation: Labelled edges and the full valuation alphabet.
56
+ acceptance: One generalized Büchi condition per UNTIL formula.
57
+ automaton: GNBA recognizing precisely the input formula's infinite words.
58
+
59
+ The result and stage records are frozen, but ``automaton`` remains mutable.
60
+ Editing it does not update the recorded construction results.
61
+ """
62
+
63
+ formula: LTLFormula
64
+ normalized_formula: LTLFormula
65
+ elementary_sets: ElementarySetEnumeration
66
+ initial_states: InitialStatesResult
67
+ transition_relation: TransitionRelationResult
68
+ acceptance: AcceptanceResult
69
+ automaton: GNBA[ElementarySet, Valuation]
70
+
71
+
72
+ def ltl_to_gnba(
73
+ formula: LTLFormula,
74
+ *,
75
+ on_step: Callable[[LTLToGNBAStep], None] | None = None,
76
+ ) -> LTLToGNBAResult:
77
+ """Normalize, enumerate, select initial states, add transitions and acceptance.
78
+
79
+ Recognizes the input formula itself: model checking's negation of a
80
+ property must be explicit. All states and stage indices retain the same
81
+ elementary-set enumeration. The alphabet is 2^AP for the formula's AP.
82
+ Stage functions also remain independently callable.
83
+
84
+ Args:
85
+ formula: LTL formula to recognize. Derived operators are normalized
86
+ automatically before the elementary-set stages run.
87
+ on_step: Optional synchronous callback receiving each stage's events
88
+ in construction order, wrapped with a global zero-based iteration.
89
+
90
+ Returns:
91
+ The original and normalized formulas, every stage result, and the
92
+ assembled GNBA. Its states include all enumerated elementary sets;
93
+ unreachable states are retained.
94
+ """
95
+ iteration = 0
96
+
97
+ def report(stage: StageName, detail: StageDetail) -> None:
98
+ nonlocal iteration
99
+ if on_step is not None:
100
+ on_step(LTLToGNBAStep(iteration, stage, detail))
101
+ iteration += 1
102
+
103
+ normalized = normalize_ltl(formula, on_step=lambda step: report("normalization", step))
104
+ enumeration = enumerate_elementary_sets(normalized, on_step=lambda step: report("elementary_sets", step))
105
+ initial = compute_initial_states(
106
+ normalized, enumeration.elementary_sets,
107
+ on_step=lambda step: report("initial_states", step),
108
+ )
109
+ transitions = compute_transition_relation(
110
+ normalized, enumeration.elementary_sets,
111
+ on_step=lambda step: report("transitions", step),
112
+ )
113
+ acceptance = compute_acceptance_sets(
114
+ normalized, enumeration.elementary_sets,
115
+ on_step=lambda step: report("acceptance", step),
116
+ )
117
+ automaton = GNBA.from_components(
118
+ states=enumeration.elementary_sets, alphabet=transitions.alphabet,
119
+ transitions=transitions.transitions, initial_states=initial.initial_states,
120
+ accepting_sets=acceptance.accepting_sets,
121
+ )
122
+ return LTLToGNBAResult(formula, normalized, enumeration, initial, transitions, acceptance, automaton)
123
+
124
+
125
+ def trace_ltl_to_gnba(formula: LTLFormula) -> AlgorithmTrace[LTLToGNBAResult, LTLToGNBAStep]:
126
+ """Translate ``formula`` and retain the complete construction trace in memory.
127
+
128
+ ``result`` is the same construction returned by ``ltl_to_gnba``; ``steps``
129
+ collects its callback events in global order, retaining stage-specific
130
+ details such as elementary-table snapshots and transition restrictions.
131
+ """
132
+ steps: list[LTLToGNBAStep] = []
133
+ result = ltl_to_gnba(formula, on_step=steps.append)
134
+ return AlgorithmTrace(result, tuple(steps))
135
+
136
+
137
+ __all__ = ["LTLToGNBAResult", "LTLToGNBAStep", "ltl_to_gnba", "trace_ltl_to_gnba"]
@@ -0,0 +1,327 @@
1
+ """Derive GNBA edges by propagating NEXT and UNTIL choices between states.
2
+
3
+ Supply a normalized formula and a collection of elementary sets. The collection
4
+ is checked for valid members and duplicates. Completeness is a precondition for
5
+ full GNBA construction and can be verified separately.
6
+ Temporal rules restrict possible targets for each source; every surviving edge
7
+ is labelled with the atomic propositions present in that source. UNTIL
8
+ acceptance is handled separately, so locally consistent pending obligations
9
+ can form cycles.
10
+ """
11
+
12
+ from collections.abc import Callable, Iterable
13
+ from dataclasses import dataclass
14
+ from itertools import product
15
+
16
+ from mocha.logic.ltl import LTLFormula, Next, Proposition, Until, propositions
17
+ from mocha.models.automaton import AutomatonTransition
18
+
19
+ from ..trace import AlgorithmTrace
20
+ from .elementary_set_validation import _validate_elementary_sets
21
+
22
+ ElementarySet = frozenset[LTLFormula]
23
+ Valuation = frozenset[str]
24
+ StatePair = tuple[int, int]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class TransitionRelationTable:
29
+ """Source rows and target columns retain the supplied elementary-set order.
30
+
31
+ ``allowed_pairs`` uses zero-based indices into ``states``. Intermediate
32
+ tables show ticks; labelled tables show source valuations. A blank cell
33
+ means no transition, whereas ∅ means a transition on the empty valuation.
34
+
35
+ Attributes:
36
+ states: Elementary sets in their supplied order.
37
+ allowed_pairs: Permitted (source, target) index pairs into ``states``.
38
+ source_labels: Valuations aligned with ``states``, each containing the
39
+ names of atomic propositions present in the corresponding source.
40
+ labelled: Whether rendering uses source valuations instead of ticks.
41
+ """
42
+
43
+ states: tuple[ElementarySet, ...]
44
+ allowed_pairs: frozenset[StatePair]
45
+ source_labels: tuple[Valuation, ...]
46
+ labelled: bool = False
47
+
48
+ def to_markdown(self) -> str:
49
+ """Render the transition matrix with B1, B2, ... row and column labels.
50
+
51
+ Allowed cells contain a tick or source valuation according to
52
+ ``labelled``. Forbidden cells remain blank. Proposition names in
53
+ valuations are sorted and escaped for Markdown table cells.
54
+ """
55
+ headers = [f"B{index + 1}" for index in range(len(self.states))]
56
+ lines = ["| source / target | " + " | ".join(headers) + " |",
57
+ "| " + " | ".join(["---"] * (len(headers) + 1)) + " |"]
58
+ for source, label in enumerate(self.source_labels):
59
+ if self.labelled:
60
+ names = [str(Proposition(name)).replace("\\", "\\\\")
61
+ .replace("|", "\\|").replace("\n", " ") for name in sorted(label)]
62
+ cell = "{" + ", ".join(names) + "}" if names else "∅"
63
+ else:
64
+ cell = "✓"
65
+ cells = [cell if (source, target) in self.allowed_pairs else ""
66
+ for target in range(len(self.states))]
67
+ lines.append("| " + " | ".join([headers[source], *cells]) + " |")
68
+ return "\n".join(lines)
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class TransitionRestriction:
73
+ """One temporal formula's restriction for a fixed source elementary set.
74
+
75
+ Target indices are zero-based. ``allowed_targets`` considers this formula
76
+ alone; ``remaining_targets`` intersects it with all preceding restrictions.
77
+ A missing ``required_formula`` means this formula imposes no restriction.
78
+
79
+ Attributes:
80
+ formula: NEXT or UNTIL formula being considered in the source.
81
+ rule: Machine-readable case name, such as ``next_included`` or
82
+ ``until_pending``.
83
+ message: Explanation specialized to the source's formula memberships.
84
+ required_formula: Formula whose membership is constrained in the target,
85
+ or ``None`` if every target satisfies this rule.
86
+ required_present: Required membership of that formula; ``None`` when
87
+ no target constraint is imposed.
88
+ allowed_targets: Targets satisfying this formula alone.
89
+ remaining_targets: Targets surviving this and all earlier restrictions.
90
+ removed_targets: Previously surviving targets eliminated by this rule.
91
+ """
92
+
93
+ formula: LTLFormula
94
+ rule: str
95
+ message: str
96
+ required_formula: LTLFormula | None
97
+ required_present: bool | None
98
+ allowed_targets: frozenset[int]
99
+ remaining_targets: frozenset[int]
100
+ removed_targets: frozenset[int]
101
+
102
+
103
+ def _target_names(targets: frozenset[int]) -> str:
104
+ """Format zero-based target indices as ordered B labels, or ∅ if empty."""
105
+ return "{" + ", ".join(f"B{index + 1}" for index in sorted(targets)) + "}" if targets else "∅"
106
+
107
+
108
+ def _valuation_text(valuation: Valuation) -> str:
109
+ """Format a valuation using sorted proposition names, or ∅ if empty."""
110
+ return "{" + ", ".join(str(Proposition(name)) for name in sorted(valuation)) + "}" if valuation else "∅"
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class TransitionRelationStep:
115
+ """A complete derivation of outgoing transitions for one elementary set.
116
+
117
+ ``input`` is the valuation labelling every outgoing transition.
118
+ ``restrictions`` visits each NEXT and UNTIL formula once, specializing its
119
+ rule to this source. ``targets`` is the final intersection. Source and
120
+ target indices refer to the supplied state order and are zero-based.
121
+
122
+ ``iteration`` equals ``source_index`` because each source produces exactly
123
+ one step. ``source`` retains the elementary set itself. Restrictions list
124
+ NEXT formulas first, then UNTIL formulas, with each group sorted by string
125
+ representation, including rules considered after no targets remain.
126
+ """
127
+
128
+ iteration: int
129
+ source_index: int
130
+ source: ElementarySet
131
+ input: Valuation
132
+ restrictions: tuple[TransitionRestriction, ...]
133
+ targets: frozenset[int]
134
+
135
+ def to_markdown(self) -> str:
136
+ """Explain the input and successive target restrictions for this source."""
137
+ name = f"B{self.source_index + 1}"
138
+ label = _valuation_text(self.input)
139
+ lines = [f"### Transitions from {name}", "",
140
+ f"Input: {label} (the atomic propositions in {name}).", "",
141
+ "Start with all elementary sets as possible targets.", ""]
142
+ for index, restriction in enumerate(self.restrictions, 1):
143
+ lines.extend([
144
+ f"{index}. {restriction.message}",
145
+ f" Targets allowed by this formula: {_target_names(restriction.allowed_targets)}.",
146
+ f" Remaining targets: {_target_names(restriction.remaining_targets)}.", "",
147
+ ])
148
+ if not self.restrictions:
149
+ lines.extend(["There are no NEXT or UNTIL formulas, so every target is allowed.", ""])
150
+ lines.append(f"Result: {name} —{label}→ {_target_names(self.targets)}.")
151
+ return "\n".join(lines)
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class TransitionRelationResult:
156
+ """The labelled edges and full alphabet for ``formula`` and supplied states.
157
+
158
+ ``table`` retains the supplied state order and the permitted source/target
159
+ pairs, with valuation rendering enabled. ``transitions`` gives the same
160
+ relation as automaton edges labelled by source valuations. ``alphabet`` is
161
+ the powerset of all proposition names in the formula, including valuations
162
+ that label no surviving edge. Initial and accepting states are determined
163
+ by separate construction stages.
164
+ """
165
+
166
+ formula: LTLFormula
167
+ table: TransitionRelationTable
168
+ alphabet: frozenset[Valuation]
169
+ transitions: frozenset[AutomatonTransition[ElementarySet, Valuation]]
170
+
171
+
172
+ def compute_transition_relation(
173
+ formula: LTLFormula,
174
+ elementary_sets: Iterable[Iterable[LTLFormula]],
175
+ *,
176
+ on_step: Callable[[TransitionRelationStep], None] | None = None,
177
+ ) -> TransitionRelationResult:
178
+ """Derive outgoing transitions one elementary set at a time.
179
+
180
+ Call ``compute_transition_relation(formula, elementary_sets)`` with the
181
+ normalized formula and ordered states. Each state is validated, but no
182
+ enumeration, completeness check, or initial-state selection is performed.
183
+ To verify completeness explicitly, call
184
+ ``validate_elementary_set_collection`` separately.
185
+
186
+ Supplied order determines B1, B2, ... labels and zero-based state indices;
187
+ use a list or tuple when that order matters. For each source, determine the
188
+ input valuation (the set of proposition names true in that source), then
189
+ specialize every NEXT and UNTIL rule to its formula memberships. Record
190
+ each rule's target restriction, including unrestricted cases, and the
191
+ remaining targets after applying it. The alphabet is 2^AP: all subsets of
192
+ the proposition names AP occurring in the formula.
193
+
194
+ For example, the complete manually supplied collection for ``X p`` is::
195
+
196
+ from mocha.logic.ltl import Next, Not, Proposition
197
+
198
+ p = Proposition("p")
199
+ formula = Next(p)
200
+ states = [{p, formula}, {p, Not(formula)},
201
+ {Not(p), formula}, {Not(p), Not(formula)}]
202
+ result = compute_transition_relation(formula, states)
203
+
204
+ Sources containing ``X p`` allow exactly the targets containing ``p``;
205
+ sources containing its negation allow exactly the targets excluding ``p``.
206
+
207
+ For a source B and target B', the restrictions enforce both equivalences:
208
+ ``X ψ ∈ B`` iff ``ψ ∈ B'``, and ``ψ U χ ∈ B`` iff ``χ ∈ B`` or
209
+ (``ψ ∈ B`` and ``ψ U χ ∈ B'``). All source/target pairs are considered,
210
+ including self-loops and states unreachable from the eventual initial set.
211
+
212
+ This constructs only the transition relation; UNTIL acceptance sets are
213
+ a separate stage. In particular, a pending UNTIL may continue on a cycle.
214
+
215
+ Args:
216
+ formula: Formula already normalized by ``normalize_ltl``. Its closure
217
+ supplies all temporal rules, even when their positive formulas are
218
+ absent from every supplied state.
219
+ elementary_sets: Iterable of elementary sets containing formula objects,
220
+ each validated by ``check_elementary_set`` and stored as a frozenset.
221
+ Double negations and negated constants are simplified as in the
222
+ checker. Distinct states retain input order. A full GNBA requires
223
+ all elementary sets over the formula's closure; the caller supplies
224
+ that guarantee. A subset, including an empty collection, is also
225
+ accepted for partial analysis: only edges between supplied states
226
+ are built, which need not recognize the formula's full language.
227
+ on_step: Optional synchronous callback receiving one derivation per
228
+ source in supplied order, including sources with no targets. All
229
+ supplied states are validated before the first callback.
230
+
231
+ Returns:
232
+ The normalized formula, labelled transition table, full valuation
233
+ alphabet, and permitted automaton edges.
234
+
235
+ Raises:
236
+ TypeError: If the formula or a candidate member has the wrong type.
237
+ ValueError: If the formula is not normalized, a supplied set fails the
238
+ elementary-set conditions, or two supplied states are identical
239
+ after simplifying equivalent spellings.
240
+ """
241
+ closure, states = _validate_elementary_sets(formula, elementary_sets)
242
+ labels = tuple(frozenset(node.name for node in state if isinstance(node, Proposition))
243
+ for state in states)
244
+ all_targets = frozenset(range(len(states)))
245
+ allowed: set[StatePair] = set()
246
+ nexts = sorted((node for node in closure if isinstance(node, Next)), key=str)
247
+ untils = sorted((node for node in closure if isinstance(node, Until)), key=str)
248
+ temporal_formulas: tuple[Next | Until, ...] = (*nexts, *untils)
249
+ for source_index, source in enumerate(states):
250
+ name = f"B{source_index + 1}"
251
+ remaining = all_targets
252
+ restrictions = []
253
+ for node in temporal_formulas:
254
+ required: LTLFormula | None = None
255
+ present: bool | None = None
256
+ if isinstance(node, Next):
257
+ required, present = node.operand, node in source
258
+ rule = "next_included" if present else "next_excluded"
259
+ membership = "included in" if present else "excluded from"
260
+ message = (f"({node}) is {membership} {name}, so ({node.operand}) "
261
+ f"must be {membership} the target set.")
262
+ elif node.right in source:
263
+ rule = "until_fulfilled"
264
+ message = (f"({node}) and its right operand ({node.right}) are included in {name}. "
265
+ "The UNTIL obligation is already fulfilled, so it imposes no restriction on the target.")
266
+ elif node in source:
267
+ rule = "until_pending"
268
+ required, present = node, True
269
+ message = (f"({node}) is included in {name}, but ({node.right}) is excluded. "
270
+ f"Its left operand ({node.left}) holds, so the obligation must continue: "
271
+ f"include ({node}) in the target set.")
272
+ elif node.left in source:
273
+ rule = "until_excluded"
274
+ required, present = node, False
275
+ message = (f"({node}) is excluded from {name}, while ({node.left}) is included "
276
+ f"and ({node.right}) is excluded. To keep UNTIL false, "
277
+ f"exclude ({node}) from the target set.")
278
+ else:
279
+ rule = "until_inactive"
280
+ message = (f"({node}) and both operands are excluded from {name}. "
281
+ "UNTIL is false regardless of the target, so it imposes no restriction.")
282
+ permitted = all_targets if required is None else frozenset(
283
+ index for index, target in enumerate(states) if (required in target) == present
284
+ )
285
+ removed = remaining - permitted
286
+ remaining = remaining & permitted
287
+ restrictions.append(TransitionRestriction(
288
+ node, rule, message, required, present, permitted, remaining, removed,
289
+ ))
290
+ allowed.update((source_index, target) for target in remaining)
291
+ if on_step is not None:
292
+ on_step(TransitionRelationStep(source_index, source_index, source, labels[source_index],
293
+ tuple(restrictions), remaining))
294
+
295
+ transitions = frozenset(AutomatonTransition(states[i], labels[i], states[j]) for i, j in allowed)
296
+ names = sorted(propositions(formula))
297
+ alphabet = frozenset(frozenset(name for name, selected in zip(names, bits) if selected)
298
+ for bits in product((False, True), repeat=len(names)))
299
+ return TransitionRelationResult(formula,
300
+ TransitionRelationTable(states, frozenset(allowed), labels, True),
301
+ alphabet, transitions)
302
+
303
+
304
+ def trace_transition_relation(
305
+ formula: LTLFormula,
306
+ elementary_sets: Iterable[Iterable[LTLFormula]],
307
+ ) -> AlgorithmTrace[TransitionRelationResult, TransitionRelationStep]:
308
+ """Record the input and ordered formula restrictions for each source set.
309
+
310
+ Accepts ``(formula, elementary_sets)`` with the same validation and ordering
311
+ rules as ``compute_transition_relation``.
312
+ Individual states and duplicates are checked; collection completeness is
313
+ a separate operation, ``validate_elementary_set_collection``.
314
+ The trace's ``result`` is the computed relation; ``steps`` retains one
315
+ immutable derivation per supplied source in input order, including removed
316
+ targets and unrestricted formulas.
317
+ """
318
+ steps: list[TransitionRelationStep] = []
319
+ result = compute_transition_relation(formula, elementary_sets, on_step=steps.append)
320
+ return AlgorithmTrace(result, tuple(steps))
321
+
322
+
323
+ __all__ = [
324
+ "TransitionRestriction",
325
+ "TransitionRelationTable", "TransitionRelationStep", "TransitionRelationResult",
326
+ "compute_transition_relation", "trace_transition_relation",
327
+ ]