Welcome to FAdo’s documentation¶
FAdo: Tools for Language Models Manipulation
Authors: Rogério Reis & Nelma Moreira
The support of transducers and all its operations, as well of Set Specifications, is a joint work with Stavros Konstantinidis (St. Mary’s University, Halifax, NS, Canada) (http://cs.smu.ca/~stavros/).
Contributions by
|
|
Page of the project: http://fado.dcc.fc.up.pt.
Version: 2.0.2
Copyright: 1999-2022 Rogério Reis & Nelma Moreira {rogerio.reis,nelma.moreira}@fc.up.pt
Faculdade de Ciências da Universidade do Porto
Centro de Matemática da Universidade do Porto
Licence:
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your Option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
What is FAdo?¶
The FAdo system aims to provide an open source extensible high-performance software library for the symbolic manipulation of automata and other models of computation.
To allow high-level programming with complex data structures, easy prototyping of algorithms, and portability (to use in computer grid systems for example), are its main features. Our main motivation is the theoretical and experimental research, but we have also in mind the construction of a pedagogical tool for teaching automata theory and formal languages.
Regular Languages¶
It currently includes most standard operations for the manipulation of regular languages. Regular languages can be represented by regular expressions (RegExp) or finite automata, among other formalisms. Finite automata may be deterministic (DFA), non-deterministic (NFA) or generalized (GFA). In FAdo these representations are implemented as Python classes.
Elementary regular languages operations as union, intersection, concatenation, complementation and reverse are implemented for each class. Also several combined operations are available for specific models.
Several conversions between these representations are implemented:
NFA -> DFA: subset construction
NFA -> RE: recursive method
GFA -> RE: state elimination, with possible choice of state orderings
RE -> NFA: Thompson method, Glushkov method, follow, Brzozowski, and partial derivatives.
For DFAs several minimization algorithms are available: Moore, Hopcroft, and some incremental algorithms. Brzozowski minimization is available for NFAs.
An algorithm for hyper-minimization of DFAs
Language equivalence of two DFAs can be determined by reducing their correspondent minimal DFA to a canonical form, or by the Hopcroft and Karp algorithm.
Enumeration of the first words of a language or all words of a given length (Cross Section)
Some support for the transition semigroups of DFAs
Finite Languages¶
Special methods for finite languages are available:
Construction of a ADFA (acyclic finite automata) from a set of words
Minimization of ADFAs
Several methods for ADFAs random generation
Methods for deterministic cover finite automata (DCFA)
Transducers¶
Several methods for transducers in standard form (SFT) are available:
Rational operations: union, inverse, reversal, composition, concatenation, Star
Test if a transducer is functional
Input intersection and Output intersection operations
Codes¶
A language property is a set of languages. Given a property specified by a transducer, several language tests are possible.
Satisfaction i.e. if a language satisfies the property
Maximality i.e. the language satisfies the property and is maximal
Properties implemented by transducers include: input preserving, input altering, trajectories, and fixed properties
Computation of the edit distance of a regular language, using input altering transducers
Module: Finite Automata (fa)¶
Finite automata manipulation.
Deterministic and non-deterministic automata manipulation, conversion and evaluation. .. Authors: Rogério Reis & Nelma Moreira .. This is part of FAdo project https://fado.dcc.fc.up.pt.
Classes¶
FA¶
- class FA[source]¶
- Base class for Finite Automata.
This is just an abstract class. Not to be used directly!!
- Variables
- addFinal(stateindex)[source]¶
A new state is added to the already defined set of final states.
- Parameters
stateindex (int) – index of the new final state.
- addSigma(sym)[source]¶
Adds a new symbol to the alphabet.
- Parameters
sym (str) – symbol to be added
- Raises
DFAepsilonRedefinition – if sym is Epsilon
Note
There is no problem with duplicate symbols because sigma is a Set.
No symbol Epsilon can be added.
- addState(name=None) int[source]¶
Adds a new state to an FA. If no name is given a new name is created.
- Parameters
name (
Object, optional) – Name of the state to be added.- Returns
Current number of states (the new state index).
- Return type
- Raises
DuplicateName – if a state with that name already exists
- countTransitions()[source]¶
Evaluates the size of FA transitionwise
- Returns
the number of transitions
- Return type
Changed in version 1.0.
- delFinal(st)[source]¶
Deletes a state from the final states list
- Parameters
st (int) – state to be marked as not final.
- deleteState(sti: int)[source]¶
Remove the given state and the transitions related with that state.
- Parameters
sti (int) – index of the state to be removed
- Raises
DFAstateUnknown – if state index does not exist
- dotFormat(size='20,20', filename=None, direction='LR', strict=False, maxlblsz=6, sep='\n') str[source]¶
A dot representation
- Parameters
- Returns
the dot representation
- Return type
New in version 0.9.6.
Changed in version 1.2.1.
- eliminateDeadName()[source]¶
Eliminates dead state name (common.DeadName) renaming the state
- Returns
self
- Return type
Attention
works inplace
New in version 1.2.
- initialP(state: int) bool[source]¶
Tests if a state is initial
- Parameters
state – state index
- Returns
is the state initial?
- Return type
- inputS(i)[source]¶
Input labels coming out of state i
- Parameters
i (int) – state
- Returns
set of input labels
- Return type
set of str
New in version 1.0.
- noBlankNames()[source]¶
Eliminates blank names
- Returns
self
- Return type
Attention
in place transformation
- renameState(st, name)[source]¶
Rename a given state.
Note
Deals gracefully both with int and str names in the case of name collision.
Attention
the object is modified in place
- renameStates(name_list=None)[source]¶
Renames all states using a new list of names.
- Parameters
name_list (list) – list of new names.
- Returns
self.
- Return type
- Raises
DFAerror – if provided list is too short.
Note
If no list of names is given, state indexes are used.
Attention
the object is modified in place
- reversal()[source]¶
Returns a NFA that recognizes the reversal of the language
- Returns
NFA recognizing reversal language
- Return type
- setFinal(statelist)[source]¶
Sets the final states of the FA
Caution
Erases any previous definition of the final state set.
- setInitial(stateindex)[source]¶
Sets the initial state of a FA
- Parameters
stateindex (int) – index of the initial state.
- stateIndex(name, auto_create=False)[source]¶
Index of given state name.
- Parameters
- Returns
state index
- Return type
- Raises
DFAstateUnknown – if the state name is unknown and autoCreate==False
Note
Replaces stateName
Note
If the state name is not known and flag is set creates it on the fly
New in version 1.0.
- stateName(name, auto_create=False)[source]¶
Index of given state name.
- Parameters
- Returns
state index
- Return type
- Raises
DFAstateUnknown – if the state name is unknown and autoCreate==False
Deprecated since version 1.0: Use:
stateIndex()insteadDeprecated since version 1.0: Use the stateIndex() function instead
- class SemiDFA[source]¶
Class of automata without initial or final states
- Variables
- static dotDrawTransition(st1: str, lbl1: str, st2, sep='\n') str[source]¶
Draw a transition in dot format
OFA¶
- class OFA[source]¶
Base class for one-way automata
- Variables

- acyclicP(strict=True)[source]¶
Checks if the FA is acyclic
- Parameters
strict (bool) – if not True loops are allowed
- Returns: True if the FA is acyclic
bool: True if the FA is acyclic
- abstract deleteStates(del_states)[source]¶
To be implemented below
- Parameters
del_states (list) – states to be deleted
- dump()[source]¶
Returns a python representation of the object
- Returns
the python representation (Tags,States,sigma,delta,Initial,Final)
- Return type
- eliminateStout(st)[source]¶
Eliminate all transitions outgoing from a given state
- Parameters
st (int) – the state index to loose all outgoing transitions
Attention
performs in place alteration of the automata
New in version 0.9.6.
- minimalBrzozowski()[source]¶
Constructs the equivalent minimal DFA using Brzozowski’s algorithm
- Returns
equivalent minimal DFA
- Return type
- topoSort()[source]¶
Topological order for the FA
- Returns
List of state indexes
- Return type
Note
self loops are taken in consideration
DFA¶
- class DFA[source]¶
Class for Deterministic Finite Automata.
- Variables

- HKeqP(other, strict=True)[source]¶
Tests the DFA’s equivalence using Hopcroft and Karp’s state equivalence algorithm
- Parameters
other –
strict –
- Returns
bool
See also
J. E. Hopcroft and r. M. Karp.A Linear Algorithm for Testing Equivalence of Finite Automata.TR 71–114. U. California. 1971
Attention
The automaton must be complete.
- MyhillNerodePartition()[source]¶
Myhill-Nerode partition, Moore’s way
New in version 1.3.5.
Attention
No state should be named with DeadName. This states is removed from the obtained partition.
See also
F.Bassino, J.David and C.Nicaud, On the Average Complexity of Moores’s State Minimization Algorihm, Symposium on Theoretical Aspects of Computer Science
- aEquiv()[source]¶
Computes almost equivalence, used by hyperMinimial
- Returns
partition of states
- Return type
Note
may be optimized to avoid dupped
- addTransition(sti1, sym, sti2)[source]¶
Adds a new transition from
sti1tosti2consuming symbolsym.
- complete(dead='DeaD')[source]¶
Transforms the automata into a complete one. If sigma is empty nothing is done.
Note
Adds a dead state (if necessary) so that any word can be processed with the automata. The new state is named
dead, so this name should never be used for other purposes.Attention
The object is modified in place.
Changed in version 1.0.
- completeMinimal()[source]¶
Completes a DFA assuming it is a minimal and avoiding de destruction of its minimality If the automaton is not complete, all the non final states are checked to see if tey are not already a dead state. Only in the negative case a new (dead) state is added to the automaton.
- Return type
Attention
The object is modified in place. If the alphabet is empty nothing is done
- computeKernel()[source]¶
The Kernel of a ICDFA is the set of states that accept a non finite language.
- Returns
triple (comp, center , mark) where comp are the strongly connected components, center the set of center states and mark the kernel states
- Return type
- concat(fa2, strict=False)[source]¶
Concatenation of two DFAs. If DFAs are not complete, they are completed.
- concatI(fa2, strict=False)[source]¶
Concatenation of two DFAs.
- Parameters
- Returns
the result of the concatenation
- Return type
- Raises
DFAdifferentSigma – if alphabet are not equal
New in version 0.9.5.
Note
this is to be used with non complete DFAs
- delTransition(sti1, sym, sti2, _no_check=False)[source]¶
Remove a transition if existing and perform cleanup on the transition function’s internal data structure.
- Parameters
Note
Unused alphabet symbols will be discarded from sigma.
- deleteStates(del_states)[source]¶
Delete given iterable collection of states from the automaton.
- Parameters
del_states – collection of int representing states
Note
in-place action
Note
delta function will always be rebuilt, regardless of whether the states list to remove is a suffix, or a sublist, of the automaton’s states list.
- dist()[source]¶
Evaluate the distinguishability language for a DFA
- Return type
See also
Cezar Câmpeanu, Nelma Moreira, Rogério Reis: The distinguishability operation on regular languages. NCMA 2014: 85-100
New in version 0.9.8.
- distMin()[source]¶
Evaluates the list of minimal words that distinguish each pair of states
- Returns
set of minimal distinguishing words
- Return type
New in version 0.9.8.
Attention
If the DFA is not minimal, the method loops forever
- distR()[source]¶
Evaluate the right distinguishability language for a DFA
- Return type
- ..seealso:: Cezar Câmpeanu, Nelma Moreira, Rogério Reis:
The distinguishability operation on regular languages. NCMA 2014: 85-100
- distRMin()[source]¶
Compute distRMin for DFA
:rtype FL
- ..seealso:: Cezar Câmpeanu, Nelma Moreira, Rogério Reis:
The distinguishability operation on regular languages. NCMA 2014: 85-100
- distTS()[source]¶
Evaluate the two-sided distinguishability language for a DFA
- Return type
- ..seealso:: Cezar Câmpeanu, Nelma Moreira, Rogério Reis:
The distinguishability operation on regular languages. NCMA 2014: 85-100
- enumDFA(n=None)[source]¶
returns the set of words of words of length up to n accepted by self :param int n: highest length or all words if finite
- Return type
list of strings or None
- equal(other)[source]¶
Verify if the two automata are equivalent. Both are verified to be minimum and complete, and then one is matched against the other… Doesn’t destroy either dfa…
- evalSymbolI(init, sym)[source]¶
Returns the state reached from a given state.
- Parameters
init (init) – current state
sym (str) – symbol to be consumed
- Returns
reached state or -1
- Return type
set of int
- Raises
DFAsymbolUnknown – if symbol not in alphabet
New in version 0.9.5.
Note
this is to be used with non complete DFAs
- evalSymbolL(ls, sym)[source]¶
Returns the set of states reached from a given set of states through a given symbol
- Parameters
ls (set of int) – set of states indexes
sym (str) – symbol to be read
- Returns
set of reached states
- Return type
set of int
- evalSymbolLI(ls, sym)[source]¶
Returns the set of states reached from a given set of states through a given symbol
- Parameters
ls (set of int) – set of current states
sym (str) – symbol to be consumed
- Returns
set of reached states
- Return type
set of int
New in version 0.9.5.
Note
this is to be used with non complete DFAs
- finalCompP(s)[source]¶
Verifies if there is a final state in strongly connected component containing
s.- Parameters
s (int) – state
- Returns
1 if yes, 0 if no
- hasTrapStateP()[source]¶
Tests if the automaton has a dead trap state
- Return type
New in version 1.1.
- hyperMinimal(strict=False)[source]¶
Hyperminization of a minimal DFA
- Parameters
strict (bool) – if strict=True it first minimizes the DFA
- Returns
an hyperminimal DFA
- Return type
See also
M. Holzer and A. Maletti, An nlogn Algorithm for Hyper-Minimizing a (Minimized) Deterministic Automata, TCS 411(38-39): 3404-3413 (2010)
Note
if strict=False minimality is assumed
- initialComp()[source]¶
Evaluates the connected component starting at the initial state.
- Returns
list of state indexes in the component
- Return type
list of int
- initialSet()[source]¶
The set of initial states
- Returns
the set of the initial states
- Return type
set of States
- joinStates(lst)[source]¶
Merge a list of states.
- Parameters
lst (iterable of state indexes.) – set of equivalent states
- makeReversible()[source]¶
Make a DFA reversible (if possible)
See also
M.Holzer, s. Jakobi, M. Kutrib ‘Minimal Reversible Deterministic Finite Automata’
- Return type
- markNonEquivalent(s1, s2, data)[source]¶
Mark states with indexes s1 and s2 in given map as non equivalent states. If any back-effects exist, apply them.
- mergeStates(f, t)[source]¶
Merge the first given state into the second. If the first state is an initial state the second becomes the initial state.
Attention
It is up to the caller to remove the disconnected state. This can be achieved with
`trim().
- minimal(method='minimalHopcroft', complete=True)[source]¶
Evaluates the equivalent minimal complete DFA
- minimalHopcroft()[source]¶
Evaluates the equivalent minimal complete DFA using Hopcroft algorithm
- Returns
equivalent minimal DFA
- Return type
See also
John Hopcroft,An n log{n} algorithm for minimizing states in a finite automaton.The Theory of Machines and Computations.AP. 1971
- minimalIncremental(minimal_test=False)[source]¶
Minimizes the DFA with an incremental method using the Union-Find algorithm and memoized non-equivalence intermediate results
- Parameters
minimal_test (bool) – starts by verifying that the automaton is not minimal?
- Returns
equivalent minimal DFA
- Return type
See also
M. Almeida and N. Moreira and and r. Reis.Incremental DFA minimisation. CIAA 2010. LNCS 6482. pp 39-48. 2010
- minimalMoore()[source]¶
Evaluates the equivalent minimal automata with Moore’s algorithm
See also
John E. Hopcroft and Jeffrey D. Ullman, Introduction to Automata Theory, Languages, and Computation, AW, 1979
- Returns
minimal complete DFA
- Return type
- minimalMooreSq()[source]¶
Evaluates the equivalent minimal complete DFA using Moore’s (quadratic) algorithm
See also
John E. Hopcroft and Jeffrey D. Ullman, Introduction to Automata Theory, Languages, and Computation, AW, 1979
- Returns
equivalent minimal DFA
- Return type
- minimalMooreSqP()[source]¶
Tests if a DFA is minimal using the quadratic version of Moore’s algorithm
- Return type
- minimalNCompleteP()[source]¶
Tests if a non necessarely complete DFA is minimal, i.e., if the DFA is non complete, if the minimal complete has only one more state.
- Returns
True if not minimal
- Return type
Attention
obsolete: use minimalP
- minimalNotEquivP()[source]¶
Tests if the DFA is minimal by computing the set of distinguishable (not equivalent) pairs of states
- Return type
- minimalP(method='minimalMooreSq')[source]¶
Tests if the DFA is minimal
- Parameters
method – the minimization algorithm to be used
- Return type
..note: if DFA non complete test if complete minimal has one more state
- minimalWatson(test_only=False)[source]¶
Evaluates the equivalent minimal complete DFA using Waton’s incremental algorithm
- Parameters
test_only (bool) – is it only to test minimality
- Returns
equivalent minimal DFA
- Return type
- Raises
DFAnotComplete – if automaton is not complete
- ..attention::
automaton must be complete
- minimalWatsonP()[source]¶
Tests if a DFA is minimal using Watson’s incremental algorithm
- Return type
- orderedStrConnComponents()[source]¶
Topological ordered list of strong components
New in version 1.3.3.
- Return type
- pairGraph()[source]¶
Returns pair graph
- Return type
DiGraphVM
See also
A graph theoretic approach to automata minimality. Antonio Restivo and Roberto Vaglica. Theoretical Computer Science, 429 (2012) 282-291. doi:10.1016/j.tcs.2011.12.049 Theoretical Computer Science, 2012 vol. 429 (C) pp. 282-291. http://dx.doi.org/10.1016/j.tcs.2011.12.049
- print_data(data)[source]¶
Prints table of compatibility (in the context of the minimalization algorithm).
- Parameters
data – data to print
- product(other)[source]¶
Returns a DFA resulting of the simultaneous execution of two DFA. No final states set.
Note
this is a fast version of the method. The resulting state names are not meaningfull.
- Parameters
other – the other DFA
- Return type
- productSlow(other, complete=True)[source]¶
Returns a DFA resulting of the simultaneous execution of two DFA. No final states set.
Note
this is a slow implementation for those that need meaningfull state names
New in version 1.3.3.
- reorder(dicti)[source]¶
Reorders states according to given dictionary. Given a dictionary (not necessarily complete)… reorders states accordingly.
- Parameters
dicti (dict) – reorder dictionary
- reverseTransitions(rev)[source]¶
Evaluate reverse transition function.
- Parameters
rev (DFA) – DFA in which the reverse function will be stored
- sSemigroup()[source]¶
Evaluation of the syntactic semigroup of a DFA
- Returns
the semigroup
- Return type
- shuffle(other, strict=False)[source]¶
CShuffle of two languages: L1 W L2
- Parameters
- Return type
See also
C. Câmpeanu, K. Salomaa and s. Yu, Tight lower bound for the state complexity of CShuffle of regular languages. J. Autom. Lang. Comb. 7 (2002) 303–310.
- sop(other)[source]¶
Strange operation
See also
Nelma Moreira, Giovanni Pighizzini, and Rogério Reis. Universal disjunctive concatenation
and star. In Jeffrey Shallit and Alexander Okhotin, editors, Proceedings of the 17th Int. Workshop on Descriptional Complexity of Formal Systems (DCFS15), number 9118 in LNCS, pages 197–208. Springer, 2015.
New in version 1.2b2.
- star(flag=False)[source]¶
Star of a DFA. If the DFA is not complete, it is completed.
..versionchanged: 0.9.6
- stronglyConnectedComponents()[source]¶
Dummy method that uses the NFA conterpart
New in version 1.3.3.
- Return type
- subword()[source]¶
Returns a dfa that recognizes subword(L(self))
- Return type
dfa
New in version 1.1.
- succintTransitions()[source]¶
Collects the transition information in a compact way suitable for graphical representation. :rtype: list of tupples
New in version 0.9.8.
- syncPower()[source]¶
Evaluates the Power automata for the action of each symbol
- Returns
The Power automata being the set of all states the initial state and all singleton states final.
- Return type
- toADFA()[source]¶
Try to convert DFA to ADFA
- Returns
the same automaton as a ADFA
- Return type
- Raises
notAcyclic – if this is not an acyclic DFA
New in version 1.2.
Changed in version 1.2.1.
- uniqueRepr()[source]¶
Normalise unique string for the string icdfa’s representation. .. seealso:: TCS 387(2):93-102, 2007 https://www.dcc.fc.up.pt/~nam/publica/tcsamr06.pdf
- Returns
normalised representation
- Return type
- Raises
DFAnotComplete – if DFA is not complete
- unmark()[source]¶
Unmarked NFA that corresponds to a marked DFA: in which each alfabetic symbol is a tuple (symbol, index)
- Returns
a NFA
- Return type
- usefulStates(initial_states=None)[source]¶
Set of states reacheable from the given initial state(s) that have a path to a final state.
- Parameters
initial_states (iterable of int) – starting states
- Returns
set of state indexes
- Return type
set of int
- static vDescription()[source]¶
Generation of Verso interface description
New in version 0.9.5.
- Returns
the interface list
- witnessDiff(other)[source]¶
Returns a witness for the difference of two DFAs and:
0
if the witness belongs to the other language
1
if the witness belongs to the self language
- Parameters
other (DFA) – the other DFA
- Returns
a witness word
- Return type
list of symbols
- Raises
DFAequivalent – if automata are equivalent
NFA¶
- class NFA[source]¶
Class for Non-deterministic Finite Automata (CEpsilon-transitions allowed).
- Variables

- HKeqP(other, strict=True)[source]¶
Test NFA equivalence with extended Hopcroft-Karp method
See also
J. E. Hopcroft and r. M. Karp. A Linear Algorithm for Testing Equivalence of Finite Automata.TR 71–114. U. California. 1971
- Parameters
other – NFA
strict – if True checks for same alphabets
- Returns
Boolean
- addEpsilonLoops()[source]¶
Add epsilon loops to every state :return: self
Attention
in-place modification
New in version 1.0.
- addInitial(stateindex)[source]¶
Add a new state to the set of initial states.
- Parameters
stateindex (int) – index of new initial state
- addTransition(sti1, sym, sti2)[source]¶
Adds a new transition. Transition is from
sti1tosti2consuming symbolsym.sti2is a unique state, not a set of them.
- addTransitionQ(srci, dest, symb, qfuture, qpast)[source]¶
Add transition to the new transducer instance.
- Parameters
New in version 1.0.
- autobisimulation()[source]¶
Largest right invariant equivalence between states of the NFA
- Returns
Incomplete equivalence relation (transitivity, and reflexivity not calculated) as a set of unordered pairs of states
- Return type
Set of frozensets
See also
Ilie&Yu, 2003
- autobisimulation2()[source]¶
Alternative space-efficient definition of NFA.autobisimulation.
- Returns
Incomplete equivalence relation (reflexivity, symmetry, and transitivity not calculated) as a set of pairs of states
- Return type
list of tuples
- closeEpsilon(st)[source]¶
Add all non CEpsilon transitions from the states in the CEpsilon closure of given state to given state.
- Parameters
st (int) – state index
- delTransition(sti1, sym, sti2, _no_check=False)[source]¶
Remove a transition if existing and perform cleanup on the transition function’s internal data structure.
- Parameters
Note
unused alphabet symbols will be discarded from sigma.
- deleteStates(del_states)[source]¶
Delete given iterable collection of states from the automaton.
Note
delta function will always be rebuilt, regardless of whether the states list to remove is a suffix, or a sublist, of the automaton’s states list.
- detSet(generic=False)[source]¶
Computes the determination uppon a followFromPosition result
- Return type
- dotFormat(size='20,20', filename=None, direction='LR', strict=False, maxlblsz=6, sep='\n') str[source]¶
A dot representation
- Parameters
- Returns
the dot representation
- Return type
New in version 0.9.6.
Changed in version 1.2.1.
- elimEpsilon()[source]¶
Eliminate CEpsilon-transitions from this automaton.
:rtype : NFA
Attention
performs in place modification of automaton
Changed in version 1.1.1.
- eliminateEpsilonTransitions()[source]¶
Eliminates all epslilon-transitions with no state addition
Attention
in-place modification
- eliminateTSymbol(symbol)[source]¶
Delete all trasitions through a given symbol
- Parameters
symbol (str) – the symbol to be excluded from delta
Attention
in place alteration of the automata
New in version 0.9.6.
- enumNFA(n=None)[source]¶
returns the set of words of words of length up to n accepted by self :param int n: highest lenght or all words if finite
- Return type
list of strings or None
- epsilonClosure(st)[source]¶
Returns the set of states CEpsilon-connected to from given state or set of states.
- Parameters
- Returns
the list of state indexes CEpsilon connected to
st- Return type
set of int
Attention
stmust exist.
- epsilonPaths(start, end)[source]¶
All states in all paths (DFS) through empty words from a given starting state to a given ending state.
- equivReduced(equiv_classes)[source]¶
Equivalent NFA reduced according to given equivalence classes.
- Parameters
equiv_classes (UnionFind) – Equivalence classes
- Returns
Equivalent NFA
- Return type
- evalSymbol(stil, sym)[source]¶
Set of states reacheable from given states through given symbol and CEpsilon closure.
- finalCompP(s)[source]¶
Verify whether there is a final state in strongly connected component containing given state.
- Parameters
s (int) – state index
- Returns
:: bool
- hasTransitionP(state, symbol=None, target=None)[source]¶
Whether there’s a transition from given state, optionally through given symbol, and optionally to a specific target.
- homogeneousFinalityP()[source]¶
Tests if states have incoming transitions froms states with different finalities
- Return type
- homogenousP(x)[source]¶
Whether this NFA is homogenous; that is, for all states, whether all incoming transitions to that state are through the same symbol.
- Parameters
x – dummy parameter to agree with the method in DFAr
- Return type
- initialComp()[source]¶
Evaluate the connected component starting at the initial state.
- Returns
list of state indexes in the component
- Return type
list of int
- lEquivNFA()[source]¶
Equivalent NFA obtained from merging equivalent states from autobisimulation of this NFA’s reversal.
- Return type
Note
returns copy of self if autobisimulation renders no equivalent states.
- lrEquivNFA()[source]¶
Equivalent NFA obtained from merging equivalent states from autobisimulation of this NFA, and from autobisimulation of its reversal; i.e., merges all states that are equivalent w.r.t. the largest right invariant and largest left invariant equivalence relations.
- Return type
Note
returns copy of self if autobisimulations render no equivalent states.
- minimalDFA()[source]¶
Evaluates the equivalent minimal complete DFA
- Returns
equivalent minimal DFA
- Return type
- product(other)[source]¶
Returns a NFA (skeletom) resulting of the simultaneous execution of two DFA.
Note
No final states are set.
Attention
the name
EmptySetis used in a unique special state namethe method uses 3 internal functions for simplicity of code (really!)
- rEquivNFA()[source]¶
Equivalent NFA obtained from merging equivalent states from autobisimulation of this NFA.
- Return type
Note
returns copy of self if autobisimulation renders no equivalent states.
- renameStatesFromPosition()[source]¶
Rename states of a Glushkov automaton using the positions of the marked RE
- Return type
- reorder(dicti)[source]¶
Reorder states indexes according to given dictionary.
- Parameters
dicti (dict) – state name reorder
Note
dictionary does not have to be complete
- reversal()[source]¶
Returns a NFA that recognizes the reversal of the language
- Returns
NFA recognizing reversal language
- Return type
- reverseTransitions(rev)[source]¶
Evaluate reverse transition function.
- Parameters
rev (NFA) – NFA in which the reverse function will be stored
- shuffle(other)[source]¶
Shuffle of a NFA
- Parameters
other (FA) – an FA
- Returns: the resulting NFA
NFA: the resulting NFA
- succintTransitions()[source]¶
Collects the transition information in a compact way suitable for graphical representation. :rtype: list
- toDFA()[source]¶
Construct a DFA equivalent to this NFA, by the subset construction method.
- Return type
Note
valid to CEpsilon-NFA
- toNFAr()[source]¶
NFA with the reverse mapping of the delta function.
- Returns
shallow copy with reverse delta function added
- Return type
- usefulStates(initial_states=None)[source]¶
Set of states reacheable from the given initial state(s) that have a path to a final state.
- Parameters
initial_states (set of int or list of int) – set of initial states
- Returns
set of state indexes
- Return type
set of int
NFAr¶
- class NFAr[source]¶
- Class for Non-deterministic Finite Automata with reverse delta function added by construction.
Includes efficient methods for merging states.

- addTransition(sti1, sym, sti2)[source]¶
Adds a new transition. Transition is from
sti1tosti2consuming symbolsym.sti2is a unique state, not a set of them. Reversed transition function is also computed
- delTransition(sti1, sym, sti2, _no_check=False)[source]¶
Remove a transition if existing and perform cleanup on the transition function’s internal data structure and in the reversal transition function
- deleteStates(del_states)[source]¶
Delete given iterable collection of states from the automaton. Performe deletion in the transition function and its reversal.
- Parameters
del_states (set or list of int) – collection of int representing states
- elimEpsilonO()[source]¶
Eliminate CEpsilon-transitions from this automaton, with reduction of states through elimination of CEpsilon-cycles, and single CEpsilon-transition cases.
- Returns
itself
- Return type
Attention
performs inplace modification of automaton
- homogenousP(inplace=False)[source]¶
Checks is the automaton is homogenous, i.e.the transitions that reaches a state have all the same label.
- mergeStates(f, t)[source]¶
Merge the first given state into the second. If first state is an initial or final state, the second becomes respectively an initial or final state.
Attention
It is up to the caller to remove the disconnected state. This can be achieved with
`trim().
- mergeStatesSet(tomerge, target=None)[source]¶
Merge a set of states with a target merge state. If the states in the set have transitions among them, those transitions will be directly merged into the target state.
- Parameters
tomerge (Set of int) – set of states to merge with target
target (int) – optional target state
Note
if target state is not given, the minimal index with be considered.
Attention
The states of the list will become unreacheable, but won’t be removed. It is up to the caller to remove them. That can be achieved with
trim().
- toNFA()[source]¶
Turn into an instance of NFA, and remove the reverse mapping of the delta function.
- Returns
shallow copy without reverse delta function
- Return type
- unlinkSoleIncoming(state)[source]¶
If given state has only one incoming transition (indegree is one), and it’s through CEpsilon, then remove such transition and return the source state.
Note
if conditions aren’t met, returned source state is None, and automaton remains unmodified.
SSemiGroup¶
- class SSemiGroup[source]¶
Class support for the Syntactic SemiGroup.
- Variables
elements – list of tuples representing the transformations
words – a list of pairs (index of the prefix transformation, index of the suffix char)
gen – a list of the max index of each generation
sigma – set of symbols
EnumL¶
- class EnumL(aut, store=False)[source]¶
- Class for enumerate FA languages
See: Efficient enumeration of words in regular languages, M. Ackerman and J. Shallit, Theor. Comput. Sci. 410, 37, pp 3461-3470. 2009. http://dx.doi.org/10.1016/j.tcs.2009.03.018
- Variables
New in version 0.9.8.
- enum(m)[source]¶
Enumerates the first m words of L(A) according to the lexicographic order if there are at least m words. Otherwise, enumerates all words accepted by A.
- Parameters
m (int) – max number of words
- enumCrossSection(n)[source]¶
Enumerates the nth cross-section of L(A)
- Parameters
n (int) – nonnegative integer
Functions¶
saveToString¶
stringToDFA¶
Module: Conversion of Finite Automata: (conversions)¶
Conversions between objects.
Deterministic and non-deterministic automata manipulation, conversion and evaluation. .. Authors: Rogério Reis & Nelma Moreira .. This is part of FAdo project https://fado.dcc.fc.up.pt.
Classes¶
GFA¶
- class GFA[source]¶
Class for Generalized Finite Automata: NFA with a unique initial state and transitions are labeled with RegExp.

- addTransition(sti1, sym, sti2)[source]¶
- Adds a new transition from
sti1tosti2consuming symbolsym. Label of the transition function is a RegExp.
- Adds a new transition from
- completeDelta()[source]¶
Adds empty set transitions between the automatons final and initial states in order to make it complete. It’s only meant to be used in the final stage of SEA…
- deleteStates(del_states)[source]¶
To be implemented below
- Parameters
del_states (list) – states to be deleted
- eliminateState(st)[source]¶
Deletes a state and updates the automaton
- Parameters
st (int) – the state to be deleted
- evalNumberOfStateCycles()[source]¶
Evaluates the number of cycles each state participates
- Returns
state->list of cycle lengths
- Return type
- normalize()[source]¶
Create a single initial and final state with Epsilon transitions.
Attention
works in place
- reorder(dictio)[source]¶
Reorder states indexes according to given dictionary.
- Parameters
dictio (dict) – order
Note
dictionary does not have to be complete
:members:
Functions¶
FA2GFA¶
FAallRegExps¶
cutPoints¶
FA2regexpSE¶
FA2regexpSE_nn¶
SP2regexp¶
- SP2regexp(aut)[source]¶
Checks if FA is SP (Serial-PArallel), and if so returns the regular expression whose language is recognised by the FA
- Parameters
aut (OFA) – the automaton
- Returns
equivalent regular expression
- Return type
- Raises
NotSP – if the automaton is not Serial-Parallel
See also
Moreira & Reis, Fundamenta Informatica, Series-Parallel automata and short regular expressions, n.91 3-4, pag 611-629. https://www.dcc.fc.up.pt/~nam/publica/spa07.pdf
Note
Automata must be Serial-Parallel
FAeliminateSingles¶
FA2regexpCG¶
FA2regexpCG_nn¶
- FA2regexpCG_nn(aut: FAdo.fa.OFA)[source]¶
Regular expression from state elimination whose language is recognised by the FA. Uses a heuristic to choose the order of elimination. The FA is not normalized before the state elimination.
- Parameters
aut (OFA) – the automaton
- Returns
the equivalent regular expression
- Return type
FA2regexpSEO¶
FA2regexpDynamicCycleHeuristic¶
- FA2regexpDynamicCycleHeuristic(aut)[source]¶
State elimination Heuristic based on the number of cycles that passes through each state. Here those numbers are evaluated dynamically after each elimination step
- Parameters
aut (OFA) – the automaton
- Returns
an equivalent regular expression
- Return type
See also
Nelma Moreira, Davide Nabais, and Rogério Reis. State elimination ordering strategies: Some experimental results. Proc. of 11th Workshop on Descriptional Complexity of Formal Systems (DCFS10), pages 169-180.2010. DOI: 10.4204/EPTCS.31.16
FA2regexpStaticCycleHeuristic¶
- FA2regexpStaticCycleHeuristic(aut)[source]¶
State elimination Heuristic based on the number of cycles that passes through each state. Here those numbers are evaluated statically in the beginning of the process
- Parameters
aut (OFA) – the automaton
- Returns
a equivalent regular expression
- Return type
See also
Nelma Moreira, Davide Nabais, and Rogério Reis. State elimination ordering strategies: Some experimental results. Proc. of 11th Workshop on Descriptional Complexity of Formal Systems (DCFS10), pages 169-180.2010. DOI: 10.4204/EPTCS.31.16
DFA2regexpDijkstra¶
- DFA2regexpDijkstra(aut) FAdo.reex.RegExp[source]¶
Returns a regexp for the current DFA considering the recursive method. Very inefficent.
- Parameters
aut (DFA) – the automaton
- Returns
a regexp equivalent to the current DFA
- Return type
DFAsyncWords¶
Module: Common Definitions (common)¶
Common definitions for FAdo files
Classes¶
Word¶
Drawable¶
- class Drawable[source]¶
Any FAdo object that is drawable
- display(filename=None, size='30,20', strict=False, maxlblsz=6)[source]¶
Display automata using dot
- Parameters
Changed in version 1.2.1.
Module: FAdo IO Functions (fio)¶
In/Out.
FAdo I/O methods. The parsing grammars for most of the objects reside here.
Classes¶
Class BuildFadoObject¶
Functions¶
readFromFile¶
- readFromFile(FileName)[source]¶
Reads list of finite automata definition from a file.
The format of these files must be the as simple as possible:
#begins a comment@DFAor@NFAbegin a new automata (and determines its type) and must be followed by the list of the final states separated by blanksfields are separated by a blank and transitions by a CR:
statesymbolnew statein case of a NFA declaration, the “symbol” @epsilon is interpreted as a CEpsilon-transition
the source state of the first transition is the initial state
in the case of a NFA, its declaration
@NFAcan, after the declaration of the final states, have a*followed by the list of initial statesboth, NFA and DFA, may have a declaration of alphabet starting with a
$followed by the symbols of the alphabeta line with a sigle name, decrares a state
FAdo ::= FA | FA CR FAdo FA ::= DFA | NFA | Transducer DFA ::= "@DFA" LsStates Alphabet CR dTrans NFA ::= "@NFA" LsStates Initials Alphabet CR nTrans Transducer ::= "@Transducer" LsStates Initials Alphabet Output CR tTrans Initials ::= "*" LsStates | /CEpsilon Alphabet ::= "$" LsSymbols | /CEpsilon Output ::= "$" LsSymbols | /CEpsilon nSymbol ::= symbol | "@epsilon" LsStates ::= stateid | stateid , LsStates LsSymbols ::= symbol | symbol , LsSymbols dTrans ::= stateid symbol stateid | | stateid symbol stateid CR dTrans nTrans ::= stateid nSymbol stateid | | stateid nSymbol stateid CR nTrans tTrans ::= stateid nSymbol nSymbol stateid | | stateid nSymbol nSymbol stateid CR nTransNote
If an error occur, either syntactic or because of a violation of the declared automata type, an exception is raised
Changed in version 0.9.6.
Changed in version 1.0.
readOneFromFile¶
readOneFromString¶
saveToFile¶
saveToJson¶
saveToString¶
toJson¶
Constants¶
- const
FAdo.fio.FAdoGrammar
Module: Regular Expressions (reex)¶
Regular expressions manipulation
Regular expression classes and manipulation
Classes¶
RegularExpression¶
RegExp¶
- class RegExp(sigma=None)[source]¶
Base class for regular expressions.
- Variables
Sigma – alphabet set of strings

- abstract static alphabeticLength()[source]¶
Number of occurrences of alphabet symbols in the regular expression.
- Return type
integer
Attention
Doesn’t include the empty word.
- compare(r, cmp_method='compareMinimalDFA', nfa_method='nfaPD')[source]¶
Compare with another regular expression for equivalence. :param r: :param cmp_method: :param nfa_method:
- compareMinimalDFA(r, nfa_method='nfaPosition')[source]¶
Compare with another regular expression for equivalence through minimal DFAs. :param r: :param nfa_method:
- dfaAuPoint()[source]¶
DFA “au-point” acconding to Nipkow
- Returns
“au-point” DFA
- Return type
See also
Andrea Asperti, Claudio Sacerdoti Coen and Enrico Tassi, Regular Expressions, au point. arXiv 2010
See also
Tobias Nipkow and Dmitriy Traytel, Unified Decision Procedures for
Regular Expression Equivalence
- dfaBrzozowski(memo=None)[source]¶
Word derivatives automaton of the regular expression
- Returns
word derivatives automaton
- Return type
See also
Brzozowski, Derivatives of Regular Expressions. J. ACM 11(4): 481-494 (1964)
- dfaYMG()[source]¶
DFA Yamada-McNaugthon-Gluskov acconding to Nipkow
- Returns
Y-M-G DFA
- Return type
See also
Tobias Nipkow and Dmitriy Traytel, Unified Decision Procedures for
Regular Expression Equivalence
- abstract static epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Return type
integer
- evalWordP(word)[source]¶
Verifies if a word is a member of the language represented by the regular expression.
- static ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
Boolean
- marked()[source]¶
Regular expression in which every alphabetic symbol is marked with its Position.
The kind of regular expression returned is known, depending on the literary source, as marked, linear or restricted regular expression.
- Returns
linear regular expression
- Return type
See also
r. McNaughton and H. Yamada, Regular Expressions and State Graphs for Automata, IEEE Transactions on Electronic Computers, V.9 pp:39-47, 1960
..attention: mark and unmark do not preserve the alphabet, neither set the new alphabet
- nfaFollow()[source]¶
NFA that accepts the regular expression’s language, whose structure, equiand construction.
- Return type
See also
Ilie & Yu (Follow Automata, 03)
- nfaFollowEpsilon(trim=True)[source]¶
Epsilon-NFA constructed with Ilie and Yu’s method () that accepts the regular expression’s language.
- Parameters
trim –
- Returns
NFA possibly with CEpsilon transitions
- Return type
NFAe
Note
The regular expression must be reduced
See also
Ilie & Yu, Follow automta, Inf. Comp. ,v. 186 (1),140-162,2003
- nfaGlushkov()[source]¶
Position or Glushkov automaton of the regular expression. Recursive method.
- Returns
NFA
- nfaNaiveFollow()[source]¶
NFA that accepts the regular expression’s language, and is equal in structure to the follow automaton.
- Return type
Note
Included for testing purposes.
See also
Ilie & Yu (Follow Automata, 2003)
- nfaPD(pdmethod='nfaPDDAG')[source]¶
Computes the partial derivative automaton : param pdmethod str: an implementation of the PD automaton. Default value : nfaPDDAG :return: a PD nfa :rtype: NFA
- nfaPDDAG()[source]¶
” :return: a PD nfa build using a DAG :rtype: NFA
- ..seealso:: s.Konstantinidis, A. Machiavelo, N. Moreira, and r. Reis.
Partial derivative automaton by compressing regular expressions. DCFS 2021, volume 13037 of LNCS, pages 100–112. Springer, 2022
- nfaPDNaive()[source]¶
- NFA that accepts the regular expression’s language,
and which is constructed from the expression’s partial derivatives.
- Returns
NFA: partial derivatives [or equation] automaton
See also
V. M. Antimirov, Partial Derivatives of Regular Expressions and Finite Automaton Constructions .Theor. Comput. Sci.155(2): 291-319 (1996)
- nfaPDO()[source]¶
- NFA that accepts the regular expression’s language, and which is constructed from the expression’s partial
derivatives.
Note
optimized version
- Returns
partial derivatives [or equation] automaton
- Return type
- nfaPSNF()[source]¶
Position or Glushkov automaton of the regular expression constructed from the expression’s star normal form.
- Returns
Position automaton
- Return type
- nfaPosition(lstar=True)[source]¶
Position automaton of the regular expression.
- Parameters
lstar (boolean) – if not None followlists are computed as disjunct
- Returns
Position NFA
- Return type
- nfaPre()[source]¶
Prefix NFA of a regular expression States are of the form (RegExp,sym) :return: prefix automaton :rtype: NFA
See also
Maia et al, Prefix and Right-partial derivative automata, 11th CIE 2015, 258-267 LNCS 9136, 2015
- nfaPreSlow()[source]¶
Prefix NFA of a regular expression :return: prefix automaton :rtype: NFA .. seealso:: Maia et al, Prefix and Right-partial derivative automata, 11th CIE 2015, 258-267 LNCS 9136, 2015 ..note:: not working with current tailForm
- setSigma(symbolset=None, strict=False)[source]¶
Set the alphabet for a regular expression and all its nodes
- Parameters
..attention: Normally this attribute is not defined in a RegExp()
- abstract static starHeight()[source]¶
Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Return type
integer
- toNFA(nfa_method='nfaPDNaive')[source]¶
NFA that accepts the regular expression’s language. :param nfa_method:
- abstract static treeLength()[source]¶
Number of nodes of the regular expression’s syntactical tree.
- Return type
integer
- wordDerivative(word)[source]¶
- Derivative of the regular expression in relation to the given word,
which is represented by a list of symbols.
- Parameters
word – list of arbitrary symbols.
- Return type
regular expression
See also
Brzozowski, Derivatives of Regular Expressions. J. ACM 11(4): 481-494 (1964)
SpecialConstant¶
- class SpecialConstant(sigma=None)[source]¶
Base class for Epsilon and EmptySet

- Parameters
sigma – alphabet
- distDerivative(sigma)[source]¶
- Parameters
sigma – an arbitrary symbol.
- Return type
regular expression
- static epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Return type
integer
- static starHeight()[source]¶
Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Return type
integer
- static treeLength()[source]¶
Number of nodes of the regular expression’s syntactical tree.
- Return type
integer
CEpsilon¶
CEmptySet¶
SigmaP¶
- SigmaP¶
alias of @sigmaP
SigmaS¶
- SigmaS¶
alias of @sigmaS
Connective¶
- class Connective(arg1, arg2, sigma=None)[source]¶
Base class for (binary) operations: concatenation, disjunction, etc

- alphabeticLength()[source]¶
Number of occurrences of alphabet symbols in the regular expression.
- Return type
integer
Attention
Doesn’t include the empty word.
- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Return type
integer
Star¶
Concat¶
Disj¶
Power¶
- class Power(arg, n=1, sigma=None)[source]¶
Class for Power operation on regular expressions.

- alphabeticLength()[source]¶
Number of occurrences of alphabet symbols in the regular expression.
- Return type
integer
Attention
Doesn’t include the empty word.
- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Return type
integer
Option¶
- Option¶
alias of -
Conj¶
- Conj¶
alias of &
Shuffle¶
- Shuffle¶
alias of :
Atom¶
Position¶
SConnective¶
- class SConnective(arg, sigma=None)[source]¶
- Special regular expressions modulo associativity, commutativity, idempotence of disjunction and intersection;
- associativity of concatenation; identities sigma^* and sigma^+. Connectives are:
SDisj: disjunction SConj: intersection SConcat: concatenation
For parsing use str2sre

SConcat¶
SStar¶
SDisj¶
SConj¶
SNot¶
- class SNot(arg, sigma=None)[source]¶
- Special regular expressions modulo associativity, commutativity, idempotence of disjunction and intersection;
associativity of concatenation; identities sigma^* and sigma^+. SNot: negation

DAG¶
- class DAG(reg)[source]¶
Class to support dags representing regexps
- …seealso: P. Flajolet, P. Sipala, J.-M. Steyaert, Analytic variations on the common subexpression problem,
in: Automata, Languages and Programmin, LNCS, vol. 443, Springer, New York, 1990, pp. 220–234.
- Variables
reg (reex) – regular expression
DNode¶
MAtom¶
- class MAtom(val, mark, sigma=None)[source]¶
Base class for pointed (marked) regular expressions
Used directly to represent atoms (characters). This class is used to obtain Yamada or Asperti automata. There is no evident use for it, outside this module.
- Parameters
val – symbol
sigma – alphabet
BuildRegexp¶
BuildRPNRegexp¶
BuildRPNSRE¶
BuildSRE¶
Functions¶
str2regexp¶
- str2regexp(s, parser=Lark(open('/Users/rvr/Work/FAdo/FAdo/regexp_grammar.lark'), parser='lalr', lexer='contextual', ...), sigma=None, strict=False)[source]¶
Reads a RegExp from string.
- Parameters
s (string) – the string representation of the regular expression
parser – a parser generator for regexps
sigma (list or set of symbols) – alphabet of the regular expression
strict (boolean) – if True tests if the symbols of the regular expression are included in sigma
- Return type
str2sre¶
rpn2regexp¶
to_s¶
Module: Transducers (transducers)¶
Finite Tranducer Support
Transducer manipulation.
New in version 1.0.
Classes¶
Transducer¶
SFT¶
- class SFT[source]¶
Standard Form Tranducer
- Variables
Output (set) – output alphabet

- addEpsilonLoops()[source]¶
Add a loop transition with CEpsilon input and output to every state in the transducer.
- addTransitionProductQ(src, dest, ddest, sym, out, futQ, pastQ)[source]¶
Add transition to the new transducer instance.
Version for the optimized product
- addTransitionQ(src, dest, sym, out, futQ, pastQ)[source]¶
Add transition to the new transducer instance.
- delTransition(sti1, sym, symo, sti2, _no_check=False)[source]¶
Remove a transition if existing and perform cleanup on the transition function’s internal data structure.
- deleteState(sti)[source]¶
Remove given state and transitions related with that state.
- Parameters
sti (int) – index of the state to be removed
- Raises
DFAstateUnknown – if state index does not exist
- dup()[source]¶
Duplicate of itself :rtype: SFT
Attention
only duplicates the initially connected component
- evalWordP(wp)[source]¶
Tests whether the transducer returns the second word using the first one as input
- evalWordSlowP(wp)[source]¶
Tests whether the transducer returns the second word using the first one as input
Note: original :param tuple wp: pair of words :rtype: bool
- functionalP()[source]¶
Tests if a transducer is functional using Allauzer & Mohri and Béal&Carton&Prieur&Sakarovitch algorithms.
- Return type
See also
Cyril Allauzer and Mehryar Mohri, Journal of Automata Languages and Combinatorics, Efficient Algorithms for Testing the Twins Property, 8(2): 117-144, 2003.
See also
M.P. Béal, O. Carton, C. Prieur and J. Sakarovitch. Squaring transducers: An efficient procedure for deciding functionality and sequentiality. Theoret. Computer Science 292:1 (2003), 45-63.
Note
This is implemented using nonFunctionalW()
- inIntersection(other)[source]¶
Conjunction of transducer and automata: X & Y.
Note
This is a fast version of the method that does not produce meaningfull state names.
Note
The resulting transducer is not trim.
- inIntersectionSlow(other)[source]¶
Conjunction of transducer and automata: X & Y.
Note
This is the slow version of the method that keeps meaningfull names of states.
- inverse()[source]¶
Switch the input label with the output label.
No initial or final state changed.
- Returns
Transducer with transitions switched.
- Return type
- nonFunctionalW()[source]¶
Returns a witness of non funcionality (if is that the case) or a None filled triple
- Returns
witness
- Return type
- outIntersection(other)[source]¶
Conjunction of transducer and automaton: X & Y using output intersect operation.
- productInput(other)[source]¶
Returns a transducer (skeleton) resulting from the execution of the transducer with the automaton as filter on the input.
Note
This version does not use stateIndex() with the price of generating some unreachable sates
Changed in version 1.3.3.
- productInputSlow(other)[source]¶
Returns a transducer (skeleton) resulting from the execution of the transducer with the automaton as filter on the input.
Note
This is the slow version of the method that keeps meaningfull names of states.
- reversal()[source]¶
Returns a transducer that recognizes the reversal of the relation.
- Returns
Transducer recognizing reversal language
- Return type
- runOnWord(word)[source]¶
Returns the automaton accepting the outup of the transducer on the input word
- Parameters
word – the word
- Return type
- setInitial(sts)[source]¶
Sets the initial state of a Transducer
- Parameters
sts (list) – list of states
- toOutNFA()[source]¶
Returns the result of considering the output symbols of the transducer as input symbols of a NFA (ignoring the input symbol, thus)
- Returns
the NFA
- Return type
NFT¶
GFT¶
- class GFT[source]¶
General Form Transducer

- addOutput(sym)[source]¶
Add a new symbol to the output alphabet
There is no problem with duplicate symbols because Output is a Set. No symbol Epsilon can be added
- Parameters
sym (str) – symbol or regular expression to be added
- codeOfTransducer()[source]¶
Appends into one string the codes of the alphabets and initial and final state sets and the set of transitions
- Return type
:members:
Functions¶
hypercodeTransducer¶
infixTransducer¶
isLimitExceed¶
- isLimitExceed(NFA0Delta, NFA1Delta)[source]¶
Decide if the size of NFA0 and NFA1 exceed the limit.
Size of NFA0 is denoted as N, and size of NFA1 is denoted as M. If N*N*M exceeds 1000000, return False, else return True. If bothNFA is False, then NFA0 should be NFA, and NFA1 should be Transducer. If both NFA is True, then NFA0 and NFA1 are both NFAs.
outfixTransducer¶
prefixTransducer¶
suffixTransducer¶
Module: Finite Languages (fl)¶
Finite languages and related automata manipulation
Finite languages manipulation
Classes¶
FL¶
- class FL(wordsList=None, Sigma=None)[source]¶
Finite Language Class
- Variables
Words – the elements of the language
Sigma – the alphabet
- MADFA()[source]¶
Generates the minimal acyclical DFA using specialized algorithm
New in version 1.3.3.
See also
Incremental Construction of Minimal Acyclic Finite-State Automata, J.Daciuk, s.Mihov, B.Watson and r.E.Watson
- Return type
- intersection(other)[source]¶
Intersection of FL: a & b
- Parameters
other (FL) – right hand operand
- Raises
FAdoGeneralError – if both arguments are not FL
- multiLineAutomaton()[source]¶
Generates the trivial linear ANFA equivalent to this language
- Return type
- setSigma(Sigma, Strict=False)[source]¶
Sets the alphabet of a FL
Attention
Unless Strict flag is set to True, alphabet can only be enlarged. The resulting alphabet is in fact the union of the former alphabet with the new one. If flag is set to True, the alphabet is simply replaced.
DCFA¶
AFA¶
- class AFA[source]¶
Base class for Acyclic Finite Automata

note: This is just a container for some common methods. Not to be used directly!!
- evalRank()[source]¶
Evaluates the rank map of a automaton
- Returns
pair of sets of states by rank map, reverse delta accessability map
- Return type
- getLeaves()[source]¶
The set of leaves, i.e. final states for last symbols of language words
- Returns
set of leaves
- Return type
ADFA¶
- class ADFA[source]¶
Acyclic Deterministic Finite Automata class

Changed in version 1.3.3.
- addSuffix(st, w)[source]¶
Adds a suffix starting in st
New in version 1.3.3.
Attention
in place transformation
- complete(dead=None)[source]¶
Make the ADFA complete
- Parameters
dead (int) – a state to be identified as dead state if one was not identified yet
- Return type
Attention
The object is modified in place
Changed in version 1.3.3.
- dissMin(witnesses=None)[source]¶
Evaluates the minimal dissimilarity language :param dict witnesses: optional witness dictionay :rtype: FL
New in version 1.2.1.
- level()[source]¶
Computes the level for each state
- Returns
levels of states
- Return type
New in version 0.9.8.
- minDFCA()[source]¶
Generates a minimal deterministic cover automata from a DFA
- Return type
New in version 0.9.8.
See also
Cezar Campeanu, Andrei Päun, and Sheng Yu, An efficient algorithm for constructing minimal cover automata for finite languages, IJFCS
- minimal()[source]¶
Finds the minimal equivalent ADFA
See also
[TCS 92 pp 181-189] Minimisation of acyclic deterministic automata in linear time, Dominique Revuz
Changed in version 1.3.3.
- Returns
the minimal equivalent ADFA
- Return type
- minimalP(method=None)[source]¶
Tests if the DFA is minimal
- Parameters
method – minimization algorithm (here void)
- Return type
Changed in version 1.3.3.
ANFA¶
- class ANFA[source]¶
Acyclic Nondeterministic Finite Automata class

- mergeStates(s1, s2)[source]¶
Merge state s2 into state s1
Note
no attempt is made to check if the merging preserves the language of teh automaton
Attention
the object is modified in place
- moveFinal(st, stf)[source]¶
Unsets a set as final transfering transition to another final :param int st: the state to be ‘moved’ :param int stf: the destination final state
Note
stf must be a ‘last’ final state, i.e., must have no out transitions to anywhere but to a possible dead state
Attention
the object is modified in place
RndWGen¶
Functions¶
sigmaInitialSegment¶
genRndTrieBalanced¶
- genRndTrieBalanced(maxL, Sigma, safe=True)[source]¶
Generates a random trie automaton for a binary language of balanced words of a given leght for max word :param int maxL: length of the max word :param set Sigma: alphabet to be used :param bool safe: should a word of size maxl be present in every language? :return: the generated trie automaton :rtype: ADFA
genRndTrieUnbalanced¶
genRandomTrie¶
- genRandomTrie(maxL, Sigma, safe=True)[source]¶
Generates a random trie automaton for a finite language with a given length for max word :param int maxL: length of the max word :param set Sigma: alphabet to be used :param bool safe: should a word of size maxl be present in every language? :return: the generated trie automaton :rtype: ADFA
genRndTriePrefix¶
- genRndTriePrefix(maxL, Sigma, ClosedP=False, safe=True)[source]¶
Generates a random trie automaton for a finite (either prefix free or prefix closed) language with a given length for max word :param int maxL: length of the max word :param set Sigma: alphabet to be used :param bool ClosedP: should it be a prefix closed language? :param bool safe: should a word of size maxl be present in every language? :return: the generated trie automaton :rtype: ADFA
DFAtoADFA¶
stringToADFA¶
- stringToADFA(s)[source]¶
Convert a canonical string representation of a ADFA to a ADFA :param list s: the string in its canonical order :returns: the ADFA :rtype: ADFA
See also
Marco Almeida, Nelma Moreira, and Rogério Reis. Exact generation of minimal acyclic deterministic finite automata. International Journal of Foundations of Computer Science, 19(4):751-765, August 2008.
Module: Context Free Grammars Manipulation (cfg)¶
Context Free Grammars Manipulation.
Basic context-free grammars manipulation for building uniform random generetors
Classes¶
CFGrammar¶
- class CFGrammar(gram)[source]¶
Class for context-free grammars
- Variables
Rules – grammar rules
Terminals – terminals symbols
Nonterminals – nonterminals symbols
Start (str) – start symbol
ntr – dictionary of rules for each nonterminal
Initialization
- Parameters
gram – is a list for productions; each production is a tuple (LeftHandside, RightHandside) with LeftHandside nonterminal, RightHandside list of symbols, First production is for start symbol
CNF¶
- class CNF(gram, mark='A@')[source]¶
Chomsky Normal Form. No useless nonterminals or eepsipsilon rules are ALLOWED… Given a CFG grammar description generates one in CNF Then its possible to random generate words of a given size. Before some pre-calculations are needed.
Initialization
- Parameters
gram – is a list for productions; each production is a tuple (LeftHandside, RightHandside) with LeftHandside nonterminal, RightHandside list of symbols, First production is for start symbol
cfgGenerator¶
reStringRGenerator¶
- class reStringRGenerator(Sigma=None, size=10, cfgr=None, epsilon=None, empty=None, ident='Ti')[source]¶
Uniform random Generator for reStrings
- Uniform random generator for regular expressions. Used without arguments generates an uncollapsible re
over {a,b} with size 10. For generate an arbitary re over an alphabet of 10 symbols of size 100: reStringRGenerator (smallAlphabet(10),100,reGrammar[“g_regular_base”])
- Parameters
Note
the grammar can have already this symbols
Functions¶
gRules¶
- gRules(rules_list, rulesym='->', rhssep=None, rulesep='|')[source]¶
Transforms a list of rules into a grammar description.
- Parameters
rules_list – is a list of rule where rule is a string of the form: Word rulesym Word1 … Word2 or Word rulesym []
rulesym – LHS and RHS rule separator
rhssep – RHS values separator (None for white chars)
- Returns
a grammar description
smallAlphabet¶
Constants¶
- const
reGrammar
Module: Random DFA Generator (rndfap)¶
Random DFA generation (alternative version in python)
ICDFA Random generation binding
New in version 1.0.
Classes¶
ICDFArgen¶
- class ICDFArgen(n, k, nd=False, pn=1, seed=0)[source]¶
Generic ICDFA random generator class
- Variables
See also
Marco Almeida, Nelma Moreira, and Rogério Reis. Enumeration and generation with a string automata representation. Theoretical Computer Science, 387(2):93-102, 2007
Changed in version 1.3.4: seed added to the random generator
ICDFArnd¶
ICDFArndIncomplete¶
Module: Random ADFA Generator (rndadfa)¶
Random ADFA generation
ADFA Random generation binding
New in version 1.2.1.
Classes¶
ADFArnd¶
- class ADFArnd(n, k=2, s=1)[source]¶
Sets a random generator for Adfas by sources. By default, s=1 to be initially connected
Note: For ICDFA s=1
- alpha(n, s, k=2)[source]¶
Number of labeled acyclic initially connected DFA by states and by sources
- Parameters
- Return type
Note
uses countAdfabySource
- alpha0(n, s, k=2)[source]¶
Number of labeled acyclic initially connected DFA by states and by sources
- Parameters
- Return type
Note
uses gamma instead of beta or rndAdfa
- beta(n, s, u, k=2)[source]¶
Number of valid configurations of transitions
- Parameters
- Return type
Note
not used by alpha or rndAdfa
- countAdfaBySources(n, s, k=2)[source]¶
Number of labelled (initially connected) acyclic automata with n states, alphabet size k, and s sources
- Parameters
- Raises
IndexError – if number of states less than number of sources
- rndAdfa(n, s)[source]¶
Recursively generates a initially connected adfa
See also
Felice & Nicaud, CSR 2013 Lncs 7913, pp 88-99, Random Generation of Deterministic Acyclic Automata Using the Recursive Method, DOI:10.1007/978-3-642-38536-0_8
Module: Combo Operations (comboperations)¶
Several combined operations for DFAs
Combined operations
Functions¶
starConcat¶
concatWStar¶
starWConcat¶
starDisj¶
starInter0¶
starInter¶
disjWStar¶
interWStar¶
Module: Codes (codes)¶
Code theory module
New in version 1.0.
Classes¶
CodeProperty¶
- class CodeProperty(name, alph)[source]¶
- See: K. Dudzinski and s. Konstantinidis: Formal descriptions of code properties: decidability, complexity,
implementation. International Journal of Foundations of Computer Science 23:1 (2012), 67–85.
- Variables
sigma – the alphabet
TrajProp¶
IPTProp¶
- class IPTProp(aut, name=None)[source]¶
Input Preserving Transducer Property

Constructor :param SFT aut: Input preserving transducer
- addToCode(aut, N, n=2000)[source]¶
Returns an NFA and a list W of up to N words of length ell, such that the NFA accepts L(aut) union W, which is an error-detecting language. ell is computed from aut
- makeCode(N, ell, s, n=2000, ov_free=False)[source]¶
Returns an NFA and a list W of up to N words of length ell, such that the NFA accepts W, which is an error-detecting language. The alphabet to use is {0,1,…,s-1}. where s <= 10.
- makeCodeO(N, ell, s, n=2000, end=None, ov_free=False)[source]¶
Returns an NFA and a list W of up to N words of length ell, such that the NFA accepts W, which is an error-detecting language. The alphabet to use is {0,1,…,s-1}. where s <= 10.
- Parameters
- Returns
an automaton and a list of strings
- Return type
Note: not ov_free and end defined simultaneously Note: end should be a Word
- notMaxStatW(aut, ell, n=2000, ov_free=False)[source]¶
Returns a word of length ell to add into aut or None; simpler version of function nonMaxStatFEpsW
IATProp¶
PrefixProp¶
ErrDetectProp¶
- ErrDetectProp¶
alias of
FAdo.codes.IPTProp
ErrCorrectProp¶
- class ErrCorrectProp(t)[source]¶
Error Correcting Property

Constructor :param SFT aut: Input preserving transducer
Functions¶
buildTrajPropS¶
buildIATPropF¶
buildIPTPropF¶
buildIATPropS¶
buildIPTPropS¶
buildErrorDetectPropF¶
buildErrorCorrectPropF¶
buildErrorCorrectPropF¶
buildErrorDetectPropS¶
buildErrorCorrectPropS¶
buildPrefixProperty¶
editDistanceW¶
- editDistanceW(auto)[source]¶
Compute the edit distance of a given regular language accepted by the NFA via Input-altering transducer.
- Parameters
auto (NFA) – language recogniser
- Returns
The edit distance of the given regular language plus a witness pair
- Return type
Attention
language should have at least two words
See also
Lila Kari, Stavros Konstantinidis, Steffen Kopecki, Meng Yang. An efficient algorithm for computing the edit distance of a regular language via input-altering transducers. arXiv:1406.1041 [cs.FL]
exponentialDensityP¶
createInputAlteringSIDTrans¶
Module: Set Specification Transducers and Automata (sst)¶
Set Specification Transducer supportt
New in version 1.4.
Classes¶
PSP¶
PSPVanila¶
PDPEqual¶
PSPDiff¶
SetSpec¶
Module: graphs (graph creation and manipulation)¶
Graph support
Basic Graph object support and manipulation
Classes¶
Graph¶
- class Graph[source]¶
Graph base class

- addEdge(v1, v2)[source]¶
Adds an edge :param int v1: vertex 1 index :param int v2: vertex 2 index :raises GraphError: if edge is loop
- addVertex(vname)[source]¶
Adds a vertex (by name)
- Parameters
vname – vertex name
- Returns
vertex index
- Return type
- Raises
DuplicateName – if vname already exists
DiGraph¶
- class DiGraph[source]¶
Directed graph base class

DiGraphVm¶
Small Tutorial¶
A small tutorial for FAdo¶
FAdo system is a set tools for regular languages manipulation.
Regular languages can be represented by regular expressions (RegExp) or finite automata, among other formalisms. Finite automata may be deterministic (DFA) or non-deterministic (NFA). In FAdo these representations are implemented as Python classes. A full documentation of all classes and methods is here.
To work with FAdo, after installation, import the following modules on a Python interpreter:
>>> from FAdo.fa import *
>>> from FAdo.reex import *
>>> from FAdo.fio import *
The module fa implements the classes for finite automata and the module reex the classes for regular expressions. The module fio implements methods for IO of automata and related models.
General conventions
Methods which name ends in P test if the object verifies a given property and return True or False.
Finite Automata
The top class for finite automata is the class FA,which has two main subclasses: OFA for one way finite automata and the class TFA for two-way finite automata. The class OFA implements the basic structure of a finite automaton shared by DFAs and NFAs. This class defines the following attributes:
Sigma: the input alphabet (set)
States: the list of states. It is a list such that each state is referred by its index whenever it is used (transitions, Final, etc).
Initial:the initial state (or a set of initial states for NFA). It is an index or list of indexes.
Final: the set of final states. It is a list of indexes.
In general, one should not create instances (objects) of class OFA. The class DFA and NFA implement DFAs and NFAs, respectively. The class GFA implements generalized NFAs that are used in the conversion between finite automata and regular expressions. All three classes inherit from class OFA.
For each class there are special methods for add/delete/modify alphabet symbols, states and transitions.
DFAs
The following example shows how to build a DFA that accepts the words of {0,1}* that are multiples of 3.
>>> m3= DFA()
>>> m3.setSigma(['0','1'])
>>> m3.addState('s1')
>>> m3.addState('s2')
>>> m3.addState('s3')
>>> m3.setInitial(0)
>>> m3.addFinal(0)
>>> m3.addTransition(0, '0', 0)
>>> m3.addTransition(0, '1', 1)
>>> m3.addTransition(1, '0', 2)
>>> m3.addTransition(1, '1', 0)
>>> m3.addTransition(2, '0', 1)
>>> m3.addTransition(2, '1', 2)
It is now possible, for instance, to see the structure of the automaton or to test if a word is accepted by it.
>>> m3
DFA((['s1', 's2', 's3'], ['1', '0'], 's1', ['s1'], "[('s1', '1', 's2'), ('s1', '0', 's1'), ('s2', '1', 's1'), ('s2', '0', 's3'), ('s3', '1', 's3'), ('s3', '0', 's2')]"))
>>> m3.evalWordP("011")
True
>>> m3.evalWordP("1011")
False
>>>
If graphviz is installed it is also possible to display the diagram of an automaton as follows:
>>>m3.display()
Instead of constructing the DFA directly we can load (and save) it in a simple text format. For the previous automaton the description will be:
Then, if this description is saved in file mul3.fa, we have
>>> m3=readFromFile(“mul3.fa”)[0]
As the set of states is represented by a Python list , the list method len can be used to determine the number of states of a FA:
>>> len(m3.States)
3
For the number of Transitions the countTransitions() method must be used
>>> m3.countTransitions()
6
To minimize a DFA any of the minimization algorithms implemented can be used:
>>> min=m3.minimalHopcroft()
In this case, the DFA was already minimal so min has the same number of states as m3.
Several (regularity preserving) operations of DFAs are implemented in FAdo: boolean (union (| or __or__), intersection (& or __and__) and complementation (~ or __invert__)), concatenation (Concat), reversal (reversal) and Star (Star).
>>> u = m3 | ~m3
>>> u
DFA(([(1, 1), (0, 0), (2, 2)], set(['1', '0']), 0,set([0, 1, 2]), {0: {'1': 1, '0': 0}, 1: {'1': 0, '0': 2}, 2:{'1': 2, '0': 1}}))
>>> m = u.minimal()
>>> m
DFA((['(1, 1)'], ['1', '0'], '(1, 1)', ['(1, 1)'], "[('(1, 1)', '1', '(1, 1)'), ('(1, 1)', '0', '(1, 1)')]"))
State names can be renamed in-place using:
>>> m.renameStates(range(len(m)))
DFA(([‘0’], [‘1’, ‘0’], ‘0’, [‘0’], “[(0, ‘1’, 0), (0, ‘0’, 0)]”))
Notice that m recognize all words over the alphabet {0.1}.
It is possible to generate a word recognisable by an automata (witness)
>>> u.witness()
'@CEpsilon'
In this case this allows to ensure that u recognizes the empty word.
This method is also useful for obtain a witness for the difference of two DFAs (witnessDiff).
To test if two DFAs are equivalent the the operator == (equivalenceP) can be used.
NFAs
NFAs can be built and manipulated in a similar way. There is no distinction between NFAs with and without CEpsilon-transitions. But it is possible to test if a NFA has CEpsilon-transitions and convert between a NFA with CEpsilon-transitions to a (equivalent) NFA without them.
Converting between NFAs and DFAs
The method toDFA allows to convert a NFA to an equivalent DFA by the subset construction method. The method toNFA migrates trivially a DFA to a NFA.
Regular Expressions
A regular expression can be a symbol of the alphabet, the empty set (@epmtyset), the empty word (@CEpsilon) or the concatenation or the union (+) or the Kleene Star (*) of a regular expression. Examples of regular expressions are a+b, (a+ba)*, and (@CEpsilon+ a)(ba+ab+@EmptySet).
The class RegExp is the base class for regular expressions and is used to represent an alphabet symbol. The classes CEpsilon and EmptySet are the subclasses used for the empty set and empty word, respectively. Complex regular expressions are Concat, Disj, and Star.
As for DFAs (and NFAs) we can build directly a regular expressions as a Python class:
>>> r = Star(Disj(RegExp("a"),Concat(RegExp("b"),RegExp("a"))))
>>> print r
(a + (b a))*
But we can convert a string to a RegExp class or subclass, using the method str2regexp.
>>> r = str2regexp("(a+ba)*")
>>> print r
(a + (b a))*
For regular expressions there are several measures available: alphabetic size, (parse) tree size, string length, number of epsilons and Star height. It is also possible to explicitly associate an alphabet to regular expression (even if some symbols do not appear in it) (setSigma)
There are several algebraic properties that can be used to obtain equivalent regular expressions of a smaller size. The method reduced transforms a regular expression into one equivalent without some obvious unnecessary epsilons, emptysets or stars.
Several methods that allows the manipulation of derivatives (or partial derivatives) by a symbol or by a word are implemented. However, the class RegExp does not deal with regular expressions module ACI properties (associativity, commutativity and idempotence of the union) (see class xre) , a so it is not possible to obtain all word derivatives of a given regular expression. This is not the case for partial derivatives.
To test if two regular expressions are equivalent the method compare can be used.
>>> r.compare(str2regexp(\"(a*(ba)*a*)*\"))
True
>>>
Converting Finite Automata to Regular Expressions
For pedagogical purposes, it is implemented a recursive method that constructs a regular expression equivalent to a given DFA (regexp).
>>> print m3.RegExp()
((0 + ((@CEpsilon + 0) (0* (@CEpsilon + 0)))) + ((1 +((@CEpsilon + 0) (0* 1))) ((1 (0* 1))* (1 + (1 (0
True
>>>
Converting Finite Automata to Regular Expressions
For pedagogical purposes, it is implemented a recursive method that constructs a regular expression equivalent to a given DFA (regexp).
>>> print m3.RegExp()
((0 + ((@CEpsilon + 0) (0* (@CEpsilon + 0)))) + ((1 +((@CEpsilon + 0) (0* 1))) ((1 (0* 1))* (1 + (1 (0
True
>>>
Converting Finite Automata to Regular Expressions
For pedagogical purposes, it is implemented a recursive method that constructs a regular expression equivalent to a given DFA (RegExp).
>>> print m3.regexp()
((0 + ((@CEpsilon + 0) (0* (@CEpsilon + 0)))) + ((1 +((@CEpsilon + 0) (0* 1))) ((1 (0* 1))* (1 + (1 (0*(@CEpsilon + 0))))))) + (((1 + ((@CEpsilon + 0) (0* 1)))((1 (0* 1))* 0)) ((1 + (0 ((1 (0* 1))* 0)))* (0 ((1(0* 1))* (1 + (1 (0* (@CEpsilon + 0))))))))
Methods based on state elimination techniques are usually more efficient, and produces much smaller regular expressions. We have implemented several heuristics for the elimination order.
>>> print m3.reCG()
((0 + (1 1)) + (((1 0) (1 + (0 0))*) (0 1)))*
Converting Regular Expressions to Finite Automata
Several methods to convert between regular expressions and NFAs are implemented. With the Thompson construction a NFA with CEpsilon transitions is obtained (nfaThompson). Epsilon free NFAs can be obtained by the Glushkov method (Position automata) (nfaPosition,) the partial derivatives method (nfaPD – several implementations) or by the follow method (nfaFollow). The two last methods usually allows to obtain smaller NFAs.
>>> r.nfaThompson()
NFA((['', '', '', '', '0', '1', '2', '3', '8', '9'], ['a', 'b'], ['8'], ['9'], "[('', '@CEpsilon', ''), ('', '@CEpsilon', 0), ('', '@CEpsilon', '9'), ('', 'a', ''), ('', '@CEpsilon', ''), (0, 'b', 1), (1, '@CEpsilon', 2), (2, 'a', 3), (3, '@CEpsilon', ''), ('8', '@CEpsilon', ''), ('8', '@CEpsilon', '9'), ('9', '@CEpsilon', '8')]"))
>>> r.nfaPosition()
NFA((['Initial', "('a', 1)", "('b', 2)", "('a', 3)"], ['a', 'b'], ['Initial'], ['Initial', "('a', 1)", "('a', 3)"], '[(\'Initial\', \'a\', "(\'a\', 1)"), (\'Initial\', \'b\', "(\'b\', 2)"), ("(\'a\', 1)", \'a\', "(\'a\', 1)"), ("(\'a\', 1)", \'b\', "(\'b\', 2)"), ("(\'b\', 2)", \'a\', "(\'a\', 3)"), ("(\'a\', 3)", \'a\', "(\'a\', 1)"), ("(\'a\', 3)", \'b\', "(\'b\', 2)")]'))
>>> r.nfaPD()
NFA((['(a + (b a))*', 'a (a + (b a))*'], ['a', 'b'], ['(a + (b a))*'], ['(a + (b a))*'], "[(Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a)))), 'a', Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a))))), (Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a)))), 'b', Concat(RegExp(a),Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a)))))), (Concat(RegExp(a),Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a))))), 'a', Star(Disj(RegExp(a),Concat(RegExp(b),RegExp(a)))))]"))
General Example
Considering the several methods described before it is possible to convert between the different equivalent representations of regular languages, as well to perform several regularity preserving operations.
>>> r.nfaPosition().toDFA().minimal(complete=False)
DFA((['0', '2'], ['a', 'b'], '0', ['0'], "[('0', 'a', '0'), ('0', 'b', '2'), ('2', 'a', '0')]"))
>>> m3 == m3.reCG().nfaPD().toDFA().minimal()
True
>>>
More classes and modules¶
Several other classes and modules are also available, including:
class ICDFArnd (module rndfa.py): Random DFA generation
class FL (module fl.py): special methods for finite languages
module comboperations.py: implementation of several algorithms for several combined operations with DFAs and NFAs
# module grail.py: compatibility with GRAIL
module transducers.py: several classes and methods for transducers
module codes.py: language tests for a property (set of languages) specified by a transducer










