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,535 @@
1
+ """A mutable, typed representation of a labelled transition system.
2
+
3
+ A transition system is the tuple ``(S, Act, →, I, AP, L)``: states, actions,
4
+ the transition relation, initial states, atomic propositions, and a state
5
+ labelling function, respectively.
6
+ """
7
+ from __future__ import annotations
8
+ from collections.abc import Iterable, Iterator
9
+ from typing import Generic, Hashable, NamedTuple, TypeVar, Self, Mapping
10
+
11
+ State = TypeVar("State", bound=Hashable)
12
+ Action = TypeVar("Action", bound=Hashable)
13
+ AtomicProposition = TypeVar("AtomicProposition", bound=Hashable)
14
+
15
+ __all__ = ["Action", "AtomicProposition", "State", "Transition", "TransitionSystem"]
16
+
17
+
18
+ class Transition(NamedTuple, Generic[State, Action]):
19
+ """A member of the transition relation: ``source --action--> target``."""
20
+
21
+ source: State
22
+ action: Action
23
+ target: State
24
+
25
+
26
+ class TransitionSystem(Generic[State, Action, AtomicProposition]):
27
+ """A mutable labelled transition system.
28
+
29
+ Type parameters represent hashable state, action, and atomic proposition
30
+ values. Collection properties return immutable ``frozenset`` snapshots;
31
+ use the supplied mutation methods to change the system.
32
+
33
+ To construct a TS, use :meth:`from_components` when the formal tuple's components are already
34
+ available, or :meth:`from_edges` to create a TS based on a graph structure where all transitions share an action
35
+
36
+ Note that `None` is reserved and cannot be used for actions.
37
+ """
38
+
39
+ def __init__(self) -> None:
40
+ """Create an empty transition system."""
41
+ self._states: set[State] = set()
42
+ self._actions: set[Action] = set()
43
+ self._transitions: dict[State, dict[Action, set[State]]] = {}
44
+ self._initial_states: set[State] = set()
45
+ self._atomic_propositions: set[AtomicProposition] = set()
46
+ self._labels: dict[State, set[AtomicProposition]] = {}
47
+
48
+ @staticmethod
49
+ def _validate_action(action: Action) -> None:
50
+ """Reject the sentinel used for unfiltered ``pre`` and ``post`` queries."""
51
+ if action is None:
52
+ raise ValueError("None cannot be used as an action")
53
+
54
+ @property
55
+ def states(self) -> frozenset[State]:
56
+ """Return the state set ``S``."""
57
+ return frozenset(self._states)
58
+
59
+ @property
60
+ def actions(self) -> frozenset[Action]:
61
+ """Return the action set ``Act``."""
62
+ return frozenset(self._actions)
63
+
64
+ @property
65
+ def initial_states(self) -> frozenset[State]:
66
+ """Return the initial-state set ``I``."""
67
+ return frozenset(self._initial_states)
68
+
69
+ @property
70
+ def atomic_propositions(self) -> frozenset[AtomicProposition]:
71
+ """Return the atomic-proposition set ``AP``."""
72
+ return frozenset(self._atomic_propositions)
73
+
74
+ def add_state(
75
+ self,
76
+ state: State,
77
+ *,
78
+ initial: bool = False,
79
+ labels: Iterable[AtomicProposition] = (),
80
+ ) -> None:
81
+ """Add ``state`` with optional initial status and labels.
82
+
83
+ The supplied labels are added to ``AP`` if necessary.
84
+ Raises ``ValueError`` if the state is already present.
85
+ """
86
+ if state in self._states:
87
+ raise ValueError(f"State {state!r} already exists")
88
+
89
+ state_labels = set(labels)
90
+
91
+ self._states.add(state)
92
+ self._labels[state] = state_labels
93
+ self._transitions[state] = {}
94
+
95
+ self._atomic_propositions.update(state_labels)
96
+
97
+ if initial:
98
+ self._initial_states.add(state)
99
+
100
+ def add_transition(
101
+ self,
102
+ source: State,
103
+ action: Action,
104
+ target: State,
105
+ ) -> None:
106
+ """Add the transition ``source --action--> target``.
107
+
108
+ Endpoints must already be states. The action is added to ``Act`` if
109
+ necessary. Raises ``ValueError`` for an unknown endpoint.
110
+ """
111
+ if source not in self._states:
112
+ raise ValueError(f"Unknown source state {source!r}")
113
+
114
+ if target not in self._states:
115
+ raise ValueError(f"Unknown target state {target!r}")
116
+
117
+ self._validate_action(action)
118
+ self._actions.add(action)
119
+
120
+ self._transitions[source].setdefault(action, set()).add(target)
121
+
122
+ def add_action(self, action: Action) -> None:
123
+ """Add an action to ``Act`` without adding a transition."""
124
+ self._validate_action(action)
125
+ self._actions.add(action)
126
+
127
+ def post(
128
+ self,
129
+ state: State,
130
+ action: Action | None = None,
131
+ ) -> frozenset[State]:
132
+ """Return successors of ``state``, optionally restricted to successors after ``action``.
133
+
134
+ Raises ``ValueError`` if the state is unknown.
135
+ """
136
+ if state not in self._states:
137
+ raise ValueError(f"Unknown state {state!r}")
138
+
139
+ if action is not None:
140
+ return frozenset(self._transitions[state].get(action, ()))
141
+ successors: set[State] = set()
142
+ for targets in self._transitions[state].values():
143
+ successors.update(targets)
144
+
145
+ return frozenset(successors)
146
+
147
+ def pre(
148
+ self,
149
+ state: State,
150
+ action: Action | None = None,
151
+ ) -> frozenset[State]:
152
+ """Return predecessors of ``state``, optionally restricted to predecessors before ``action``.
153
+
154
+ Raises ``ValueError`` if the state is unknown.
155
+ """
156
+ if state not in self._states:
157
+ raise ValueError(f"Unknown state {state!r}")
158
+
159
+ result: set[State] = set()
160
+
161
+ for source, transitions_by_action in self._transitions.items():
162
+ if action is None:
163
+ if any(
164
+ state in targets
165
+ for targets in transitions_by_action.values()
166
+ ):
167
+ result.add(source)
168
+
169
+ else:
170
+ if state in transitions_by_action.get(action, set()):
171
+ result.add(source)
172
+
173
+ return frozenset(result)
174
+
175
+ def add_atomic_proposition(
176
+ self,
177
+ proposition: AtomicProposition,
178
+ ) -> None:
179
+ """Add a proposition to ``AP`` without labelling a state with it."""
180
+ self._atomic_propositions.add(proposition)
181
+
182
+ def labels(self, state: State) -> frozenset[AtomicProposition]:
183
+ """Return ``L(state)``, the propositions that hold in ``state``."""
184
+ if state not in self._states:
185
+ raise ValueError(f"Unknown state {state!r}")
186
+
187
+ return frozenset(self._labels[state])
188
+
189
+ def add_label(
190
+ self,
191
+ state: State,
192
+ proposition: AtomicProposition,
193
+ ) -> None:
194
+ """Make ``proposition`` hold in ``state`` and add it to ``AP``."""
195
+ if state not in self._states:
196
+ raise ValueError(f"Unknown state {state!r}")
197
+
198
+ self._atomic_propositions.add(proposition)
199
+ self._labels[state].add(proposition)
200
+
201
+ def remove_label(
202
+ self,
203
+ state: State,
204
+ proposition: AtomicProposition,
205
+ ) -> None:
206
+ """Remove a proposition from a state label, if present.
207
+
208
+ The proposition remains declared in ``AP``.
209
+ """
210
+ if state not in self._states:
211
+ raise ValueError(f"Unknown state {state!r}")
212
+
213
+ self._labels[state].discard(proposition)
214
+
215
+ def set_labels(
216
+ self,
217
+ state: State,
218
+ labels: Iterable[AtomicProposition],
219
+ ) -> None:
220
+ """Replace a state's labels, adding the supplied propositions to ``AP``."""
221
+ if state not in self._states:
222
+ raise ValueError(f"Unknown state {state!r}")
223
+
224
+ labels = set(labels)
225
+
226
+ self._atomic_propositions.update(labels)
227
+ self._labels[state] = labels
228
+
229
+ def set_initial(
230
+ self,
231
+ state: State,
232
+ initial: bool = True,
233
+ ) -> None:
234
+ """Set or clear membership of ``state`` in the initial-state set ``I``."""
235
+ if state not in self._states:
236
+ raise ValueError(f"Unknown state {state!r}")
237
+
238
+ if initial:
239
+ self._initial_states.add(state)
240
+ else:
241
+ self._initial_states.discard(state)
242
+
243
+ @property
244
+ def terminal_states(self) -> frozenset[State]:
245
+ """Return states without outgoing transitions."""
246
+ return frozenset(
247
+ state
248
+ for state in self._states
249
+ if not self.post(state)
250
+ )
251
+
252
+ def is_non_blocking(self) -> bool:
253
+ """Return whether every state has at least one outgoing transition.
254
+
255
+ An empty system is non-blocking by vacuous truth.
256
+ """
257
+ return all(self.post(state) for state in self._states)
258
+
259
+ def transitions(self) -> Iterator[Transition[State, Action]]:
260
+ """Iterate over each distinct member of the transition relation ``→``."""
261
+ for source, actions in self._transitions.items():
262
+ for action, targets in actions.items():
263
+ for target in targets:
264
+ yield Transition(source, action, target)
265
+
266
+ def has_transition(
267
+ self,
268
+ source: State,
269
+ action: Action,
270
+ target: State,
271
+ ) -> bool:
272
+ """Return whether ``source --action--> target`` belongs to ``→``."""
273
+ return (
274
+ source in self._transitions
275
+ and target in self._transitions[source].get(action, ())
276
+ )
277
+
278
+ def enabled_actions(
279
+ self,
280
+ state: State,
281
+ ) -> frozenset[Action]:
282
+ """Return actions with at least one outgoing transition from ``state``."""
283
+ if state not in self._states:
284
+ raise ValueError(f"Unknown state {state!r}")
285
+
286
+ return frozenset(
287
+ action
288
+ for action, targets in self._transitions[state].items()
289
+ if targets
290
+ )
291
+
292
+ def remove_transition(
293
+ self,
294
+ source: State,
295
+ action: Action,
296
+ target: State,
297
+ ) -> None:
298
+ """Remove one existing transition from ``→``.
299
+
300
+ Raises ``ValueError`` for unknown endpoints or a missing transition.
301
+ The action stays in ``Act`` even if this removes its final transition.
302
+ """
303
+ if source not in self._states:
304
+ raise ValueError(f"Unknown source state {source!r}")
305
+
306
+ if target not in self._states:
307
+ raise ValueError(f"Unknown target state {target!r}")
308
+
309
+ targets = self._transitions[source].get(action)
310
+
311
+ if targets is None or target not in targets:
312
+ raise ValueError(
313
+ f"Transition ({source!r}, {action!r}, {target!r}) does not exist"
314
+ )
315
+
316
+ targets.remove(target)
317
+
318
+ # Don't keep an empty action entry around.
319
+ if not targets:
320
+ del self._transitions[source][action]
321
+
322
+ def remove_state(self, state: State) -> None:
323
+ """Remove ``state`` and all incoming/outgoing transitions.
324
+
325
+ Its labels and initial-state membership are removed. Actions and atomic
326
+ propositions remain declared.
327
+ """
328
+ if state not in self._states:
329
+ raise ValueError(f"Unknown state {state!r}")
330
+
331
+ # Remove all incoming transitions.
332
+ for source in self._states:
333
+ if source == state:
334
+ continue
335
+
336
+ actions_to_remove: list[Action] = []
337
+
338
+ for action, targets in self._transitions[source].items():
339
+ targets.discard(state)
340
+
341
+ if not targets:
342
+ actions_to_remove.append(action)
343
+
344
+ for action in actions_to_remove:
345
+ del self._transitions[source][action]
346
+
347
+ # Remove the state itself and all outgoing transitions.
348
+ del self._transitions[state]
349
+ del self._labels[state]
350
+
351
+ self._initial_states.discard(state)
352
+ self._states.remove(state)
353
+
354
+ def remove_action(self, action: Action) -> None:
355
+ """Remove an action and all transitions that use it."""
356
+ if action not in self._actions:
357
+ raise ValueError(f"Unknown action {action!r}")
358
+
359
+ for transitions_by_action in self._transitions.values():
360
+ transitions_by_action.pop(action, None)
361
+
362
+ self._actions.remove(action)
363
+
364
+ def remove_atomic_proposition(
365
+ self,
366
+ proposition: AtomicProposition,
367
+ ) -> None:
368
+ """Remove a proposition from ``AP``. Also removes the proposition as a label for every state."""
369
+ if proposition not in self._atomic_propositions:
370
+ raise ValueError(
371
+ f"Unknown atomic proposition {proposition!r}"
372
+ )
373
+
374
+ for labels in self._labels.values():
375
+ labels.discard(proposition)
376
+
377
+ self._atomic_propositions.remove(proposition)
378
+
379
+ def induced_subsystem(self, states: Iterable[State]) -> TransitionSystem[State, Action, AtomicProposition]:
380
+ """Return a new system induced by the selected states.
381
+
382
+ Retain exactly the transitions whose endpoints are both selected,
383
+ the selected states' labels, and their initial-state membership.
384
+ Actions and atomic propositions remain declared, even if unused.
385
+ An empty selection yields a system with no states or transitions.
386
+
387
+ Raises ``ValueError`` if any selected state is unknown. The returned
388
+ system has independent collections; state, action, and proposition
389
+ values themselves are shared.
390
+ """
391
+ states = set(states)
392
+ unknown = states - self._states
393
+ if unknown:
394
+ raise ValueError(f"Unknown states: {unknown!r}")
395
+
396
+ return self.from_components(
397
+ states=states,
398
+ actions=self._actions,
399
+ transitions=(
400
+ transition
401
+ for transition in self.transitions()
402
+ if transition.source in states and transition.target in states
403
+ ),
404
+ initial_states=self._initial_states & states,
405
+ atomic_propositions=self._atomic_propositions,
406
+ labels={state: self._labels[state] for state in states},
407
+ )
408
+
409
+ @classmethod
410
+ def from_components(
411
+ cls,
412
+ *,
413
+ states: Iterable[State],
414
+ actions: Iterable[Action],
415
+ transitions: Iterable[tuple[State, Action, State]],
416
+ initial_states: Iterable[State] = (),
417
+ atomic_propositions: Iterable[AtomicProposition] = (),
418
+ labels: Mapping[State, Iterable[AtomicProposition]] | None = None,
419
+ ) -> Self:
420
+ """Construct a system from the explicit components of its formal tuple.
421
+
422
+ The declared states, actions, and propositions form the sets.
423
+ Initial states, transition endpoints/actions, and labels are validated
424
+ against them; missing state labels default to the empty set. In contrast
425
+ to the incremental mutation methods, this constructor does not infer
426
+ undeclared actions or propositions from transitions and labels.
427
+ """
428
+ states = set(states)
429
+ actions = set(actions)
430
+ transitions = set(transitions)
431
+ initial_states = set(initial_states)
432
+ atomic_propositions = set(atomic_propositions)
433
+ labelling_function = {
434
+ state: set(state_labels)
435
+ for state, state_labels in (labels or {}).items()
436
+ }
437
+
438
+ if None in actions:
439
+ raise ValueError("None cannot be used as an action")
440
+
441
+ # Validate input and catch mistakes explicitly
442
+ if not initial_states <= states:
443
+ unknown = initial_states - states
444
+ raise ValueError(
445
+ f"Unknown initial states: {unknown!r}"
446
+ )
447
+
448
+ unknown_label_states = set(labelling_function) - states
449
+
450
+ if unknown_label_states:
451
+ raise ValueError(
452
+ f"Labels specified for unknown states: "
453
+ f"{unknown_label_states!r}"
454
+ )
455
+
456
+ for state, state_labels in labelling_function.items():
457
+ unknown_propositions = state_labels - atomic_propositions
458
+ if unknown_propositions:
459
+ raise ValueError(
460
+ f"State {state!r} uses unknown atomic "
461
+ f"propositions: {unknown_propositions!r}"
462
+ )
463
+
464
+ for source, action, target in transitions:
465
+ if action is None:
466
+ raise ValueError("None cannot be used as an action")
467
+
468
+ if source not in states:
469
+ raise ValueError(
470
+ f"Unknown transition source: {source!r}"
471
+ )
472
+
473
+ if target not in states:
474
+ raise ValueError(
475
+ f"Unknown transition target: {target!r}"
476
+ )
477
+
478
+ if action not in actions:
479
+ raise ValueError(
480
+ f"Unknown transition action: {action!r}"
481
+ )
482
+
483
+ ts = cls()
484
+ # states
485
+ for state in states:
486
+ ts.add_state(
487
+ state,
488
+ labels=labelling_function.get(state, ()),
489
+ )
490
+
491
+ # actions
492
+ for action in actions:
493
+ ts.add_action(action)
494
+
495
+ # atomic propositions
496
+ for proposition in atomic_propositions:
497
+ ts.add_atomic_proposition(proposition)
498
+
499
+ # initial states
500
+ for state in initial_states:
501
+ ts.set_initial(state)
502
+
503
+ # transitions
504
+ for source, action, target in transitions:
505
+ ts.add_transition(source, action, target)
506
+
507
+ return ts
508
+
509
+ @classmethod
510
+ def from_edges(
511
+ cls,
512
+ *,
513
+ states: Iterable[State],
514
+ edges: Iterable[tuple[State, State]],
515
+ action: Action,
516
+ initial_states: Iterable[State] = (),
517
+ atomic_propositions: Iterable[AtomicProposition] = (),
518
+ labels: Mapping[State, Iterable[AtomicProposition]] | None = None,
519
+ ) -> Self:
520
+ """Construct a system from graph edges that all use one ``action``.
521
+
522
+ Each ``(source, target)`` edge becomes ``(source, action, target)``.
523
+ This is a shorthand for :meth:`from_components`.
524
+ """
525
+ return cls.from_components(
526
+ states=states,
527
+ actions={action},
528
+ transitions={
529
+ (source, action, target)
530
+ for source, target in edges
531
+ },
532
+ initial_states=initial_states,
533
+ atomic_propositions=atomic_propositions,
534
+ labels=labels,
535
+ )
mocha/py.typed ADDED
File without changes
@@ -0,0 +1,55 @@
1
+ """Graphviz visualisation helpers for transition systems and automata."""
2
+
3
+ from typing import Any
4
+
5
+ from .overlay import TransitionSystemOverlay
6
+
7
+ __all__ = [
8
+ "AcceptingStateShape",
9
+ "TransitionSystemOverlay",
10
+ "to_automaton_graphviz",
11
+ "to_graphviz",
12
+ "to_lasso_graphviz",
13
+ "visualise_invariant_step",
14
+ "visualise_invariant_result",
15
+ "visualise_persistence_counterexample",
16
+ "visualise_reachability_step",
17
+ "visualise_step",
18
+ ]
19
+
20
+
21
+ def __getattr__(name: str) -> Any:
22
+ """Load Graphviz-dependent rendering helpers only when they are requested."""
23
+ if name == "AcceptingStateShape":
24
+ from .automaton import AcceptingStateShape
25
+
26
+ return AcceptingStateShape
27
+ if name == "to_automaton_graphviz":
28
+ from .automaton import to_graphviz as to_automaton_graphviz
29
+
30
+ return to_automaton_graphviz
31
+ if name in {"to_graphviz", "to_lasso_graphviz", "visualise_step"}:
32
+ from .transition_system import to_graphviz, to_lasso_graphviz, visualise_step
33
+
34
+ return {
35
+ "to_graphviz": to_graphviz,
36
+ "to_lasso_graphviz": to_lasso_graphviz,
37
+ "visualise_step": visualise_step,
38
+ }[name]
39
+ if name == "visualise_persistence_counterexample":
40
+ from .persistence import visualise_persistence_counterexample
41
+
42
+ return visualise_persistence_counterexample
43
+ if name == "visualise_reachability_step":
44
+ from .reachability import visualise_reachability_step
45
+
46
+ return visualise_reachability_step
47
+ if name == "visualise_invariant_step":
48
+ from .invariance import visualise_invariant_step
49
+
50
+ return visualise_invariant_step
51
+ if name == "visualise_invariant_result":
52
+ from .invariance import visualise_invariant_result
53
+
54
+ return visualise_invariant_result
55
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")