Coverage for /home/marcofavorito/workfolder/pythomata/pythomata/simulator.py : 0%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2"""This module contains implements utilities to execute a finite automaton."""
3from abc import ABC, abstractmethod
4from typing import Generic, Set
6from pythomata.core import StateType, SymbolType, FiniteAutomaton
9class AbstractSimulator(Generic[StateType, SymbolType], ABC):
10 """An interface for a simulator of finite automata."""
12 @abstractmethod
13 def step(self, s: SymbolType) -> StateType:
14 """Make a transition, updating the current state of the simulator."""
16 @abstractmethod
17 def is_true(self) -> bool:
18 """Check if the simulator is in a final state."""
20 @abstractmethod
21 def is_failed(self) -> bool:
22 """Check if the simulator is failed (i.e. in an undefined state)."""
24 @abstractmethod
25 def reset(self) -> StateType:
26 """Reset the state of the simulator to its initial state."""
29class AutomatonSimulator(AbstractSimulator[Set[StateType], SymbolType]):
30 """A DFA simulator."""
32 def __init__(self, automaton: FiniteAutomaton):
33 """
34 Initialize a simulator for a finite automaton.
36 :param automaton: the automaton.
37 """
38 self._automaton = automaton
39 self._current_states = self._automaton.initial_states # type: Set[StateType]
41 @property
42 def automaton(self) -> FiniteAutomaton:
43 """Get the automaton."""
44 return self._automaton
46 @property
47 def cur_state(self) -> Set[StateType]:
48 """
49 Get the current states of the simulator.
51 :return: the index corresponding to the automaton state.
52 | If None, then the simulation is in a failure state.
53 """
54 return self._current_states
56 def step(self, symbol: SymbolType) -> Set[StateType]:
57 """Do a simulation step."""
58 next_macro_state = set() # type: Set[StateType]
59 for state in self.cur_state:
60 next_macro_state = next_macro_state.union(self.automaton.get_successors(state, symbol))
61 return next_macro_state
63 def is_true(self):
64 """Check whether the simulator is in an accepting state."""
65 return not self.is_failed() and any(s in self.automaton.final_states for s in self.cur_state)
67 def is_failed(self) -> bool:
68 """Check whether the simulator is in a failed state."""
69 return self.cur_state == set()
71 def reset(self) -> Set[StateType]:
72 """Reset the simulator."""
73 self._current_states = self.automaton.initial_states
74 return self.cur_state