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.4
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
FAdo.fa¶
Finite automata manipulation.
Deterministic and non-deterministic automata manipulation, conversion and evaluation.
- 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 sti1 to sti2 consuming symbol sym.
- 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.
- Parameters
- Returns
the result of the concatenation
- Return type
- Raises
DFAdifferentSigma – if alphabet are not equal
- 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 state indexes
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
- Return type
set of minimal distinguishing words (FL)
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
- Return type
- ..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…
- evalSymbol(init, sym)[source]¶
Returns the state reached from given state through a given symbol.
- Parameters
- Returns
reached state
- Return type
- Raises
DFAsymbolUnknown – if symbol not in alphabet
DFAstopped – if transition function is not defined for the given input
- 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
- 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
- make_prefix_free()[source]¶
Turns a DFA in a prefix-free automaton deleting all outgoing transitions from final states
- Return type
New in version 2.0.3.
- 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 apeoach 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
- sMonoid()[source]¶
Evaluation of the syntactic monoid of a DFA
- Returns
the semigroup
- Return type
SSemiGroup
- sSemigroup()[source]¶
Evaluation of the syntactic semigroup of a DFA
- Returns
the semigroup
- Return type
SSemiGroup
- 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
- succintTransitions()[source]¶
Collects the transition information in a compact way suitable for graphical representation.
- Returns
list of tupples
- Return type
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
- 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
- class EnumDFA(aut, store=False)[source]¶
Class for enumerating languages defined by DFAs

- fillStack(w)[source]¶
Computes S_1,…,S_n-1 where S_i is the set of (n-i)-complete states reachable from S_i-1
- Parameters
w – word
- 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
- class EnumNFA(aut, store=False)[source]¶
Class for enumerating languages defined by NFAs

