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,360 @@
1
+ """Enumerate elementary sets for normalized LTL formulas using a choice table.
2
+
3
+ Each column represents a formula and its complement. A cell value of ``1``
4
+ means the elementary set includes the column formula; ``0`` means it includes
5
+ the complement instead. For a column ``p``, these choices select ``p`` and
6
+ ``not p``, respectively. An ``x`` means the choice is unresolved. Internally,
7
+ these values are stored as ``True``, ``False``, and ``None``, respectively.
8
+
9
+ Rows start with all choices for atomic propositions and NEXT formulas; Boolean
10
+ and local UNTIL rules then resolve or split the remaining choices. Completed
11
+ rows represent elementary sets over the input formula's closure, including
12
+ sets that do not contain the input formula itself.
13
+
14
+ Enumeration can emit immutable snapshots with stable row IDs, split ancestry,
15
+ and cell changes so that callers can display or inspect each rule application.
16
+ """
17
+
18
+ from collections.abc import Callable, Mapping
19
+ from dataclasses import dataclass
20
+ from itertools import product
21
+
22
+ from mocha.logic.ltl import (
23
+ And, BooleanConstant, LTLFormula, Next, Not, Proposition, Until, complement,
24
+ )
25
+
26
+ from ..trace import AlgorithmTrace
27
+ from .elementary_set_validation import check_elementary_set
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ElementaryTableRow:
32
+ """An immutable assignment of choices to a table's ordered columns.
33
+
34
+ Attributes:
35
+ id: Stable identifier within one enumeration, independent of the row's
36
+ display position. Filling cells preserves this ID; splitting a row
37
+ replaces it with two children that receive fresh IDs.
38
+ values: One entry per table column. ``True`` selects the column formula,
39
+ ``False`` selects its complement, and ``None`` leaves the choice
40
+ unresolved. The tuple has the same order as ``ElementaryTable.columns``.
41
+ parent_id: ID of the row from which this row was split, or ``None`` for
42
+ an initial row. The parent can be found in earlier snapshots and
43
+ need not be present in the current table.
44
+
45
+ The frozen dataclass prevents field reassignment. Enumeration creates new
46
+ row objects when filling cells, preserving previously emitted snapshots.
47
+ """
48
+
49
+ id: int
50
+ values: tuple[bool | None, ...]
51
+ parent_id: int | None = None
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ElementaryTable:
56
+ """An immutable snapshot of partial or completed elementary set choices.
57
+
58
+ A Markdown cell ``1`` (``True``) selects its column formula, ``0``
59
+ (``False``) selects the complement, and ``x`` (``None``) is unresolved.
60
+ Once every cell is resolved, each row represents one elementary set.
61
+
62
+ Attributes:
63
+ columns: Ordered formula representatives, one per complement pair in
64
+ the closure. A false cell selects the representative's complement.
65
+ rows: Assignments in enumeration order, with one value per column.
66
+ Splits replace a row in place with its false child, then its true
67
+ child; their stable IDs retain the link to the original row.
68
+
69
+ """
70
+
71
+ columns: tuple[LTLFormula, ...]
72
+ rows: tuple[ElementaryTableRow, ...]
73
+
74
+ @property
75
+ def is_complete(self) -> bool:
76
+ """Whether every cell has chosen its column formula or its complement."""
77
+ return all(value is not None for row in self.rows for value in row.values)
78
+
79
+ def to_markdown(self, aliases: Mapping[LTLFormula, str] | None = None) -> str:
80
+ """Render a table, optionally abbreviating columns with a formula legend.
81
+
82
+ Completed rows are numbered B1, B2, ... in result order. Stable row IDs
83
+ and split ancestry remain available on the row objects for trace UIs.
84
+
85
+ Args:
86
+ aliases: Optional formula-to-label mapping used for column headers.
87
+ Aliased columns also receive a legend below the table. Other
88
+ columns use their formula's string representation.
89
+
90
+ Returns:
91
+ A Markdown table where ``1`` selects the column formula, ``0``
92
+ selects its complement, and ``x`` marks an unresolved choice.
93
+ If any cell is unresolved, all rows use plain positional numbers
94
+ instead of B labels. Backslashes and pipes are escaped, and
95
+ newlines in headers and legend entries are replaced with spaces.
96
+ """
97
+ aliases = aliases or {}
98
+
99
+ def escape(text: str) -> str:
100
+ return text.replace("\\", "\\\\").replace("|", "\\|").replace("\n", " ")
101
+
102
+ headers = [escape(aliases.get(column, str(column))) for column in self.columns]
103
+ lines = ["| " + " | ".join(["B" if self.is_complete else "#", *headers]) + " |",
104
+ "| " + " | ".join(["---"] * (len(headers) + 1)) + " |"]
105
+ for index, row in enumerate(self.rows, 1):
106
+ label = f"B{index}" if self.is_complete else str(index)
107
+ cells = ["x" if value is None else str(int(value)) for value in row.values]
108
+ lines.append("| " + " | ".join([label, *cells]) + " |")
109
+ legend = [f"{escape(aliases[column])} = {escape(str(column))}"
110
+ for column in self.columns if column in aliases]
111
+ if legend:
112
+ lines.extend(["", *[f"- {entry}" for entry in legend]])
113
+ return "\n".join(lines)
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class ElementaryTableChange:
118
+ """A cell assignment made by one enumeration step.
119
+
120
+ Attributes:
121
+ row_id: Stable ID of the affected row in the step's new snapshot.
122
+ For a split, this identifies a child rather than its parent.
123
+ column: Zero-based index into the snapshot's columns.
124
+ before: Previous choice, or ``None`` if unresolved. A split compares
125
+ against the parent's values; initial choices compare against an
126
+ entirely unresolved row.
127
+ after: Resolved choice in the new snapshot.
128
+ """
129
+
130
+ row_id: int
131
+ column: int
132
+ before: bool | None
133
+ after: bool
134
+
135
+
136
+ @dataclass(frozen=True)
137
+ class ElementaryTableStep:
138
+ """One rule application and the immutable table snapshot it produces.
139
+
140
+ Attributes:
141
+ iteration: Zero-based step number within one enumeration.
142
+ rule: Machine-readable rule name, such as ``simple_choices``,
143
+ ``conjunction``, ``until_choices``, or ``complete``.
144
+ message: Human-readable explanation of the rule application.
145
+ table: Table after applying the rule, including any newly split rows.
146
+ changes: Assignments made by this step. This can be empty when a rule
147
+ has no effect or when the step announces completion.
148
+ formula: Formula whose column is being processed, or ``None`` for the
149
+ initial choices and completion steps.
150
+ """
151
+
152
+ iteration: int
153
+ rule: str
154
+ message: str
155
+ table: ElementaryTable
156
+ changes: tuple[ElementaryTableChange, ...]
157
+ formula: LTLFormula | None = None
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class ElementarySetEnumeration:
162
+ """The completed table and the elementary sets derived from its rows.
163
+
164
+ Attributes:
165
+ formula: Normalized input formula used to build the closure.
166
+ closure: Input subformulas together with their complements.
167
+ table: Final table, with every cell resolved.
168
+ elementary_sets: Validated elementary sets in the same order as the
169
+ table's rows. Each set selects exactly one member of every
170
+ complement pair; it need not contain the input formula.
171
+ """
172
+
173
+ formula: LTLFormula
174
+ closure: frozenset[LTLFormula]
175
+ table: ElementaryTable
176
+ elementary_sets: tuple[frozenset[LTLFormula], ...]
177
+
178
+
179
+ def _columns(formula: LTLFormula, closure: frozenset[LTLFormula]) -> tuple[LTLFormula, ...]:
180
+ """Choose one representative per complement pair in evaluation order.
181
+
182
+ Propositions come first, followed by NEXT formulas, each group sorted by
183
+ string representation. A left-to-right traversal then adds conjunctions
184
+ and UNTIL formulas after their dependencies, with ``true`` representing
185
+ the constant pair when needed. Negations use their operand's column.
186
+ NEXT choices remain independent of their operands, whose subformulas are
187
+ still visited to include the rest of the closure.
188
+ """
189
+ # NEXT is an independent choice even when its operand is compound. Still
190
+ # traverse that operand: its subformulas also belong to the closure.
191
+ simple: list[Proposition | Next] = sorted(
192
+ (node for node in closure if isinstance(node, (Proposition, Next))),
193
+ key=lambda node: (isinstance(node, Next), str(node)),
194
+ )
195
+ ordered: list[LTLFormula] = list(simple)
196
+ visited: set[LTLFormula] = set()
197
+
198
+ def visit(node: LTLFormula) -> None:
199
+ if node in visited:
200
+ return
201
+ visited.add(node)
202
+ if isinstance(node, (Not, Next)):
203
+ visit(node.operand)
204
+ elif isinstance(node, (And, Until)):
205
+ visit(node.left)
206
+ visit(node.right)
207
+ ordered.append(node)
208
+ elif isinstance(node, BooleanConstant) and BooleanConstant(True) not in ordered:
209
+ ordered.append(BooleanConstant(True))
210
+
211
+ visit(formula)
212
+ return tuple(ordered)
213
+
214
+
215
+ def enumerate_elementary_sets(
216
+ formula: LTLFormula, *, on_step: Callable[[ElementaryTableStep], None] | None = None,
217
+ ) -> ElementarySetEnumeration:
218
+ """Build elementary sets from atomic/NEXT choices, Boolean rules and UNTIL.
219
+
220
+ Each column represents a formula and its complement. A cell displayed as
221
+ ``1`` selects the column formula for the elementary set; ``0`` excludes it
222
+ and selects its complement instead. For example, in a column for ``p``,
223
+ ``1`` selects ``p`` and ``0`` selects ``not p``. An ``x`` marks an unresolved
224
+ choice. These cell values are stored as ``True``, ``False``, and ``None``,
225
+ respectively.
226
+
227
+ Simple columns are ordered by name (atomics first, then NEXT), with 0 before
228
+ 1. Compound columns follow dependency order, using left-to-right traversal
229
+ to break ties. Each UNTIL is processed with two separate local rules, then
230
+ remaining choices split into two child rows: one selecting the complement
231
+ (0), then one selecting the UNTIL formula (1). Boolean evaluation resumes
232
+ as needed for nested formulas. No restriction to sets containing the input
233
+ is made.
234
+
235
+ For an UNTIL formula, a selected right operand forces inclusion, while
236
+ excluding both operands forces exclusion. If only the left operand is
237
+ selected, both choices are locally consistent and the row splits.
238
+ NEXT formulas have no local constraint tying them to their operands.
239
+
240
+ Args:
241
+ formula: Formula already normalized by ``normalize_ltl`` to AND, NOT,
242
+ NEXT, UNTIL, propositions, and constants, without double negations
243
+ or negated constants. No automatic normalization is performed.
244
+ on_step: Optional synchronous callback receiving each rule application
245
+ as an ``ElementaryTableStep``, including initial choices and final
246
+ completion. Steps include immutable snapshots and changed cells,
247
+ even when a rule changes no cells. Snapshots can be retained safely.
248
+
249
+ Returns:
250
+ The input formula, its closure, the completed table, and all elementary
251
+ sets in row order. Each set is independently validated by
252
+ ``check_elementary_set`` before the completion step is emitted.
253
+
254
+ Raises:
255
+ TypeError: If ``formula`` is not an ``LTLFormula``.
256
+ ValueError: If ``formula`` is not in the required normal form.
257
+ RuntimeError: If a dependency remains unresolved or a completed row
258
+ fails elementary-set validation, indicating an internal error.
259
+ """
260
+ closure = check_elementary_set(formula, ()).closure
261
+ columns = _columns(formula, closure)
262
+ indices = {column: index for index, column in enumerate(columns)}
263
+ simple_count = sum(isinstance(column, (Proposition, Next)) for column in columns)
264
+ rows = [ElementaryTableRow(index, (*values, *((None,) * (len(columns) - simple_count))))
265
+ for index, values in enumerate(product((False, True), repeat=simple_count), 1)]
266
+ next_id = len(rows) + 1
267
+ iteration = 0
268
+
269
+ def emit(rule: str, message: str, changes: list[ElementaryTableChange],
270
+ node: LTLFormula | None = None) -> None:
271
+ nonlocal iteration
272
+ if on_step is not None:
273
+ on_step(ElementaryTableStep(iteration, rule, message,
274
+ ElementaryTable(columns, tuple(rows)), tuple(changes), node))
275
+ iteration += 1
276
+
277
+ def value(node: LTLFormula, row: ElementaryTableRow) -> bool:
278
+ if isinstance(node, Not):
279
+ return not value(node.operand, row)
280
+ if isinstance(node, BooleanConstant):
281
+ return node.value
282
+ result = row.values[indices[node]]
283
+ if result is None:
284
+ raise RuntimeError(f"Unresolved dependency: {node}")
285
+ return result
286
+
287
+ def fill(index: int, decide: Callable[[ElementaryTableRow], bool | None]) -> list[ElementaryTableChange]:
288
+ changes = []
289
+ for position, row in enumerate(rows):
290
+ selected = decide(row)
291
+ if selected is not None and selected != row.values[index]:
292
+ changes.append(ElementaryTableChange(row.id, index, row.values[index], selected))
293
+ values = list(row.values)
294
+ values[index] = selected
295
+ rows[position] = ElementaryTableRow(row.id, tuple(values), row.parent_id)
296
+ return changes
297
+
298
+ emit("simple_choices", "Choose each atomic proposition and NEXT formula or its negation.",
299
+ [ElementaryTableChange(row.id, index, None, value(columns[index], row))
300
+ for row in rows for index in range(simple_count)])
301
+
302
+ for index, node in enumerate(columns[simple_count:], simple_count):
303
+ if isinstance(node, BooleanConstant):
304
+ emit("constant", "true must be included; false must be excluded.",
305
+ fill(index, lambda row: True), node)
306
+ elif isinstance(node, And):
307
+ emit("conjunction", f"Include {node} exactly when both operands are included.",
308
+ fill(index, lambda row: value(node.left, row) and value(node.right, row)), node)
309
+ elif isinstance(node, Until):
310
+ emit("until_fulfilled", f"If {node.right} is included, include {node}.",
311
+ fill(index, lambda row: True if value(node.right, row) else None), node)
312
+ emit("until_pending", f"If neither ({node.left}) nor ({node.right}) is included, "
313
+ f"exclude {node}: a pending UNTIL requires its left operand.",
314
+ fill(index, lambda row: False if not value(node.right, row)
315
+ and not value(node.left, row) else None), node)
316
+ expanded = []
317
+ changes = []
318
+ for row in rows:
319
+ if row.values[index] is not None:
320
+ expanded.append(row)
321
+ continue
322
+ for selected in (False, True):
323
+ values = list(row.values)
324
+ values[index] = selected
325
+ expanded.append(ElementaryTableRow(next_id, tuple(values), row.id))
326
+ changes.append(ElementaryTableChange(next_id, index, None, selected))
327
+ next_id += 1
328
+ rows = expanded
329
+ emit("until_choices", f"Where ({node.left}) is included and ({node.right}) is excluded, "
330
+ f"both choices for {node} are locally consistent; split each such row.", changes, node)
331
+
332
+ table = ElementaryTable(columns, tuple(rows))
333
+ sets = tuple(frozenset(column if selected else complement(column)
334
+ for column, selected in zip(columns, row.values)) for row in rows)
335
+ for candidate in sets:
336
+ if not check_elementary_set(formula, candidate).is_elementary:
337
+ raise RuntimeError("Enumeration produced a non-elementary set")
338
+ emit("complete", "Every completed row passes the elementary-set checker.", [])
339
+ return ElementarySetEnumeration(formula, closure, table, sets)
340
+
341
+
342
+ def trace_elementary_sets(formula: LTLFormula) -> AlgorithmTrace[ElementarySetEnumeration, ElementaryTableStep]:
343
+ """Enumerate elementary sets and retain every step in an ``AlgorithmTrace``.
344
+
345
+ ``formula`` has the same normalization requirements as
346
+ ``enumerate_elementary_sets``. The trace's ``result`` contains the completed
347
+ enumeration, and its ``steps`` tuple contains the callback snapshots in
348
+ order, from initial choices through completion. All snapshots are retained
349
+ in memory, including those for rules that change no cells.
350
+ """
351
+ steps: list[ElementaryTableStep] = []
352
+ result = enumerate_elementary_sets(formula, on_step=steps.append)
353
+ return AlgorithmTrace(result, tuple(steps))
354
+
355
+
356
+ __all__ = [
357
+ "ElementarySetEnumeration", "ElementaryTable", "ElementaryTableRow",
358
+ "ElementaryTableChange", "ElementaryTableStep", "enumerate_elementary_sets",
359
+ "trace_elementary_sets",
360
+ ]
@@ -0,0 +1,312 @@
1
+ """Validate individual elementary sets and full collections for normalized LTL.
2
+
3
+ Individual checks report closure, Boolean, local UNTIL, and maximality
4
+ violations. Collection checks add duplicate and completeness feedback for
5
+ computed solutions, retaining every submitted state and its individual result.
6
+ Completeness verification recomputes the full enumeration and can be expensive;
7
+ component construction uses only individual checks and duplicate detection.
8
+ """
9
+
10
+ from collections.abc import Iterable
11
+ from dataclasses import dataclass
12
+ from typing import Literal
13
+
14
+ from mocha.logic.ltl import (
15
+ And, BooleanConstant, LTLFormula, Next, Not, Until, complement,
16
+ )
17
+
18
+ from ..ltl_transformations import normalize_ltl
19
+
20
+ ElementarySetCondition = Literal[
21
+ "closure", "propositional_consistency", "local_consistency", "maximality"
22
+ ]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ElementarySetViolation:
27
+ """A failed condition, its witness formulas, and a readable explanation."""
28
+
29
+ condition: ElementarySetCondition
30
+ rule: str
31
+ formulas: tuple[LTLFormula, ...]
32
+ message: str
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ElementarySetResult:
37
+ """Immutable feedback, retaining the submitted candidate."""
38
+
39
+ formula: LTLFormula
40
+ candidate: frozenset[LTLFormula]
41
+ closure: frozenset[LTLFormula]
42
+ violations: tuple[ElementarySetViolation, ...]
43
+
44
+ @property
45
+ def is_elementary(self) -> bool:
46
+ return not self.violations
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ElementarySetCollectionResult:
51
+ """Feedback on a submitted collection, retaining every individual check.
52
+
53
+ Attributes:
54
+ formula: Normalized formula whose elementary sets are required.
55
+ state_results: Individual checker results in submission order, including
56
+ invalid entries and their violations. Each retains the original set.
57
+ duplicate_indices: Pairs (first index, repeated index) identifying valid
58
+ states with identical choices after simplifying equivalent spellings.
59
+ Indices are zero-based; add one to obtain display labels B1, B2, etc.
60
+ missing_sets: Required elementary sets absent from the valid submitted
61
+ states, in the enumeration's deterministic order.
62
+
63
+ ``is_complete`` describes coverage only. ``is_valid`` additionally requires
64
+ every submitted state to be elementary and each state to occur exactly once.
65
+ """
66
+
67
+ formula: LTLFormula
68
+ state_results: tuple[ElementarySetResult, ...]
69
+ duplicate_indices: tuple[tuple[int, int], ...]
70
+ missing_sets: tuple[frozenset[LTLFormula], ...]
71
+
72
+ @property
73
+ def is_complete(self) -> bool:
74
+ """Whether the valid submitted states cover every required elementary set."""
75
+ return not self.missing_sets
76
+
77
+ @property
78
+ def is_valid(self) -> bool:
79
+ """Whether the submission contains exactly all elementary sets, once each."""
80
+ return (self.is_complete and not self.duplicate_indices
81
+ and all(result.is_elementary for result in self.state_results))
82
+
83
+
84
+ def _representative(formula: LTLFormula) -> LTLFormula:
85
+ """Identify double negation and negated constants within core syntax."""
86
+ if isinstance(formula, Not):
87
+ return complement(_representative(formula.operand))
88
+ if isinstance(formula, Next):
89
+ return Next(_representative(formula.operand))
90
+ if isinstance(formula, (And, Until)):
91
+ return type(formula)(_representative(formula.left), _representative(formula.right))
92
+ return formula
93
+
94
+
95
+ def _closure(formula: LTLFormula) -> frozenset[LTLFormula]:
96
+ subformulas: set[LTLFormula] = set()
97
+
98
+ def visit(node: LTLFormula) -> None:
99
+ if node in subformulas:
100
+ return
101
+ subformulas.add(node)
102
+ if isinstance(node, (Not, Next)):
103
+ visit(node.operand)
104
+ elif isinstance(node, (And, Until)):
105
+ visit(node.left)
106
+ visit(node.right)
107
+
108
+ visit(formula)
109
+ return frozenset(subformulas | {complement(node) for node in subformulas})
110
+
111
+
112
+ def check_elementary_set(
113
+ formula: LTLFormula, candidate: Iterable[LTLFormula],
114
+ ) -> ElementarySetResult:
115
+ """Check the elementary-set conditions from *Principles of Model Checking*.
116
+
117
+ ``formula`` must already be normalized by ``normalize_ltl``: only AND,
118
+ NOT, NEXT, UNTIL, propositions, and constants are allowed, without double
119
+ negations or negated constants. No automatic normalization is performed.
120
+
121
+ Candidates use formula objects (e.g. from ``parse_ltl``). Membership
122
+ identifies double negations and negated constants within core syntax;
123
+ derived operators are not expanded. The original candidate is retained.
124
+ Every failed condition is reported, in deterministic order. Elementary
125
+ sets need not contain ``formula``; NEXT has no local temporal condition.
126
+ """
127
+ if not isinstance(formula, LTLFormula):
128
+ raise TypeError("formula must be an LTLFormula")
129
+ normalized = normalize_ltl(formula)
130
+ if normalized != formula:
131
+ raise ValueError(
132
+ f"Formula '{formula}' is not normalized. Elementary-set checking requires "
133
+ "only AND, NOT, NEXT, UNTIL, propositions, and constants, with no double "
134
+ "negations or negated constants. Call normalize_ltl(formula) first; "
135
+ f"the normalized formula is '{normalized}'."
136
+ )
137
+ submitted = tuple(candidate)
138
+ if any(not isinstance(item, LTLFormula) for item in submitted):
139
+ raise TypeError("candidate members must be LTLFormula objects")
140
+ original = frozenset(submitted)
141
+ members = frozenset(_representative(item) for item in original)
142
+ closure = _closure(formula)
143
+ violations: list[ElementarySetViolation] = []
144
+
145
+ def report(
146
+ condition: ElementarySetCondition, rule: str,
147
+ formulas: tuple[LTLFormula, ...], message: str,
148
+ ) -> None:
149
+ violations.append(ElementarySetViolation(condition, rule, formulas, message))
150
+
151
+ for item in sorted(members - closure, key=str):
152
+ report("closure", "outside_closure", (item,),
153
+ f"{item} is not in the closure of {formula}.")
154
+
155
+ pairs_seen: set[frozenset[LTLFormula]] = set()
156
+ for item in sorted(closure, key=str):
157
+ opposite = complement(item)
158
+ pair = frozenset((item, opposite))
159
+ if pair not in pairs_seen:
160
+ pairs_seen.add(pair)
161
+ if item in members and opposite in members:
162
+ report("propositional_consistency", "contradiction", (item, opposite),
163
+ f"Both {item} and its complement {opposite} are included.")
164
+ elif item not in members and opposite not in members:
165
+ report("maximality", "missing_choice", (item, opposite),
166
+ f"Neither {item} nor its complement {opposite} is included; include one.")
167
+
168
+ if isinstance(item, BooleanConstant) and item.value and item not in members:
169
+ report("propositional_consistency", "true_required", (item,),
170
+ "true belongs to the closure and must be included.")
171
+ elif isinstance(item, And):
172
+ operands_present = item.left in members and item.right in members
173
+ if (item in members) != operands_present:
174
+ report("propositional_consistency", "conjunction", (item, item.left, item.right),
175
+ f"{item} must be included if and only if both operands "
176
+ f"({item.left}) and ({item.right}) are included.")
177
+ elif isinstance(item, Until):
178
+ if item.right in members and item not in members:
179
+ report("local_consistency", "until_fulfilled", (item, item.right),
180
+ f"{item.right} is included, so {item} must be included.")
181
+ if item in members and item.right not in members and item.left not in members:
182
+ report("local_consistency", "until_pending", (item, item.left, item.right),
183
+ f"{item} is included but {item.right} is absent, "
184
+ f"so {item.left} must be included.")
185
+
186
+ return ElementarySetResult(formula, original, closure, tuple(violations))
187
+
188
+
189
+ def _validate_elementary_sets(
190
+ formula: LTLFormula, elementary_sets: Iterable[Iterable[LTLFormula]],
191
+ ) -> tuple[frozenset[LTLFormula], tuple[frozenset[LTLFormula], ...]]:
192
+ """Validate and freeze supplied states without checking collection completeness.
193
+
194
+ Return the formula's closure and the states in input order. Simplify the
195
+ equivalent spellings accepted by the checker before detecting duplicates,
196
+ so every zero-based state position identifies a distinct elementary set.
197
+ """
198
+ closure = check_elementary_set(formula, ()).closure
199
+ states = []
200
+ seen: dict[frozenset[LTLFormula], int] = {}
201
+ for index, candidate in enumerate(elementary_sets):
202
+ checked = check_elementary_set(formula, candidate)
203
+ if not checked.is_elementary:
204
+ reasons = "; ".join(violation.message for violation in checked.violations)
205
+ raise ValueError(f"B{index + 1} is not an elementary set: {reasons}")
206
+ state = frozenset(normalize_ltl(node) for node in checked.candidate)
207
+ if state in seen:
208
+ raise ValueError(f"B{index + 1} duplicates elementary set B{seen[state] + 1}")
209
+ seen[state] = index
210
+ states.append(state)
211
+ return closure, tuple(states)
212
+
213
+
214
+ def check_elementary_set_collection(
215
+ formula: LTLFormula, elementary_sets: Iterable[Iterable[LTLFormula]],
216
+ ) -> ElementarySetCollectionResult:
217
+ """Report invalid, repeated, and missing states in a computed solution.
218
+
219
+ ``formula`` must already be normalized. Check every submitted state using
220
+ ``check_elementary_set``, retaining its original formulas and all violations.
221
+ Valid states are compared after simplifying double negations and negated
222
+ constants. Invalid states do not count toward coverage of required states.
223
+ Unlike the raising validator, this returns all mathematical errors together
224
+ so callers can give feedback on a student's full submission.
225
+
226
+ Completeness checking recomputes the entire elementary-set enumeration and
227
+ can take exponential time and space. Component construction does not invoke
228
+ this check. A full collection includes states excluding the input formula.
229
+
230
+ Returns:
231
+ Immutable feedback with one individual result per submitted state,
232
+ zero-based duplicate indices, and all missing states in enumeration order.
233
+
234
+ Raises:
235
+ TypeError: If the formula or a candidate member has the wrong type.
236
+ ValueError: If the input formula is not normalized. Invalid mathematical
237
+ solutions are reported in the result rather than raising an error.
238
+ """
239
+ # Enumeration imports the individual checker, so load it only for completeness.
240
+ from .elementary_set_enumeration import enumerate_elementary_sets
241
+
242
+ check_elementary_set(formula, ())
243
+ results = tuple(check_elementary_set(formula, candidate) for candidate in elementary_sets)
244
+ seen: dict[frozenset[LTLFormula], int] = {}
245
+ duplicates = []
246
+ for index, result in enumerate(results):
247
+ if not result.is_elementary:
248
+ continue
249
+ state = frozenset(normalize_ltl(node) for node in result.candidate)
250
+ if state in seen:
251
+ duplicates.append((seen[state], index))
252
+ else:
253
+ seen[state] = index
254
+ expected = enumerate_elementary_sets(formula).elementary_sets
255
+ missing = tuple(state for state in expected if state not in seen)
256
+ return ElementarySetCollectionResult(formula, results, tuple(duplicates), missing)
257
+
258
+
259
+ def validate_elementary_set_collection(
260
+ formula: LTLFormula, elementary_sets: Iterable[Iterable[LTLFormula]],
261
+ ) -> tuple[frozenset[LTLFormula], ...]:
262
+ """Require exactly all elementary sets over a normalized formula's closure.
263
+
264
+ This is the raising counterpart of ``check_elementary_set_collection``.
265
+ It recomputes the full elementary-set enumeration and can take exponential
266
+ time and space. For student feedback, use the checker to inspect individual
267
+ violations, duplicate positions, and missing states without raising.
268
+
269
+ Args:
270
+ formula: Formula already normalized by ``normalize_ltl``.
271
+ elementary_sets: Iterable of states containing formula objects. All
272
+ elementary sets are required, including those excluding ``formula``.
273
+ Double negations and negated constants are simplified as in the
274
+ individual checker. Supply a list or tuple for a predictable order.
275
+
276
+ Returns:
277
+ The validated states as frozensets in supplied order, allowing reuse
278
+ even when the original input was a generator. This tuple can be passed
279
+ directly to ``compute_transition_relation(formula, states)``.
280
+
281
+ Raises:
282
+ TypeError: If the formula or a state member has the wrong type.
283
+ ValueError: If the formula is not normalized, a state is not elementary,
284
+ states are duplicated after simplification, or any state is missing.
285
+ An incomplete collection's error includes a count and an example.
286
+ """
287
+ result = check_elementary_set_collection(formula, elementary_sets)
288
+ errors = []
289
+ for index, state_result in enumerate(result.state_results):
290
+ if not state_result.is_elementary:
291
+ reasons = "; ".join(violation.message for violation in state_result.violations)
292
+ errors.append(f"B{index + 1} is not an elementary set: {reasons}")
293
+ for first, repeated in result.duplicate_indices:
294
+ errors.append(f"B{repeated + 1} duplicates elementary set B{first + 1}")
295
+ if result.missing_sets:
296
+ example = ", ".join(sorted(map(str, result.missing_sets[0])))
297
+ noun = "elementary set" if len(result.missing_sets) == 1 else "elementary sets"
298
+ errors.append(
299
+ f"Incomplete elementary-set collection: missing {len(result.missing_sets)} "
300
+ f"{noun} (for example, {{{example}}})"
301
+ )
302
+ if errors:
303
+ raise ValueError(". ".join(errors))
304
+ return tuple(frozenset(normalize_ltl(node) for node in state_result.candidate)
305
+ for state_result in result.state_results)
306
+
307
+
308
+ __all__ = [
309
+ "ElementarySetResult", "ElementarySetViolation", "check_elementary_set",
310
+ "ElementarySetCollectionResult", "check_elementary_set_collection",
311
+ "validate_elementary_set_collection",
312
+ ]