- fillStack(w)[source]¶
Computes S_1,…,S_n-1 where S_i is the set of (n-i)-complete states reachable from S_i-1
- Parameters
w – word
- 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.
- indexList(lstn)[source]¶
Converts a list of stateNames into a set of stateIndexes.
- Parameters
lstn (list) – list of names
- Returns
the list of state indexes
- Return type
- Raises
DFAstateUnknown – if a state name is unknown
- 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 NFA[source]¶
Class for Non-deterministic Finite Automata (epsilon-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
- addEpsilonLoops()[source]¶
Add epsilon loops to every state
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
See also
Ilie and S. Yu, Follow automata Inf. Comput. 186 - 1, pp 140-162, 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
- closeEpsilon(st)[source]¶
Add all non epsilon transitions from the states in the epsilon closure of given state to given state.
- Parameters
st (int) – state index
Attention
in-place modification
- 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 epsilon-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 modification
New in version 0.9.6.
- epsilonClosure(st)[source]¶
Returns the set of states epsilon-connected to from given state or set of states.
- Parameters
- Returns
the list of state indexes epsilon connected to
st- Return type
Attention
stmust exist beforehand.
- 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 epsilon closure.
- Parameters
- Returns
set of reached state indexes
- Return type
- Raises
DFAsymbolUnknown – if symbol is not in alphabet
- finalCompP(s)[source]¶
Verify whether there is a final state in strongly connected component containing given state.
- 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
Attention
in-place modification
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
- 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 epsilon-NFA
- toNFAr()[source]¶
NFA with the reverse mapping of the delta function.
- Returns
shallow copy with reverse delta function added
- Return type
- 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.
- elimEpsilonO()[source]¶
Eliminate epsilon-transitions from this automaton, with reduction of states through elimination of Epsilon-cycles, and single epsilon-transition cases.
- 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.
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 epsilon, then remove such transition and return the source state.
Note
if conditions aren’t met, returned source state is None, and automaton remains unmodified.
- 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
- 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 lose 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
- 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
- emptyDFA(sigma=None)[source]¶
Given an alphabet returns the minimal DFA for the empty language
New in version 1.3.4.2.
- saveToString(aut, sep='&')[source]¶
Finite automata definition as a string using the input format.
New in version 0.9.5.
Changed in version 0.9.6: Names are now used instead of indexes.
Changed in version 0.9.7: New format with quotes and alphabet
- sigmaStarDFA(sigma=None)[source]¶
Given a alphabet s returns the minimal DFA for s*
New in version 1.2.
FAdo.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.
- 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(aut)[source]¶
Evaluates the regular expression corresponding to the synchronizing pwords of the automata.
- Parameters
aut (DFA) – the automata
- Returns
a regular expression of the sync words of the automata
- Return type
- FA2regexpCG(aut)[source]¶
Regular expression from state elimination whose language is recognised by the FA. Uses a heuristic to choose the order of elimination.
- Parameters
aut (OFA) – the automaton
- Returns
the equivalent regular expression
- Return type
- 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
- 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
- FA2regexpSE(aut)[source]¶
A regular expression obtained by state elimination algorithm whose language is recognised by the FA aut.
- Parameters
aut (OFA) – the automaton
- Returns
the equivalent regular expression
- Return type
- FA2regexpSEO(aut, order=None)[source]¶
Regular expression from state elimination whose language is recognised by the FA. The FA is normalized before the state elimination.
- Parameters
- Returns
the equivalent regular expression
- Return type
- FA2regexpSE_nn(aut, order=None)[source]¶
Regular expression from state elimination whose language is recognised by the FA. The FA is not normalized before the state elimination.
- Parameters
- Returns
the equivalent regular expression
- Return type
- 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
- FAallRegExps(aut)[source]¶
Evaluates the alphabetic length of the equivalent regular expression using every possible order of state elimination.
- FAeliminateSingles(aut)[source]¶
Eliminates every state that only have one successor and one predecessor.
- 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…
- 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
- 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
FAdo.common¶
Common definitions for FAdo files
- 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.
- class SPLabel(val=None)[source]¶
Label class for Serial-Paralel test algorithm
See also
Moreira & Reis, Fundamenta Informatica, ‘Series-Paralel automata and short regular expressions’, n.91 3-4, pag 611-629
- class Word(data=None)[source]¶
Class to implement generic words as iterables with pretty-print
Basically a unified way to deal with words with caracters of sizes different of one with no much fuss
- dememoize(cls, method_name)[source]¶
Restore method of given class from memoized state. Stored attributes will be removed.
- lSet(s)[source]¶
returns the last element of a set
- Parameters
s (set) – the set
- Returns
the last element of the set
New in version 1.3.3.
- memoize(cls, method_name)[source]¶
Memoizes a given method result on instances of given class.
Given method should have no side effects. Results are stored as instance attributes — given parameters are disregarded.
- Parameters
cls –
method_name –
- class memoized(func)[source]¶
Decorator that caches a function’s return value each time it is called.
If called later with the same arguments, the cached value is returned, and not re-evaluated.
- overlapFreeP(word)[source]¶
- Returns True if word is overlap free, i.e, no proper and nonempty
prefix is a suffix
- Parameters
word – the word
- Return type
Boolean
- sConcat(x, y)[source]¶
CConcat words
- Parameters
x – first word
y – second word
- Returns
concatenation word
FAdo.fio¶
In/Out.
FAdo I/O methods. The parsing grammars for most of the objects reside here.
- 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 an epsilon-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 | /Epsilon Alphabet ::= "$" LsSymbols | /Epsilon Output ::= "$" LsSymbols | /Epsilon 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.
- readOneFromString(s)[source]¶
Reads one finite automata definition from a file.
See also
readFromFile for description of format
- saveToFile(FileName, fa, mode='a')[source]¶
Saves a list finite automata definition to a file using the input format
Changed in version 0.9.5.
Changed in version 0.9.6.
Changed in version 0.9.7: New format with quotes and alphabet
- saveToJson(FileName, aut, mode='w')[source]¶
Saves a finite automata definition to a file using the JSON format
- saveToString(fa)[source]¶
Saves a finite automaton definition to a string :param fa: automaton :return: the string containing the automaton definition :rtype: str
..versionadded:: 1.2.1
FAdo.reex¶
Regular expressions manipulation
Regular expression classes and manipulation
- class BuildRegexp(context=None)[source]¶
Semantics of the FAdo grammars’ regexps Priorities of operators: disj > conj > shuffle > concat > not > star >= option
- class CAtom(val, sigma=None)[source]¶
Simple Atom (symbol)
- Variables
Sigma – alphabet set of strings
val – the actual symbol

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- PD()[source]¶
Closure of partial derivatives of the regular expression in relation to all words.
- Returns
set of regular expressions
- Return type
See also
Antimirov, 95
- static alphabeticLength()[source]¶
Number of occurrences of alphabet symbols in the regular expression.
- Return type
Attention
Doesn’t include the empty word.
- derivative(sigma)[source]¶
Derivative of the regular expression in relation to the given symbol.
Note
whether the symbols belong to the expression’s alphabet goes unchecked. The given symbol will be matched against the string representation of the regular expression’s symbol.
See also
Brzozowski, Derivatives of Regular Expressions. J. ACM 11(4): 481-494 (1964)
- static epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Return type
- first(parent_first=None)[source]¶
List of possible symbols matching the first symbol of a string in the language of the regular expression.
- followLists(lists=None)[source]¶
Map of each symbol’s follow list in the regular expression.
- Parameters
lists (dict) –
- Returns
map of symbols’ follow lists {symbol: list of symbols}
- Return type
Attention
For first() and last() return lists, the follow list for certain symbols might have repetitions in the case of follow maps calculated from Star operators. The union of last(), first() and follow() sets are always disjoint when the regular expression is in Star normal form ( Brüggemann-Klein, 92), therefore FAdo implements them as lists. You should order exclusively, or take a set from a list in order to resolve repetitions.
- followListsD(lists=None)[source]¶
Map of each symbol’s follow list in the regular expression.
- Parameters
lists (dict) –
- Returns
map of symbols’ follow list {symbol: list of symbols}
- Return type
Attention
For first() and last() return lists, the follow list for certain symbols might have repetitions in the case of follow maps calculated from star operators. The union of last(), first() and follow() sets are always disjoint
See also
Sabine Broda, António Machiavelo, Nelma Moreira, and Rogério Reis. On the average size of glushkov and partial derivative automata. International Journal of Foundations of Computer Science, 23(5):969-984, 2012.
- followListsStar(lists=None)[source]¶
Map of each symbol’s follow list in the regular expression under a star.
- Parameters
lists (dict) –
- Returns
map of symbols’ follow lists {symbol: list of symbols}
- Return type
dict
See also
Sabine Broda, António Machiavelo, Nelma Moreira, and Rogério Reis. On the average size of glushkov and partial derivative automata. International Journal of Foundations of Computer Science, 23(5):969-984, 2012.
- last(parent_last=None)[source]¶
List of possible symbols matching the last symbol of a string in the language of the regular expression.
- linearForm()[source]¶
Linear form of the regular expression , as a mapping from heads to sets of tails, so that each pair (head, tail) is a monomial in the set of linear forms.
- Returns:
dict: dictionary mapping heads to sets of tails
See also
Antimirov, 95
- linearP()[source]¶
Whether the regular expression is linear; i.e., the occurrence of a symbol in the expression is unique.
- Return type
- static measure(from_parent=None)[source]¶
A list with four measures for regular expressions.
[alphabeticLength, treeLength, epsilonLength, starHeight]
alphabeticLength: number of occurences of symbols of the alphabet;
treeLength: number of functors in the regular expression, including constants.
epsilonLength: number of occurrences of the empty word.
starHeight: highest level of nested Kleene stars, starting at one for one star occurrence.
disjLength: number of occurrences of the disj operator
concatLength: number of occurrences of the concat operator
starLength: number of occurrences of the star operator
conjLength: number of occurrences of the conj operator
starLength: number of occurrences of the shuffle operator
Attention
Methods for each of the measures are implemented independently. This is the most effective for obtaining more than one measure.
- nfaThompson()[source]¶
Epsilon-NFA constructed with Thompson’s method that accepts the regular expression’s language.
- Returns
NFA Thompson
- Return type
See also
Thompson. Regular Expression Search Algorithm. CACM 11(6), 419-422 (1968)
- partialDerivatives(sigma)[source]¶
Set of partial derivatives of the regular expression in relation to given symbol.
- Parameters
sigma (str) – symbol in relation to which the derivative will be calculated.
- Returns
set of regular expressions
- Return type
See also
Antimirov, 95
- reduced(has_epsilon=False)[source]¶
Equivalent regular expression with the following cases simplified:
Epsilon.RE = RE.Epsilon = RE
EmptySet.RE = RE.EmptySet = EmptySet
EmptySet + RE = RE + EmptySet = RE
Epsilon + RE = RE + Epsilon = RE, where Epsilon is in L(RE)
RE** = RE*
EmptySet* = Epsilon* = Epsilon
7.Epsilon:RE = RE:Epsilon= RE
- Parameters
has_epsilon (bool) – used internally to indicate that the language of which this term is a subterm has the empty
word. –
- Returns
regular expression
- Return type
Attention
Returned structure isn’t strictly a duplicate. Use __copy__() for that purpose.
- setOfSymbols()[source]¶
Set of symbols that occur in a regular expression..
- Returns
set of symbols
- Return type
- static starHeight()[source]¶
- Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Return type
- stringLength()[source]¶
Length of the string representation of the regular expression.
- Returns
string length
- Return type
- support(side=True)[source]¶
Support of a regular expression.
- Parameters
side (bool) – if True concatenation of a set on the left if False on the right (prefix support)
- Returns
set of regular expressions
- Return type
See also
Champarnaud, J.M., Ziadi, D.: From Mirkin’s prebases to Antimirov’s word partial derivative. Fundam. Inform. 45(3), 195-205 (2001)
See also
Maia et al, Prefix and Right-partial derivative automata, 11th CIE 2015, 258-267 LNCS 9136, 2015
- static syntacticLength()[source]¶
Number of nodes of the regular expression’s syntactical tree (sets).
- Return type
- class CConcat(arg1, arg2, sigma=None)[source]¶
Class for catenation operation on regular expressions.

- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class CConj(arg1, arg2, sigma=None)[source]¶
Intersection operation of regexps
- class CDisj(arg1, arg2, sigma=None)[source]¶
Class for disjunction/union operation on regular expressions.

- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class CEmptySet(sigma=None)[source]¶
Class that represents the empty set.

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- class CEpsilon(sigma=None)[source]¶
Class that represents the empty word.

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- class COption(arg, sigma=None)[source]¶
Class for option operation (reg + @epsilon) on regular expressions.

- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class CShuffle(arg1, arg2, sigma=None)[source]¶
Shuffle operation of regexps
- class CShuffleU(arg, sigma=None)[source]¶
Unary Shuffle operation of regexps
- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- class CSigmaP(sigma=None)[source]¶
- Special regular expressions modulo associativity, commutativity, idempotence of disjunction and intersection;
associativity of concatenation; identities sigma^* and sigma^+.
CSigmaP: Class that represents the complement of the EmptySet word (sigma^+)

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- class CSigmaS(sigma=None)[source]¶
- Special regular expressions modulo associativity, commutativity, idempotence of disjunction and intersection;
associativity of concatenation; identities sigma^* and sigma^+.
CSigmaS: Class that represents the complement of the EmptySet set (sigma^*)

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- class CStar(arg, sigma=None)[source]¶
Class for iteration operation (aka Kleene star, or Kleene closure) on regular expressions.

- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class Compl(arg, sigma=None)[source]¶
Class for not operation on regular expressions.

- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- starHeight()[source]¶
Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Returns
number of nested star
- Return type
- 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. :returns: alphapetic length :rtype: int
Attention
Doesn’t include the empty word.
- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- 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.
Args: reg (RegExp): regular expression
- catLF(idl, idr, delay=False)[source]¶
Linear form for concatenation :param idl: node :type idl: int :param idr: node :type idr: int :param delay: if true partial derivatives are delayed :type delay: bool
- Returns
partial derivatives
- Return type
..note:: both arguments are assumed to be already present in the DAG
- getIdx(reg)[source]¶
Builds dag nodes :param reg: regular expression :type reg: regexp
- Returns
node id
- Return type
- 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
- class Position(val, sigma=None)[source]¶
Class for marked regular expression symbols.

Constructor of a regular expression symbol.
- Parameters
val – the actual symbol
- 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. :returns: alphapetic length :rtype: int
Attention
Doesn’t include the empty word.
- epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- followLists()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- 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. :returns: alphapetic length :rtype: int
Attention
Doesn’t include the empty word.
- compare(r, cmp_method='compareMinimalDFA', nfa_method='nfaPD')[source]¶
Compare with another regular expression for equivalence.
- compareMinimalDFA(r, nfa_method='nfaPosition')[source]¶
Compare with another regular expression for equivalence through minimal DFAs.
- 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
- Parameters
memo – if True memorizes the states already computed
- Returns
word derivatives automaton
- Return type
See also
Brzozowski, Derivatives of Regular Expressions. J. ACM 11(4): 481-494 (1964)
- dfaNaiveFollow()[source]¶
DFA that accepts the regular expression’s language, and is obtained from the follow automaton.
- Returns
DFA follow
- Return type
Note
Included for testing purposes.
See also
Ilie & Yu (Follow Automata, 2003)
- 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.
- Returns
number of epsilons
- Return type
- 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
- abstract followLists()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- abstract followListsD()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- 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.
- Returns
NFA follow
- 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 (bool) – if True automaton is trimmed at the end
- Returns
possibly with epsilon 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 position
- Return type
- nfaNaiveFollow()[source]¶
NFA that accepts the regular expression’s language, and is equal in structure to the follow automaton.
- Returns
NFA follow
- Return type
Note
Included for testing purposes.
See also
Ilie & Yu (Follow Automata, 2003)
- nfaPD(pdmethod='nfaPDDAG')[source]¶
Computes the partial derivative automaton
- Parameters
pdmethod (str) – an implementation of the PD automaton. Default value : nfaPDDAG
- Returns
a PD nfa
- Return type
Attention
for sre classes, CConj and CShuffle use nfaPDNaive directly
- nfaPDDAG()[source]¶
Partial derivative automaton using a DAG for the re and partial derivatives
- Returns
a PD nfa build using a DAG
- Return type
- ..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
partial derivatives [or equation] automaton
- Return type
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.
- Returns
partial derivatives [or equation] automaton
- Return type
Note
optimized version
- nfaPSNF()[source]¶
Position or Glushkov automaton of the regular expression constructed from the expression’s star normal form.
- Returns
Position automaton
- Return type
- nfaPre()[source]¶
Prefix NFA of a regular expression
- Returns
prefix automaton
- Return type
See also
Maia et al, Prefix and Right-partial derivative automata, 11th CIE 2015, 258-267 LNCS 9136, 2015
- 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.
- Returns
number of nested star
- Return type
- 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.
- Returns
tree lenght
- Return type
- 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

- followLists()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class SDisj(arg, sigma=None)[source]¶
Class that represents the disjunction operation for special regular expressions.

- 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

- followLists()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD()[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- class SStar(arg, sigma=None)[source]¶
- Special regular expressions modulo associativity, commutativity, idempotence of disjunction and intersection;
associativity of concatenation; identities sigma^* and sigma^+.
SStar: Class that represents Kleene star

- 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.
- Returns
number of epsilons
- Return type
- static starHeight()[source]¶
Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Returns
number of nested star
- Return type
- static treeLength()[source]¶
Number of nodes of the regular expression’s syntactical tree.
- Returns
tree lenght
- Return type
- class Unary(arg, sigma=None)[source]¶
Base class for unary operations: star, option, not, unary shuffle, etc

- alphabeticLength()[source]¶
Number of occurrences of alphabet symbols in the regular expression. :returns: alphapetic length :rtype: int
Attention
Doesn’t include the empty word.
- abstract epsilonLength()[source]¶
Number of occurrences of the empty word in the regular expression.
- Returns
number of epsilons
- Return type
- abstract ewp()[source]¶
Whether the empty word property holds for this regular expression’s language.
- Return type
- followLists(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- followListsD(lists=None)[source]¶
Follow set
- Returns
for each key position a set of follow positions
- Return type
- abstract starHeight()[source]¶
Maximum level of nested regular expressions with a star operation applied.
For instance, starHeight(((a*b)*+b*)*) is 3.
- Returns
number of nested star
- Return type
- equivalentP(first, second)[source]¶
Verifies if the two languages given by some representative (DFA, NFA or re) are equivalent
- Parameters
first – language
second – language
- Return type
New in version 0.9.6.
- powerset(iterable)[source]¶
Powerset of a set. :param iterable: the set :type iterable: list
- Returns
the powerset
- Return type
itertools.chain
- rpn2regexp(s, sigma=None, strict=False)[source]¶
Reads a (simple) RegExp from a RPN representation
r ::= .RR | +RR | *r | L | @ L ::= [a-z] | [A-Z]
- Parameters
- Return type
Note
This method uses python stack… thus depth limitations apply
- 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
FAdo.transducers¶
Finite Tranducer Support
Transducer manipulation.
New in version 1.0.
- 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
- class NFT[source]¶
Normal Form Transducer.
Transsitions here have labels of the form (s,Epsilon) or (Epsilon,s)

- class SFT[source]¶
Standard Form Tranducer
- Variables
Output (set) – output alphabet

- addEpsilonLoops()[source]¶
Add a loop transition with epsilon 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
- concatN(x, y)[source]¶
Concatenation of tuples of words :param x: iterable :param y: iterable :return: iterable
- hypercodeTransducer(alphabet, preserving=False)[source]¶
Creates an hypercode property transducer based on given alphabet
- infixTransducer(alphabet, preserving=False)[source]¶
Creates an infix property transducer based on given alphabet
- 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(alphabet, preserving=False)[source]¶
Creates an outfix property transducer based on given alphabet
FAdo.fl¶
Finite languages and related automata manipulation
Finite languages manipulation
- 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.
- 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
- 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
- DFAtoADFA(aut)[source]¶
Transforms an acyclic DFA into a ADFA
- Parameters
aut (DFA) – the automaton to be transformed
- Raises
notAcyclic – if the DFA is not acyclic
- Returns
the converted automaton
- Return type
- class DFCA[source]¶
Deterministic Cover Automata class

- property length¶
size of the longest word :rtype: int
- Type
return
- 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
- diff(other)[source]¶
Difference of FL: a - b
- Parameters
other (FL) – right hand operand
- Return type
- Raises
FAdoGeneralError – if both arguments are not FL
- 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.
- trieFA()[source]¶
Generates the trie automaton that recognises this language
- Returns
the trie automaton
- Return type
- union(other)[source]¶
union of FL: a | b
- Parameters
other (FL) – right hand operand
- Return type
- Raises
FAdoGeneralError – if both arguments are not FL
- class RndWGen(aut)[source]¶
Word random generator class
New in version 1.2.
- Parameters
aut (ADFA) – automata recognizing the language
- 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
- 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
- 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
- genRndTrieUnbalanced(maxL, Sigma, ratio, safe=True)[source]¶
Generates a random trie automaton for a binary language of balanced words of a given length for max word
- sigmaInitialSegment(Sigma, l, exact=False)[source]¶
Generates the ADFA recognizing sigma^i for i<=l :param set Sigma: the alphabet :param int l: length :param bool exact: only the words with exactly that length? :returns: the automaton :rtype: ADFA
- 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.
FAdo.cgf¶
Context Free Grammars Manipulation.
Basic context-free grammars manipulation for building uniform random generetors
- class CFGGenerator(cfgr, size)[source]¶
CFG uniform genetaror
- ..seealso: Generating words in a context-free language uniformly at random. Harry Mairson
Information Processing Letters, 49-2, 95-92. 1994
Object initialization :param cfgr: grammar for the random objects :type cfgr: CNF :param size: size of objects :type size: integer
- 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
- 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
- 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
FAdo.rndfap¶
Random DFA generation (alternative version in python)
ICDFA Random generation binding
New in version 1.0.
- 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
- class ICDFArnd(n, k, seed=0)[source]¶
Complete ICDFA random generator class
This is the class for the uniform random generator for Initially Connected DFAs
- Variables
Note
This is an abstract class, not to be used directly
Changed in version 1.3.4: seed added to the random generator
- class ICDFArndIncomplete(n, k, bias=None, seed=0)[source]¶
Incomplete ICDFA random generator class
- Variables
- Raises
IllegalBias – if a bias >=1 or <=0 is provided
Changed in version 1.3.4: seed added to the random generator
FAdo.rndadfa¶
Random ADFA generation
ADFA Random generation binding
New in version 1.2.1.
- 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
- countadfaL(n, k)[source]¶
Acyclic (complete) deterministic finite automata structure (labeled) initially connected (one dead state)
FAdo.comboperations¶
Several combined operations for DFAs
Combined operations
- concatWStar(fa1, fa2, strict=False)[source]¶
Concatenation combined with star: (L1.L2*)
- Parameters
- Return type
See also
Bo Cui, Yuan Gao, Lila Kari, and Sheng Yu. ‘State complexity of two combined operations: Reversal-catenation and star-catenation’. CoRR, abs/1006.4646, 2010.
- disjWStar(f1, f2, strict=True)[source]¶
Union with Star: (L1 + L2*)
- Parameters
- Return type
See also
Yuan Gao and Sheng Yu. ‘State complexity of union and intersection combined with Star and reversal’. CoRR, abs/1006.3755, 2010.
- interWStar(f1, f2, strict=True)[source]¶
Intersection with Star: (L1 & L2*)
- Parameters
- Return type
See also
Yuan Gao and Sheng Yu. ‘State complexity of union and intersection combined with Star and reversal’. CoRR, abs/1006.3755, 2010.
- starConcat(fa1, fa2, strict=False)[source]¶
Star of concatenation of two languages: (L1.L2)*
- Parameters
- Return type
See also
Yuan Gao, Kai Salomaa, and Sheng Yu. ‘The state complexity of two combined operations: star of catenation and star of reversal’. Fundamenta Informaticae, 83:75–89, Jan 2008.
- starDisj(fa1, fa2, strict=False)[source]¶
Star of Union of two DFAs: (L1 + L2)*
- Parameters
- Return type
See also
Arto Salomaa, Kai Salomaa, and Sheng Yu. ‘State complexity of combined operations’. Theor. Comput. Sci., 383(2-3):140–152, 2007.
- starInter0(fa1, fa2, strict=False)[source]¶
Star of Intersection of two DFAs: (L1 & L2)*
- Parameters
- Return type
See also
Arto Salomaa, Kai Salomaa, and Sheng Yu. ‘State complexity of combined operations’. Theor. Comput. Sci., 383(2-3):140–152, 2007.
FAdo.codes¶
Code theory module
New in version 1.0.
- 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
- class ErrCorrectProp(t)[source]¶
Error Correcting Property

Constructor :param SFT aut: Input preserving transducer
- ErrDetectProp¶
alias of
FAdo.codes.IPTProp
- class FixedProp(name, alph)[source]¶
Abstract class for fixed properties
- class IATProp(aut, name=None)[source]¶
Input Altering Transducer Property

Constructor :param SFT aut: Input preserving transducer
- 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
- class UDCodeProp(alphabet)[source]¶
Uniquely decodable Code Property

- maximalP(aut, U=None)[source]¶
Tests if the language is maximal w.r.t. the property :param DFA|NFA aut: the automaton :param DFA|NFA U: Universe of permitted words (sigma^* as default) :rtype: bool
- buildErrorCorrectPropF(fname)[source]¶
Builds an Error Correcting Property
- Parameters
fname (str) – file name
- Return type
- buildErrorCorrectPropS(s)[source]¶
Builds an Error Correcting Property from string
- Parameters
s (str) – transducer string
- Return type
- buildErrorDetectPropF(fname)[source]¶
Builds an Error Detecting Property
- Parameters
fname (str) – file name
- Return type
ErrDetectProp
- buildErrorDetectPropS(s)[source]¶
Builds an Error Detecting Property from string
- Parameters
s (str) – transducer string
- Return type
ErrDetectProp
- buildHypercodeProperty(alphabet)[source]¶
Builds a Hypercode Property
- Parameters
alphabet (set) – alphabet
- Return type
- buildInfixProperty(alphabet)[source]¶
Builds a Suffix Code Property
- Parameters
alphabet (set) – alphabet
- Return type
- buildOutfixProperty(alphabet)[source]¶
Builds a Outfix Code Property
- Parameters
alphabet (set) – alphabet
- Return type
- buildPrefixProperty(alphabet)[source]¶
Builds a Prefix Code Property
- Parameters
alphabet (set) – alphabet
- Return type
- buildSuffixProperty(alphabet)[source]¶
Builds a Suffix Code Property
- Parameters
alphabet (set) – alphabet
- Return type
- buildUDCodeProperty(alphabet)[source]¶
Builds a UDCodeProp (from thin air ;-)
- Parameters
alphabet (set) – alphabet
- Return type
- constructCode(n, l, p, ipt=False, seed=None)[source]¶
- Returns up to n words of length l satisfying the property p, the first one being seed.
If ipt is True, the property is assumed to be input-preserving transducer type
- Return type
- 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(aut)[source]¶
- Checks if language density is exponential
Using breadth first search (BFS)
Attention
aut should not have Epsilon transitions
- fixedHierSubset(x, y)[source]¶
Returns whether x==y, or the fixed property with name x is a subset of y Currently (Jan 2015) the fixed properties names are ‘UD_codes’, ‘Prefix_codes’, ‘Suffix_codes’, ‘Infix_codes’, ‘Outfix_codes’, ‘Hypercodes’
- isSubclass(p1, p2)[source]¶
- Which property (language class) is a subclass of the other (if any).
It returns 1 if p1 is a subclass of p2; 2 if p2 is a subclass of p1; 3 if they are equal; 0 otherwise
- long2base(n, q)[source]¶
Maps n to a list of digits corresponding to the base q representation of n in reverse order
- notUniversalStatW(a, l, maxIter=20000)[source]¶
Tests statistically whether the NFA a is l-non-universal, by evaluating a on <= maxIter randomly chosen words of length l
- symmAndRefl(t, ipt=False)[source]¶
- Return the transducer t | t.inverse, if ipt is True;
return the transducer t | t.inverse | id, otherwise
- Return type
FAdo.sst¶
Set Specification Transducer supportt
New in version 1.4.
- class PSPDiff(arg1, arg2)[source]¶
Relation pair of two set specifications (constrained by non equality)
- class PSPVanila(arg1, arg2)[source]¶
Relation pair of two set specifications
- SSConditionalNoneOf(oset)[source]¶
Auxiliary function that coalesces an SSNoneOf into an SSAnyOf if oset is empty
- class SSFA(alph)[source]¶
NFAs with Set Specifications as transition labels
- Parameters
alph – alphabet
- addEpsilonLoops()[source]¶
Add epsilon loops to every state
Attention
in-place modification
New in version 1.0.
- class SST(sigma=None)[source]¶
SFT with set specification labels

- addEpsilonLoops()[source]¶
Add a loop transition with epsilon input and output to every state in the transducer.
- addToSigma(sym)[source]¶
Adds a new symbol to the alphabet (it it is not already there)
- Parameters
sym (unicode) – symbol to add
- Return type
- Returns
the index of the new symbol
- addTransitionProductQ(src, dest, ddest, sym, futQ, pastQ)[source]¶
Add transition to the new transducer instance.
Version for the optimized product
- 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.
- inverse()[source]¶
Switch the input label with the output label.
No initial or final state changed.
- Returns
Transducer with transitions switched.
- 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.
- reversal()[source]¶
Returns a transducer that recognizes the reversal of the relation.
- Returns
Transducer recognizing reversal language
- Return type
- toInSSFA()[source]¶
Delete the output labels in the transducer. Translate it into an SSFA
- Return type
- 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
FAdo.prax¶
Polynomial Random Approximation Algorithms
- class GenWordDis(f, alf, e)[source]¶
Word generator according to a given distribution funtion (used for sizes), for prax test
- f_dirichlet(n, d=1, t=2.000001)[source]¶
Dirichlet distribution function
- Parameters
- Return type
New in version 2.0.4.
- f_laplace(n, d=1, z=0.99)[source]¶
Laplace distribution function
- Parameters
- Return type
- Raises
FAdoGeneralError – if z is null
- minI(a, t, u=None)[source]¶
An operator that returns a t-independent language containing L(a)
- Parameters
a (FA) – the initial automaton
t (Transducer) – input-altering transducer
u (FA | None) – universe to consider
- Return type
- prax_univ_nfa(g, a, debug=False)[source]¶
Polynomial Randomized Approximation (PRAX) to NFA universality
- Parameters
- Return type
See also
S.Konstantinidis, M.Mastnak, N.Moreira, R.Reis. Approximate NFA Universality and Related Problems Motivated by Information Theory, arXiv, 2022.
New in version 2.0.4.
- random() x in the interval [0, 1).¶
- unive_index(g, aut, prop)[source]¶
Universality index of a automaton for a given distribution
- Parameters
g (GenWordDis) – distribution
aut (FA) – automaton
- Returns
universality index
- Return type
FAdo.graphs¶
Graph support
Basic Graph object support and manipulation
- class DiGraph[source]¶
Directed graph base class

- class DiGraphVm[source]¶
Directed graph with marked vertices
- Variables
MarkedV (set) – set of marked vertices

- 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
- vertexIndex(vname, autoCreate=False)[source]¶
Return vertex index
- Parameters
autoCreate (bool) – auto creation of non existing states
vname – vertex name
- Return type
- Raises
GraphError – if vname not found
![digraph dij {
"0" -> "si1" [label=e];
"si1" -> "sf1" [label="arg1"];
"sf1" -> "1" [label=e];
"0" -> "si2" [label=e];
"si2" -> "sf2" [label="arg2"];
"sf2" -> "1" [label=e];
}](_images/graphviz-73613cbb0449aec2b417511035e7a3f1c55a94f8.png)
![digraph foo {
"0" -> "1" [label=e];
"0" -> "a" [label=e];
"a" -> "b" [label=A];
"b" -> "1" [label=e];
}](_images/graphviz-67f64b6ad484334ce45721576e7ae349d8126cbd.png)
![digraph foo {
"0" -> "1" [label=e];
"0" -> "a" [label=e];
"a" -> "b" [label=A];
"b" -> "1" [label=e];
"1" -> "0" [label=e];
}](_images/graphviz-491c498f4314c2a9f19dacbde27bfa8f7268a32e.png)




