# Finite State Machines, Automata, Transducers¶

This module adds support for finite state machines, automata and transducers. See class FiniteStateMachine and the examples below for details creating one.

## Examples¶

### A simple finite state machine¶

We can easily create a finite state machine by

sage: fsm = FiniteStateMachine()
sage: fsm
Finite state machine with 0 states


By default this is the empty finite state machine, so not very interesting. Let’s create some states and transitions:

sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition
sage: day = FSMState('day')
sage: night = FSMState('night')
sage: sunrise = FSMTransition(night, day)
sage: sunset = FSMTransition(day, night)


And now let’s add those states and transitions to our finite state machine:

sage: fsm.add_transition(sunrise)
Transition from 'night' to 'day': -|-
Transition from 'day' to 'night': -|-


Note that the states are added automatically, since they are present in the transitions. We could add the states manually by

sage: fsm.add_state(day)
'day'
'night'


Anyhow, we got the following finite state machine:

sage: fsm
Finite state machine with 2 states


We can also visualize it as a graph by

sage: fsm.graph()
Digraph on 2 vertices


Alternatively, we could have created the finite state machine above simply by

sage: FiniteStateMachine([('night', 'day'), ('day', 'night')])
Finite state machine with 2 states


or by

sage: fsm = FiniteStateMachine()
sage: fsm
Finite state machine with 2 states


### A simple Automaton (recognizing NAFs)¶

We want to build an automaton which recognizes non-adjacent forms (NAFs), i.e., sequences which have no adjacent non-zeros. We use $$0$$, $$1$$, and $$-1$$ as digits:

sage: NAF = Automaton(
....:     {'A': [('A', 0), ('B', 1), ('B', -1)], 'B': [('A', 0)]})
sage: NAF.state('A').is_initial = True
sage: NAF.state('A').is_final = True
sage: NAF.state('B').is_final = True
sage: NAF
Automaton with 2 states


Of course, we could have specified the initial and final states directly in the definition of NAF by initial_states=['A'] and final_states=['A', 'B'].

So let’s test the automaton with some input:

sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False  # activate new output behavior
sage: NAF([0])
True
sage: NAF([0, 1])
True
sage: NAF([1, -1])
False
sage: NAF([0, -1, 0, 1])
True
sage: NAF([0, -1, -1, -1, 0])
False
sage: NAF([-1, 0, 0, 1, 1])
False


Alternatively, we could call that by

sage: NAF.process([0, -1, 0, 1])
(True, 'B')


which gives additionally the state in which we arrived.

### A simple transducer (binary inverter)¶

Let’s build a simple transducer, which rewrites a binary word by iverting each bit:

sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])


We can look at the states and transitions:

sage: inverter.states()
['A']
sage: for t in inverter.transitions():
....:     print t
Transition from 'A' to 'A': 0|1
Transition from 'A' to 'A': 1|0


Now we apply a word to it and see what the transducer does:

sage: inverter([0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1])
[1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0]


True means, that we landed in a final state, that state is labeled 'A', and we also got an output.

### A transducer which performs division by $$3$$ in binary¶

Now we build a transducer, which divides a binary number by $$3$$. The labels of the states are the remainder of the division. The transition function is

sage: def f(state_from, read):
....:     if state_from + read <= 1:
....:         state_to = 2*state_from + read
....:         write = 0
....:     else:
....:         state_to = 2*state_from + read - 3
....:         write = 1
....:     return (state_to, write)


which assumes reading a binary number from left to right. We get the transducer with

sage: D = Transducer(f, initial_states=[0], final_states=[0],
....:                input_alphabet=[0, 1])


Let us try to divide $$12$$ by $$3$$:

sage: D([1, 1, 0, 0])
[0, 1, 0, 0]


Now we want to divide $$13$$ by $$3$$:

sage: D([1, 1, 0, 1])
Traceback (most recent call last):
...
ValueError: Invalid input sequence.


The raised ValueError means $$13$$ is not divisible by $$3$$.

### Using the hook-functions¶

Let’s use the previous example “divison by $$3$$” to demonstrate the optional state and transition parameters hook.

First, we define, what those functions should do. In our case, this is just saying in which state we are and which transition we take

sage: def state_hook(state, process):
....:     print "We are now in State %s." % (state.label(),)
sage: from sage.combinat.finite_state_machine import FSMWordSymbol
sage: def transition_hook(transition, process):
....:     print ("Currently we go from %s to %s, "
....:            "reading %s and writing %s." % (
....:                transition.from_state, transition.to_state,
....:                FSMWordSymbol(transition.word_in),
....:                FSMWordSymbol(transition.word_out)))


Now, let’s add these hook-functions to the existing transducer:

sage: for s in D.iter_states():
....:     s.hook = state_hook
sage: for t in D.iter_transitions():
....:     t.hook = transition_hook


Rerunning the process again now gives the following output:

sage: D.process([1, 1, 0, 1])
We are now in State 0.
Currently we go from 0 to 1, reading 1 and writing 0.
We are now in State 1.
Currently we go from 1 to 0, reading 1 and writing 1.
We are now in State 0.
Currently we go from 0 to 0, reading 0 and writing 0.
We are now in State 0.
Currently we go from 0 to 1, reading 1 and writing 0.
We are now in State 1.
(False, 1, [0, 1, 0, 0])


The example above just explains the basic idea of using hook-functions. In the following, we will use those hooks more seriously.

### Detecting sequences with same number of $$0$$ and $$1$$¶

Suppose we have a binary input and want to accept all sequences with the same number of $$0$$ and $$1$$. This cannot be done with a finite automaton. Anyhow, we can make usage of the hook functions to extend our finite automaton by a counter:

sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition
sage: C = FiniteStateMachine()
sage: def update_counter(state, process):
....:     process.fsm.counter += 1 if l == 1 else -1
....:     if process.fsm.counter > 0:
....:         next_state = 'positive'
....:     elif process.fsm.counter < 0:
....:         next_state = 'negative'
....:     else:
....:         next_state = 'zero'
....:     return FSMTransition(state, process.fsm.state(next_state),
....:                          l, process.fsm.counter)
....:             is_initial=True, is_final=True))
'zero'
'positive'
'negative'


Now, let’s input some sequence:

sage: C.counter = 0; C([1, 1, 1, 1, 0, 0])
(False, 'positive', [1, 2, 3, 4, 3, 2])


The result is False, since there are four $$1$$ but only two $$0$$. We land in the state positive and we can also see the values of the counter in each step.

Let’s try some other examples:

sage: C.counter = 0; C([1, 1, 0, 0])
(True, 'zero', [1, 2, 1, 0])
sage: C.counter = 0; C([0, 1, 0, 0])
(False, 'negative', [-1, 0, -1, -2])


AUTHORS:

• Daniel Krenn (2012-03-27): initial version

• Clemens Heuberger (2012-04-05): initial version

• Sara Kropf (2012-04-17): initial version

• Clemens Heuberger (2013-08-21): release candidate for Sage patch

• Daniel Krenn (2013-08-21): release candidate for Sage patch

• Sara Kropf (2013-08-21): release candidate for Sage patch

• Clemens Heuberger (2013-09-02): documentation improved

• Daniel Krenn (2013-09-13): comments from trac worked in

• Clemens Heuberger (2013-11-03): output (labels) of determinisation,

product, composition, etc. changed (for consistency), representation of state changed, documentation improved

• Daniel Krenn (2013-11-04): whitespaces in documentation corrected

• Clemens Heuberger (2013-11-04): full_group_by added

• Daniel Krenn (2013-11-04): next release candidate for Sage patch

• Sara Kropf (2013-11-08): fix for adjacency matrix

• Clemens Heuberger (2013-11-11): fix for prepone_output

• Daniel Krenn (2013-11-11): comments from trac 15078 included:

docstring of FiniteStateMachine rewritten, Automaton and Transducer inherited from FiniteStateMachine

• Daniel Krenn (2013-11-25): documentation improved according to

ACKNOWLEDGEMENT:

• Daniel Krenn, Clemens Heuberger and Sara Kropf are supported by the Austrian Science Fund (FWF): P 24644-N26.
class sage.combinat.finite_state_machine.Automaton(data=None, initial_states=None, final_states=None, input_alphabet=None, output_alphabet=None, determine_alphabets=None, store_states_dict=True, on_duplicate_transition=None)

This creates an automaton, which is a finite state machine, whose transitions have input labels.

An automaton has additional features like creating a deterministic and a minimized automaton.

EXAMPLES:

We can create an automaton recognizing even numbers (given in binary and read from left to right) in the following way:

sage: A = Automaton([('P', 'Q', 0), ('P', 'P', 1),
....:                ('Q', 'P', 1), ('Q', 'Q', 0)],
....:               initial_states=['P'], final_states=['Q'])
sage: A
Automaton with 2 states
sage: A([0])
True
sage: A([1, 1, 0])
True
sage: A([1, 0, 1])
False


Note that the full output of the commands can be obtained by calling process() and looks like this:

sage: A.process([1, 0, 1])
(False, 'P')


TESTS:

sage: Automaton()
Automaton with 0 states

cartesian_product(other, only_accessible_components=True)

Returns a new automaton which accepts an input if it is accepted by both given automata.

INPUT:

• other – an automaton
• only_accessible_components – If True (default), then the result is piped through accessible_components. If no new_input_alphabet is given, it is determined by determine_alphabets().

OUTPUT:

A new automaton which computes the intersection (see below) of the languages of self and other.

The set of states of the new automaton is the cartesian product of the set of states of both given automata. There is a transition $$((A, B), (C, D), a)$$ in the new automaton if there are transitions $$(A, C, a)$$ and $$(B, D, a)$$ in the old automata.

The methods intersection() and cartesian_product() are the same (for automata).

EXAMPLES:

sage: aut1 = Automaton([('1', '2', 1),
....:                   ('2', '2', 1),
....:                   ('2', '2', 0)],
....:                  initial_states=['1'],
....:                  final_states=['2'],
....:                  determine_alphabets=True)
sage: aut2 = Automaton([('A', 'A', 1),
....:                   ('A', 'B', 0),
....:                   ('B', 'B', 0),
....:                   ('B', 'A', 1)],
....:                  initial_states=['A'],
....:                  final_states=['B'],
....:                  determine_alphabets=True)
sage: res = aut1.intersection(aut2)
sage: (aut1([1, 1]), aut2([1, 1]), res([1, 1]))
(True, False, False)
sage: (aut1([1, 0]), aut2([1, 0]), res([1, 0]))
(True, True, True)
sage: res.transitions()
[Transition from ('1', 'A') to ('2', 'A'): 1|-,
Transition from ('2', 'A') to ('2', 'B'): 0|-,
Transition from ('2', 'A') to ('2', 'A'): 1|-,
Transition from ('2', 'B') to ('2', 'B'): 0|-,
Transition from ('2', 'B') to ('2', 'A'): 1|-]


For automata with epsilon-transitions, intersection is not well defined. But for any finite state machine, epsilon-transitions can be removed by remove_epsilon_transitions().

sage: a1 = Automaton([(0, 0, 0),
....:                 (0, 1, None),
....:                 (1, 1, 1),
....:                 (1, 2, 1)],
....:                 initial_states=[0],
....:                 final_states=[1],
....:                 determine_alphabets=True)
sage: a2 = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 1)],
....:                 initial_states=[0],
....:                 final_states=[1],
....:                 determine_alphabets=True)
sage: a1.intersection(a2)
Traceback (most recent call last):
...
ValueError: An epsilon-transition (with empty input)
was found.
sage: a1.remove_epsilon_transitions()  # not tested (since not implemented yet)
sage: a1.intersection(a2)  # not tested

determinisation()

Returns a deterministic automaton which accepts the same input words as the original one.

INPUT:

Nothing.

OUTPUT:

A new automaton, which is deterministic.

The labels of the states of the new automaton are frozensets of states of self. The color of a new state is the frozenset of colors of the constituent states of self. Therefore, the colors of the constituent states have to be hashable.

The input alphabet must be specified. It is restricted to nice cases: input words have to have length at most $$1$$.

EXAMPLES:

sage: aut = Automaton([('A', 'A', 0), ('A', 'B', 1), ('B', 'B', 1)],
....:                 initial_states=['A'], final_states=['B'])
sage: aut.determinisation().transitions()
[Transition from frozenset(['A'])
to frozenset(['A']): 0|-,
Transition from frozenset(['A'])
to frozenset(['B']): 1|-,
Transition from frozenset(['B'])
to frozenset([]): 0|-,
Transition from frozenset(['B'])
to frozenset(['B']): 1|-,
Transition from frozenset([])
to frozenset([]): 0|-,
Transition from frozenset([])
to frozenset([]): 1|-]

sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1),
....:                ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)],
....:               initial_states=['A'], final_states=['C'])
sage: A.determinisation().states()
[frozenset(['A']), frozenset(['A', 'B']),
frozenset(['A', 'C']), frozenset(['A', 'C', 'B'])]


Note that colors of states have to be hashable:

sage: A = Automaton([[0, 0, 0]], initial_states=[0])
sage: A.state(0).color = []
sage: A.determinisation()
Traceback (most recent call last):
...
TypeError: unhashable type: 'list'
sage: A.state(0).color = ()
sage: A.determinisation()
Automaton with 1 states


TESTS:

This is from #15078, comment 13.

sage: D = {'A': [('A', 'a'), ('B', 'a'), ('A', 'b')],
....:      'C': [], 'B': [('C', 'b')]}
sage: auto = Automaton(D, initial_states=['A'], final_states=['C'])
sage: auto.is_deterministic()
False
sage: auto.process(list('aaab'))
(False, 'A')
sage: auto.states()
['A', 'C', 'B']
sage: auto.determinisation()
Automaton with 3 states

intersection(other, only_accessible_components=True)

Returns a new automaton which accepts an input if it is accepted by both given automata.

INPUT:

• other – an automaton
• only_accessible_components – If True (default), then the result is piped through accessible_components. If no new_input_alphabet is given, it is determined by determine_alphabets().

OUTPUT:

A new automaton which computes the intersection (see below) of the languages of self and other.

The set of states of the new automaton is the cartesian product of the set of states of both given automata. There is a transition $$((A, B), (C, D), a)$$ in the new automaton if there are transitions $$(A, C, a)$$ and $$(B, D, a)$$ in the old automata.

The methods intersection() and cartesian_product() are the same (for automata).

EXAMPLES:

sage: aut1 = Automaton([('1', '2', 1),
....:                   ('2', '2', 1),
....:                   ('2', '2', 0)],
....:                  initial_states=['1'],
....:                  final_states=['2'],
....:                  determine_alphabets=True)
sage: aut2 = Automaton([('A', 'A', 1),
....:                   ('A', 'B', 0),
....:                   ('B', 'B', 0),
....:                   ('B', 'A', 1)],
....:                  initial_states=['A'],
....:                  final_states=['B'],
....:                  determine_alphabets=True)
sage: res = aut1.intersection(aut2)
sage: (aut1([1, 1]), aut2([1, 1]), res([1, 1]))
(True, False, False)
sage: (aut1([1, 0]), aut2([1, 0]), res([1, 0]))
(True, True, True)
sage: res.transitions()
[Transition from ('1', 'A') to ('2', 'A'): 1|-,
Transition from ('2', 'A') to ('2', 'B'): 0|-,
Transition from ('2', 'A') to ('2', 'A'): 1|-,
Transition from ('2', 'B') to ('2', 'B'): 0|-,
Transition from ('2', 'B') to ('2', 'A'): 1|-]


For automata with epsilon-transitions, intersection is not well defined. But for any finite state machine, epsilon-transitions can be removed by remove_epsilon_transitions().

sage: a1 = Automaton([(0, 0, 0),
....:                 (0, 1, None),
....:                 (1, 1, 1),
....:                 (1, 2, 1)],
....:                 initial_states=[0],
....:                 final_states=[1],
....:                 determine_alphabets=True)
sage: a2 = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 1)],
....:                 initial_states=[0],
....:                 final_states=[1],
....:                 determine_alphabets=True)
sage: a1.intersection(a2)
Traceback (most recent call last):
...
ValueError: An epsilon-transition (with empty input)
was found.
sage: a1.remove_epsilon_transitions()  # not tested (since not implemented yet)
sage: a1.intersection(a2)  # not tested

minimization(algorithm=None)

Returns the minimization of the input automaton as a new automaton.

INPUT:

• algorithm – Either Moore’s algorithm (by algorithm='Moore' or as default for deterministic automata) or Brzozowski’s algorithm (when algorithm='Brzozowski' or when the automaton is not deterministic) is used.

OUTPUT:

A new automaton.

The resulting automaton is deterministic and has a minimal number of states.

EXAMPLES:

sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1),
....:                ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)],
....:               initial_states=['A'], final_states=['C'])
sage: B = A.minimization(algorithm='Brzozowski')
sage: B.transitions(B.states()[1])
[Transition from frozenset([frozenset(['A', 'C', 'B']),
frozenset(['C', 'B']), frozenset(['A', 'C'])]) to
frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']),
frozenset(['A', 'C']), frozenset(['C'])]): 0|-,
Transition from frozenset([frozenset(['A', 'C', 'B']),
frozenset(['C', 'B']), frozenset(['A', 'C'])]) to
frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']),
frozenset(['A', 'C'])]): 1|-]
sage: len(B.states())
3
sage: C = A.minimization(algorithm='Brzozowski')
sage: C.transitions(C.states()[1])
[Transition from frozenset([frozenset(['A', 'C', 'B']),
frozenset(['C', 'B']), frozenset(['A', 'C'])]) to
frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']),
frozenset(['A', 'C']), frozenset(['C'])]): 0|-,
Transition from frozenset([frozenset(['A', 'C', 'B']),
frozenset(['C', 'B']), frozenset(['A', 'C'])]) to
frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']),
frozenset(['A', 'C'])]): 1|-]
sage: len(C.states())
3

sage: aut = Automaton([('1', '2', 'a'), ('2', '3', 'b'),
....:                  ('3', '2', 'a'), ('2', '1', 'b'),
....:                  ('3', '4', 'a'), ('4', '3', 'b')],
....:                  initial_states=['1'], final_states=['1'])
sage: min = aut.minimization(algorithm='Brzozowski')
sage: [len(min.states()), len(aut.states())]
[3, 4]
sage: min = aut.minimization(algorithm='Moore')
Traceback (most recent call last):
...
NotImplementedError: Minimization via Moore's Algorithm is only
implemented for deterministic finite state machines

process(*args, **kwargs)

Warning

The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting FSMOldProcessOutput to False.

Returns whether the automaton accepts the input and the state where the computation stops.

INPUT:

• input_tape – The input tape can be a list with entries from the input alphabet.
• initial_state – (default: None) The state in which to start. If this parameter is None and there is only one initial state in the machine, then this state is taken.
• full_output – (default: True) If set, then the full output is given, otherwise only whether the sequence is accepted or not (the first entry below only).

OUTPUT:

The full output is a pair, where

• the first entry is True if the input string is accepted and
• the second gives the state reached after processing the input tape (This is a state with label None if the input could not be processed, i.e., when at one point no transition to go could be found.).

Note that in the case the automaton is not deterministic, one possible path is gone. This means that in this case the output can be wrong. Use determinisation() to get a deterministic automaton machine and try again.

By setting FSMOldProcessOutput to False the new desired output is produced.

EXAMPLES:

sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False  # activate new output behavior
sage: from sage.combinat.finite_state_machine import FSMState
sage: NAF_ = FSMState('_', is_initial = True, is_final = True)
sage: NAF1 = FSMState('1', is_final = True)
sage: NAF = Automaton(
....:     {NAF_: [(NAF_, 0), (NAF1, 1)], NAF1: [(NAF_, 0)]})
sage: [NAF.process(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],
....:                           [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]
[(True, '_'), (True, '1'), (False, None),
(True, '1'), (False, None), (False, None)]


If we just want a condensed output, we use:

sage: [NAF.process(w, full_output=False)
....:     for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],
....:               [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]
[True, True, False, True, False, False]


It is equivalent to:

sage: [NAF(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],
....:                   [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]
[True, True, False, True, False, False]


The following example illustrates the difference between non-existing paths and reaching a non-final state:

sage: NAF.process([2])
(False, None)
Transition from '_' to 's': 2|-
sage: NAF.process([2])
(False, 's')

sage.combinat.finite_state_machine.FSMLetterSymbol(letter)

Returns a string associated to the input letter.

INPUT:

• letter – the input letter or None (representing the empty word).

OUTPUT:

If letter is None the symbol for the empty word FSMEmptyWordSymbol is returned, otherwise the string associated to the letter.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMLetterSymbol
sage: FSMLetterSymbol(0)
'0'
sage: FSMLetterSymbol(None)
'-'

class sage.combinat.finite_state_machine.FSMProcessIterator(fsm, input_tape=None, initial_state=None, **kwargs)

This class is for processing an input string on a finite state machine.

An instance of this class is generated when FiniteStateMachine.process() or FiniteStateMachine.iter_process() of the finite state machine is invoked. It behaves like an iterator which, in each step, takes one letter of the input and runs (one step on) the finite state machine with this input. More precisely, in each step, the process iterator takes an outgoing transition of the current state, whose input label equals the input letter of the tape. The output label of the transition, if present, is written on the output tape.

INPUT:

• fsm – The finite state machine on which the input should be processed.
• input_tape – The input tape. It can be anything that is iterable.
• initial_state – The initial state in which the machine starts. If this is None, the unique inital state of the finite state machine is takes. If there are several, a ValueError is raised.

The process (iteration) stops if there are no more input letters on the tape. In this case a StopIteration exception is thrown. As result the following attributes are available:

• accept_input – Is True if the reached state is a final state.
• current_state – The current/reached state in the process.
• output_tape – The written output.

Current values of those attributes (except accept_input) are (also) available during the iteration.

OUTPUT:

An iterator.

EXAMPLES:

The following transducer reads binary words and outputs a word, where blocks of ones are replaced by just a single one. Further only words that end with a zero are accepted.

sage: T = Transducer({'A': [('A', 0, 0), ('B', 1, None)],
....:                 'B': [('B', 1, None), ('A', 0, [1, 0])]},
....:     initial_states=['A'], final_states=['A'])
sage: input = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0]
sage: T.process(input)
(True, 'A', [1, 0, 0, 1, 0, 1, 0])


The function FiniteStateMachine.process() created a new FSMProcessIterator. We can do that manually, too, and get full access to the iteration process:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: it = FSMProcessIterator(T, input_tape=input)
sage: for _ in it:
....:     print (it.current_state, it.output_tape)
('B', [])
('B', [])
('A', [1, 0])
('A', [1, 0, 0])
('B', [1, 0, 0])
('A', [1, 0, 0, 1, 0])
('B', [1, 0, 0, 1, 0])
('B', [1, 0, 0, 1, 0])
('B', [1, 0, 0, 1, 0])
('A', [1, 0, 0, 1, 0, 1, 0])
sage: it.accept_input
True


TESTS:

sage: T = Transducer([[0, 0, 0, 0]])
sage: T.process([])
Traceback (most recent call last):
...
ValueError: No state is initial.

sage: T = Transducer([[0, 1, 0, 0]], initial_states=[0, 1])
sage: T.process([])
Traceback (most recent call last):
...
ValueError: Several initial states.

get_next_transition(word_in)

Returns the next transition according to word_in. It is assumed that we are in state self.current_state.

INPUT:

• word_in – the input word.

OUTPUT:

The next transition according to word_in. It is assumed that we are in state self.current_state. If no transition matches, a ValueError is thrown.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])
sage: it.get_next_transition([0])
Transition from 'A' to 'A': 0|1
sage: it.get_next_transition([2])
Traceback (most recent call last):
...
ValueError: No transition with input [2] found.

next()

Makes one step in processing the input tape.

INPUT:

Nothing.

OUTPUT:

It returns the taken transition. A StopIteration exception is thrown when there is nothing more to read.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])
sage: it.next()
Transition from 'A' to 'A': 0|1
sage: it.next()
Transition from 'A' to 'A': 1|0
sage: it.next()
Traceback (most recent call last):
...
StopIteration


Reads a letter from the input tape.

INPUT:

Nothing.

OUTPUT:

A letter.

Exception StopIteration is thrown if tape has reached the end.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])
0

write_letter(letter)

Writes a letter on the output tape.

INPUT:

• letter – the letter to be written.

OUTPUT:

Nothing.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])
sage: it.write_letter(42)
sage: it.output_tape
[42]

write_word(word)

Writes a word on the output tape.

INPUT:

• word – the word to be written.

OUTPUT:

Nothing.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMProcessIterator
sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])
sage: it.write_word([4, 2])
sage: it.output_tape
[4, 2]

class sage.combinat.finite_state_machine.FSMState(label, word_out=None, is_initial=False, is_final=False, hook=None, color=None, allow_label_None=False)

Class for a state of a finite state machine.

INPUT:

• label – the label of the state.
• word_out – (default: None) a word that is written when the state is reached.
• is_initial – (default: False)
• is_final – (default: False)
• hook – (default: None) A function which is called when the state is reached during processing input.
• color – (default: None) In order to distinguish states, they can be given an arbitrary “color” (an arbitrary object). This is used in FiniteStateMachine.equivalence_classes(): states of different colors are never considered to be equivalent. Note that Automaton.determinisation() requires that color is hashable.
• allow_label_None – (default: False) If True allows also None as label. Note that a state with label None is used in FSMProcessIterator.

OUTPUT:

Returns a state of a finite state machine.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('state 1', word_out=0, is_initial=True)
sage: A
'state 1'
sage: A.label()
'state 1'
sage: B = FSMState('state 2')
sage: A == B
False


It is not allowed to use None as a label:

sage: from sage.combinat.finite_state_machine import FSMState
sage: FSMState(None)
Traceback (most recent call last):
...
ValueError: Label None reserved for a special state, choose another label.


This can be overridden by:

sage: FSMState(None, allow_label_None=True)
None


Note that Automaton.determinisation() requires that color is hashable:

sage: A = Automaton([[0, 0, 0]], initial_states=[0])
sage: A.state(0).color = []
sage: A.determinisation()
Traceback (most recent call last):
...
TypeError: unhashable type: 'list'
sage: A.state(0).color = ()
sage: A.determinisation()
Automaton with 1 states

copy()

Returns a (shallow) copy of the state.

INPUT:

Nothing.

OUTPUT:

A new state.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: copy(A)
'A'

deepcopy(memo=None)

Returns a deep copy of the state.

INPUT:

• memo – (default: None) a dictionary storing already processed elements.

OUTPUT:

A new state.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: deepcopy(A)
'A'

label()

Returns the label of the state.

INPUT:

Nothing.

OUTPUT:

The label of the state.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('state')
sage: A.label()
'state'

relabeled(label, memo=None)

Returns a deep copy of the state with a new label.

INPUT:

• label – the label of new state.
• memo – (default: None) a dictionary storing already processed elements.

OUTPUT:

A new state.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: A.relabeled('B')
'B'

class sage.combinat.finite_state_machine.FSMTransition(from_state, to_state, word_in=None, word_out=None, hook=None)

Class for a transition of a finite state machine.

INPUT:

• from_state – state from which transition starts.
• to_state – state in which transition ends.
• word_in – the input word of the transitions (when the finite state machine is used as automaton)
• word_out – the output word of the transitions (when the finite state machine is used as transducer)

OUTPUT:

A transition of a finite state machine.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition
sage: A = FSMState('A')
sage: B = FSMState('B')
sage: S = FSMTransition(A, B, 0, 1)
sage: T = FSMTransition('A', 'B', 0, 1)
sage: T == S
True
sage: U = FSMTransition('A', 'B', 0)
sage: U == T
False

copy()

Returns a (shallow) copy of the transition.

INPUT:

Nothing.

OUTPUT:

A new transition.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMTransition
sage: t = FSMTransition('A', 'B', 0)
sage: copy(t)
Transition from 'A' to 'B': 0|-

deepcopy(memo=None)

Returns a deep copy of the transition.

INPUT:

• memo – (default: None) a dictionary storing already processed elements.

OUTPUT:

A new transition.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMTransition
sage: t = FSMTransition('A', 'B', 0)
sage: deepcopy(t)
Transition from 'A' to 'B': 0|-

sage.combinat.finite_state_machine.FSMWordSymbol(word)

Returns a string of word. It may returns the symbol of the empty word FSMEmptyWordSymbol.

INPUT:

• word – the input word.

OUTPUT:

A string of word.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMWordSymbol
sage: FSMWordSymbol([0, 1, 1])
'0,1,1'

class sage.combinat.finite_state_machine.FiniteStateMachine(data=None, initial_states=None, final_states=None, input_alphabet=None, output_alphabet=None, determine_alphabets=None, store_states_dict=True, on_duplicate_transition=None)

Class for a finite state machine.

A finite state machine is a finite set of states connected by transitions.

INPUT:

• data – can be any of the following:

1. a dictionary of dictionaries (of transitions),
2. a dictionary of lists (of states or transitions),
3. a list (of transitions),
4. a function (transition function),
5. an other instance of a finite state machine.
• initial_states and final_states – the initial and final states of this machine

• input_alphabet and output_alphabet – the input and output alphabets of this machine

• determine_alphabets – If True, then the function determine_alphabets() is called after data was read and processed, if False, then not. If it is None, then it is decided during the construction of the finite state machine whether determine_alphabets() should be called.

• store_states_dict – If True, then additionally the states are stored in an interal dictionary for speed up.

• on_duplicate_transition – A function which is called when a transition is inserted into self which already existed (same from_state, same to_state, same word_in, same word_out).

This function is assumed to take two arguments, the first being the already existing transition, the second being the new transition (as an FSMTransition). The function must return the (possibly modified) original transition.

By default, we have on_duplicate_transition=None, which is interpreted as on_duplicate_transition=duplicate_transition_ignore, where duplicate_transition_ignore is a predefined function ignoring the occurrence. Other such predefined functions are duplicate_transition_raise_error and duplicate_transition_add_input.

OUTPUT:

A finite state machine.

The object creation of Automaton and Transducer is the same as the one described here (i.e. just replace the word FiniteStateMachine by Automaton or Transducer).

Each transition of an automaton has an input label. Automata can, for example, be determinised (see Automaton.determinisation()) and minimized (see Automaton.minimization()). Each transition of a transducer has an input and an output label. Transducers can, for example, be simplified (see Transducer.simplification()).

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition


See documentation for more examples.

We illustrate the different input formats:

1. The input-data can be a dictionary of dictionaries, where

• the keys of the outer dictionary are state-labels (from-states of transitions),
• the keys of the inner dictionaries are state-labels (to-states of transitions),
• the values of the inner dictionaries specify the transition more precisely.

The easiest is to use a tuple consisting of an input and an output word:

sage: FiniteStateMachine({'a':{'b':(0, 1), 'c':(1, 1)}})
Finite state machine with 3 states


Instead of the tuple anything iterable (e.g. a list) can be used as well.

If you want to use the arguments of FSMTransition directly, you can use a dictionary:

sage: FiniteStateMachine({'a':{'b':{'word_in':0, 'word_out':1},
....:                          'c':{'word_in':1, 'word_out':1}}})
Finite state machine with 3 states


In the case you already have instances of FSMTransition, it is possible to use them directly:

sage: FiniteStateMachine({'a':{'b':FSMTransition('a', 'b', 0, 1),
....:                          'c':FSMTransition('a', 'c', 1, 1)}})
Finite state machine with 3 states

2. The input-data can be a dictionary of lists, where the keys are states or label of states.

The list-elements can be states:

sage: a = FSMState('a')
sage: b = FSMState('b')
sage: c = FSMState('c')
sage: FiniteStateMachine({a:[b, c]})
Finite state machine with 3 states


Or the list-elements can simply be labels of states:

sage: FiniteStateMachine({'a':['b', 'c']})
Finite state machine with 3 states


The list-elements can also be transitions:

sage: FiniteStateMachine({'a':[FSMTransition('a', 'b', 0, 1),
....:                          FSMTransition('a', 'c', 1, 1)]})
Finite state machine with 3 states


Or they can be tuples of a label, an input word and an output word specifying a transition:

sage: FiniteStateMachine({'a':[('b', 0, 1), ('c', 1, 1)]})
Finite state machine with 3 states

3. The input-data can be a list, where its elements specify transitions:

sage: FiniteStateMachine([FSMTransition('a', 'b', 0, 1),
....:                     FSMTransition('a', 'c', 1, 1)])
Finite state machine with 3 states


It is possible to skip FSMTransition in the example above:

sage: FiniteStateMachine([('a', 'b', 0, 1), ('a', 'c', 1, 1)])
Finite state machine with 3 states


The parameters of the transition are given in tuples. Anyhow, anything iterable (e.g. a list) is possible.

You can also name the parameters of the transition. For this purpose you take a dictionary:

sage: FiniteStateMachine([{'from_state':'a', 'to_state':'b',
....:                      'word_in':0, 'word_out':1},
....:                     {'from_state':'a', 'to_state':'c',
....:                      'word_in':1, 'word_out':1}])
Finite state machine with 3 states


Other arguments, which FSMTransition accepts, can be added, too.

4. The input-data can also be function acting as transition function:

This function has two input arguments:

1. a label of a state (from which the transition starts),
2. a letter of the (input-)alphabet (as input-label of the transition).

It returns a tuple with the following entries:

1. a label of a state (to which state the transition goes),
2. a letter of or a word over the (output-)alphabet (as output-label of the transition).

It may also output a list of such tuples if several transitions from the from-state and the input letter exist (this means that the finite state machine is non-deterministic).

If the transition does not exist, the function should raise a LookupError or return an empty list.

When constructing a finite state machine in this way, some inital states and an input alphabet have to be specified.

sage: def f(state_from, read):
....:     if int(state_from) + read <= 2:
....:         write = 0
....:     else:
....:         state_to = 2*int(state_from) + read - 5
....:         write = 1
....:     return (str(state_to), write)
sage: F = FiniteStateMachine(f, input_alphabet=[0, 1],
....:                        initial_states=['0'],
....:                        final_states=['0'])
sage: F([1, 0, 1])
(True, '0', [0, 0, 1])

5. The input-data can be an other instance of a finite state machine:

sage: FiniteStateMachine(FiniteStateMachine([]))
Traceback (most recent call last):
...
NotImplementedError


The following examples demonstrate the use of on_duplicate_transition:

sage: F = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]])
sage: F.transitions()
[Transition from 'a' to 'a': 1/2|-]

sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error
sage: F1 = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]],
....:                         on_duplicate_transition=duplicate_transition_raise_error)
Traceback (most recent call last):
...
ValueError: Attempting to re-insert transition Transition from 'a' to 'a': 1/2|-


Use duplicate_transition_add_input to emulate a Markov chain, the input labels are considered as transition probabilities:

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: F = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]],
sage: F.transitions()
[Transition from 'a' to 'a': 1|-]


TESTS:

sage: a = FSMState('S_a', 'a')
sage: b = FSMState('S_b', 'b')
sage: c = FSMState('S_c', 'c')
sage: d = FSMState('S_d', 'd')
sage: FiniteStateMachine({a:[b, c], b:[b, c, d],
....:                     c:[a, b], d:[a, c]})
Finite state machine with 4 states


We have several constructions which lead to the same finite state machine:

sage: A = FSMState('A')
sage: B = FSMState('B')
sage: C = FSMState('C')
sage: FSM1 = FiniteStateMachine(
....:  {A:{B:{'word_in':0, 'word_out':1},
....:   C:{'word_in':1, 'word_out':1}}})
sage: FSM2 = FiniteStateMachine({A:{B:(0, 1), C:(1, 1)}})
sage: FSM3 = FiniteStateMachine(
....:  {A:{B:FSMTransition(A, B, 0, 1),
....:      C:FSMTransition(A, C, 1, 1)}})
sage: FSM4 = FiniteStateMachine({A:[(B, 0, 1), (C, 1, 1)]})
sage: FSM5 = FiniteStateMachine(
....:  {A:[FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)]})
sage: FSM6 = FiniteStateMachine(
....:  [{'from_state':A, 'to_state':B, 'word_in':0, 'word_out':1},
....:   {'from_state':A, 'to_state':C, 'word_in':1, 'word_out':1}])
sage: FSM7 = FiniteStateMachine([(A, B, 0, 1), (A, C, 1, 1)])
sage: FSM8 = FiniteStateMachine(
....:  [FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)])

sage: FSM1 == FSM2 == FSM3 == FSM4 == FSM5 == FSM6 == FSM7 == FSM8
True


It is possible to skip FSMTransition in the example above.

Some more tests for different input-data:

sage: FiniteStateMachine({'a':{'a':[0, 0], 'b':[1, 1]},
....:                     'b':{'b':[1, 0]}})
Finite state machine with 2 states

sage: a = FSMState('S_a', 'a')
sage: b = FSMState('S_b', 'b')
sage: c = FSMState('S_c', 'c')
sage: d = FSMState('S_d', 'd')
sage: t1 = FSMTransition(a, b)
sage: t2 = FSMTransition(b, c)
sage: t3 = FSMTransition(b, d)
sage: t4 = FSMTransition(c, d)
sage: FiniteStateMachine([t1, t2, t3, t4])
Finite state machine with 4 states

Kleene_closure()

TESTS:

sage: FiniteStateMachine().Kleene_closure()
Traceback (most recent call last):
...
NotImplementedError

accessible_components()

Returns a new finite state machine with the accessible states of self and all transitions between those states.

INPUT:

Nothing.

OUTPUT:

A finite state machine with the accessible states of self and all transitions between those states.

A state is accessible if there is a directed path from an initial state to the state. If self has no initial states then a copy of the finite state machine self is returned.

EXAMPLES:

sage: F = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1)],
....:               initial_states=[0])
sage: F.accessible_components()
Automaton with 2 states

sage: F = Automaton([(0, 0, 1), (0, 0, 1), (1, 1, 0), (1, 0, 1)],
....:               initial_states=[0])
sage: F.accessible_components()
Automaton with 1 states


Constructs a finite state machine from a transition function.

INPUT:

• function may return a tuple (new_state, output_word) or a list of such tuples.
• initial_states – If no initial states are given, the already existing initial states of self are taken.
• If explore_existing_states is True (default), then already existing states in self (e.g. already given final states) will also be processed if they are reachable from the initial states.

OUTPUT:

Nothing.

EXAMPLES:

sage: F = FiniteStateMachine(initial_states=['A'],
....:                        input_alphabet=[0, 1])
sage: def f(state, input):
....:     return [('A', input), ('B', 1-input)]
sage: F.transitions()
[Transition from 'A' to 'A': 0|0,
Transition from 'A' to 'B': 0|1,
Transition from 'A' to 'A': 1|1,
Transition from 'A' to 'B': 1|0,
Transition from 'B' to 'A': 0|0,
Transition from 'B' to 'B': 0|1,
Transition from 'B' to 'A': 1|1,
Transition from 'B' to 'B': 1|0]


Initial states can also be given as a parameter:

sage: F = FiniteStateMachine(input_alphabet=[0,1])
sage: def f(state, input):
....:     return [('A', input), ('B', 1-input)]
sage: F.initial_states()
['A']


Already existing states in the finite state machine (the final states in the example below) are also explored:

sage: F = FiniteStateMachine(initial_states=[0],
....:                        final_states=[1],
....:                        input_alphabet=[0])
sage: def transition_function(state, letter):
....:     return(1-state, [])
sage: F.transitions()
[Transition from 0 to 1: 0|-,
Transition from 1 to 0: 0|-]


If explore_existing_states=False, however, this behavior is turned off, i.e., already existing states are not explored:

sage: F = FiniteStateMachine(initial_states=[0],
....:                        final_states=[1],
....:                        input_alphabet=[0])
sage: def transition_function(state, letter):
....:     return(1-state, [])
....:                                explore_existing_states=False)
sage: F.transitions()
[Transition from 0 to 1: 0|-]


TEST:

sage: F = FiniteStateMachine(initial_states=['A'])
sage: def f(state, input):
....:     return [('A', input), ('B', 1-input)]
Traceback (most recent call last):
...
ValueError: No input alphabet is given.
Try calling determine_alphabets().

sage: def transition(state, where):
....:     return (vector([0, 0]), 1)
sage: Transducer(transition, input_alphabet=[0], initial_states=[0])
Traceback (most recent call last):
...
TypeError: mutable vectors are unhashable


Adds a state to the finite state machine and returns the new state. If the state already exists, that existing state is returned.

INPUT:

• state is either an instance of FSMState or, otherwise, a label of a state.

OUTPUT:

The new or existing state.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: F = FiniteStateMachine()
sage: A = FSMState('A', is_initial=True)
'A'


INPUT:

• states – a list of states or iterator over states.

OUTPUT:

Nothing.

EXAMPLES:

sage: F = FiniteStateMachine()
sage: F.states()
['A', 'B']


Adds a transition to the finite state machine and returns the new transition.

If the transition already exists, the return value of self.on_duplicate_transition is returned. See the documentation of FiniteStateMachine.

INPUT:

The following forms are all accepted:

sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition
sage: A = FSMState('A')
sage: B = FSMState('B')

sage: FSM = FiniteStateMachine()
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
sage: FSM.add_transition('A', 'B', {'word_in': 0, 'word_out': 1})
Transition from 'A' to 'B': {'word_in': 0, 'word_out': 1}|-

sage: FSM = FiniteStateMachine()
....:                    word_in=0, word_out=1)
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
....:                    'word_in': 0, 'word_out': 1})
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
Transition from 'A' to 'B': 0|1

sage: FSM = FiniteStateMachine()
Transition from 'A' to 'B': 0|1


If the states A and B are not instances of FSMState, then it is assumed that they are labels of states.

OUTPUT:

The new transition.

Adds one or more transitions if function(state, state) says that there are some.

INPUT:

• function – a transition function. Given two states from_state and to_state (or their labels if label_as_input is true), this function shall return a tuple (word_in, word_out) to add a transition from from_state to to_state with input and output labels word_in and word_out, respectively. If no such addition is to be added, the transition function shall return None. The transition function may also return a list of such tuples in order to add multiple transitions between the pair of states.
• label_as_input – (default: True)

OUTPUT:

Nothing.

EXAMPLES:

sage: F = FiniteStateMachine()
sage: def f(state1, state2):
....:     if state1 == 'C':
....:         return None
....:     return (0, 1)
sage: len(F.transitions())
6


Multiple transitions are also possible:

sage: F = FiniteStateMachine()
sage: def f(state1, state2):
....:     if state1 != state2:
....:          return [(0, 1), (1, 0)]
....:     else:
....:          return None
sage: F.transitions()
[Transition from 0 to 1: 0|1,
Transition from 0 to 1: 1|0,
Transition from 1 to 0: 0|1,
Transition from 1 to 0: 1|0]


TESTS:

sage: F = FiniteStateMachine()
0
sage: def f(state1, state2):
....:     return 1
Traceback (most recent call last):
...
ValueError: The callback function for add_transitions_from_function
is expected to return a pair (word_in, word_out) or a list of such
pairs. For states 0 and 0 however, it returned 1,
which is not acceptable.


Returns the adjacency matrix of the underlying graph.

INPUT:

• input – Only transitions with input label input are respected.
• entry – The function entry takes a transition and the return value is written in the matrix as the entry (transition.from_state, transition.to_state).

OUTPUT:

A matrix.

If any label of a state is not an integer, the finite state machine is relabeled at the beginning. If there are more than one transitions between two states, then the different return values of entry are added up.

The default value of entry takes the variable x to the power of the output word of the transition.

EXAMPLES:

sage: B = FiniteStateMachine({0:{0:(0, 0), 'a':(1, 0)},
....:                         'a':{2:(0, 0), 3:(1, 0)},
....:                         2:{0:(1, 1), 4:(0, 0)},
....:                         3:{'a':(0, 1), 2:(1, 1)},
....:                         4:{4:(1, 1), 3:(0, 1)}},
....:                        initial_states=[0])
[1 1 0 0 0]
[0 0 1 1 0]
[x 0 0 0 1]
[0 x x 0 0]
[0 0 0 x x]
[1 1 0 0 0]
[0 0 1 1 0]
[1 0 0 0 1]
[0 1 1 0 0]
[0 0 0 1 1]
....:     exp(I*transition.word_out[0]*var('t'))))
[      0       1       0       0       0]
[      0       0       0       1       0]
[e^(I*t)       0       0       0       0]
[      0       0 e^(I*t)       0       0]
[      0       0       0       0 e^(I*t)]

composition(other, algorithm=None, only_accessible_components=True)

Returns a new transducer which is the composition of self and other.

INPUT:

• other – a transducer

• algorithm – can be one of the following

• direct – The composition is calculated directly.

There can be arbitrarily many initial and final states, but the input and output labels must have length 1.

WARNING: The output of other is fed into self.

• explorative – An explorative algorithm is used.

At least the following restrictions apply, but are not checked: - both self and other have exactly one initial state - all input labels of transitions have length exactly 1

The input alphabet of self has to be specified.

This is a very limited implementation of composition. WARNING: The output of other is fed into self.

If algorithm is None, then the algorithm is chosen automatically (at the moment always direct).

OUTPUT:

A new transducer.

The labels of the new finite state machine are pairs of states of the original finite state machines. The color of a new state is the tuple of colors of the constituent states.

EXAMPLES:

sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)],
....:                initial_states=['A', 'B'], final_states=['B'],
....:                determine_alphabets=True)
sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1),
....:                 (2, 2, 1, 1), (2, 2, 0, 0)],
....:                initial_states=[1], final_states=[2],
....:                determine_alphabets=True)
sage: Hd = F.composition(G, algorithm='direct')
sage: Hd.initial_states()
[(1, 'B'), (1, 'A')]
sage: Hd.transitions()
[Transition from (1, 'B') to (1, 'A'): 1|1,
Transition from (1, 'A') to (2, 'B'): 0|0,
Transition from (2, 'B') to (2, 'A'): 0|1,
Transition from (2, 'A') to (2, 'B'): 1|0]

sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1),
....:                 ('B', 'B', 0, 0)],
....:                initial_states=['A'], final_states=['B'])
sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),
....:                 (2, 2, 0, 1), (2, 1, 1, 1)],
....:                initial_states=[1], final_states=[1])
sage: He = G.composition(F, algorithm='explorative')
sage: He.transitions()
[Transition from ('A', 1) to ('B', 2): 1|0,1,
Transition from ('B', 2) to ('B', 2): 0|1,
Transition from ('B', 2) to ('B', 1): 1|1,
Transition from ('B', 1) to ('B', 1): 0|0,
Transition from ('B', 1) to ('B', 2): 1|0]


Be aware that after composition, different transitions may share the same output label (same python object):

sage: F = Transducer([ ('A','B',0,0), ('B','A',0,0)],
....:                initial_states=['A'],
....:                final_states=['A'])
sage: F.transitions()[0].word_out is F.transitions()[1].word_out
False
sage: G = Transducer([('C','C',0,1)],)
....:                initial_states=['C'],
....:                final_states=['C'])
sage: H = G.composition(F)
sage: H.transitions()[0].word_out is H.transitions()[1].word_out
True


TESTS:

Due to the limitations of the two algorithms the following (examples from above, but different algorithm used) does not give a full answer or does not work

In the following, algorithm='explorative' is inadequate, as F has more than one initial state:

sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)],
....:                initial_states=['A', 'B'], final_states=['B'],
....:                determine_alphabets=True)
sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1),
....:                 (2, 2, 1, 1), (2, 2, 0, 0)],
....:                initial_states=[1], final_states=[2],
....:                determine_alphabets=True)
sage: He = F.composition(G, algorithm='explorative')
sage: He.initial_states()
[(1, 'A')]
sage: He.transitions()
[Transition from (1, 'A') to (2, 'B'): 0|0,
Transition from (2, 'B') to (2, 'A'): 0|1,
Transition from (2, 'A') to (2, 'B'): 1|0]


In the following example, algorithm='direct' is inappropriate as there are edges with output labels of length greater than 1:

sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1),
....:                 ('B', 'B', 0, 0)],
....:                initial_states=['A'], final_states=['B'])
sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),
....:                 (2, 2, 0, 1), (2, 1, 1, 1)],
....:                initial_states=[1], final_states=[1])
sage: Hd = G.composition(F, algorithm='direct')

concatenation(other)

TESTS:

sage: F = FiniteStateMachine([('A', 'A')])
sage: FiniteStateMachine().concatenation(F)
Traceback (most recent call last):
...
NotImplementedError

copy()

Returns a (shallow) copy of the finite state machine.

INPUT:

Nothing.

OUTPUT:

A new finite state machine.

TESTS:

sage: copy(FiniteStateMachine())
Traceback (most recent call last):
...
NotImplementedError

deepcopy(memo=None)

Returns a deep copy of the finite state machine.

INPUT:

• memo – (default: None) a dictionary storing already processed elements.

OUTPUT:

A new finite state machine.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)])
sage: deepcopy(F)
Finite state machine with 1 states

delete_state(s)

Deletes a state and all transitions coming or going to this state.

INPUT:

• s – a label of a state or an FSMState.

OUTPUT:

Nothing.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMTransition
sage: t1 = FSMTransition('A', 'B', 0)
sage: t2 = FSMTransition('B', 'B', 1)
sage: F = FiniteStateMachine([t1, t2])
sage: F.delete_state('A')
sage: F.transitions()
[Transition from 'B' to 'B': 1|-]


TESTS:

sage: F._states_
['B']
sage: F._states_dict_  # This shows that #16024 is fixed.
{'B': 'B'}

delete_transition(t)

Deletes a transition by removing it from the list of transitions of the state, where the transition starts.

INPUT:

• t – a transition.

OUTPUT:

Nothing.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'B', 0), ('B', 'A', 1)])
sage: F.delete_transition(('A', 'B', 0))
sage: F.transitions()
[Transition from 'B' to 'A': 1|-]

determine_alphabets(reset=True)

Determines the input and output alphabet according to the transitions in self.

INPUT:

• reset – If reset is True, then the existing input and output alphabets are erased, otherwise new letters are appended to the existing alphabets.

OUTPUT:

Nothing.

After this operation the input alphabet and the output alphabet of self are a list of letters.

EXAMPLES:

sage: T = Transducer([(1, 1, 1, 0), (1, 2, 2, 1),
....:                 (2, 2, 1, 1), (2, 2, 0, 0)],
....:                determine_alphabets=False)
sage: (T.input_alphabet, T.output_alphabet)
(None, None)
sage: T.determine_alphabets()
sage: (T.input_alphabet, T.output_alphabet)
([0, 1, 2], [0, 1])

digraph(edge_labels='words_in_out')

Returns the graph of the finite state machine with labeled vertices and labeled edges.

INPUT:

• edge_label: (default: 'words_in_out') can be
• 'words_in_out' (labels will be strings 'i|o')
• a function with which takes as input a transition and outputs (returns) the label

OUTPUT:

A graph.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: T = Transducer()
sage: T.graph()
Digraph on 0 vertices
'A'
sage: T.graph()
Digraph on 1 vertex
Transition from 'A' to 'A': 0|1
sage: T.graph()
Looped digraph on 1 vertex

disjoint_union(other)

TESTS:

sage: F = FiniteStateMachine([('A', 'A')])
sage: FiniteStateMachine().disjoint_union(F)
Traceback (most recent call last):
...
NotImplementedError

empty_copy(memo=None)

Returns an empty deep copy of the finite state machine, i.e., input_alphabet, output_alphabet, on_duplicate_transition are preserved, but states and transitions are not.

INPUT:

• memo – a dictionary storing already processed elements.

OUTPUT:

A new finite state machine.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error
sage: F = FiniteStateMachine([('A', 'A', 0, 2), ('A', 'A', 1, 3)],
....:                        input_alphabet=[0, 1],
....:                        output_alphabet=[2, 3],
....:                        on_duplicate_transition=duplicate_transition_raise_error)
sage: FE = F.empty_copy(); FE
Finite state machine with 0 states
sage: FE.input_alphabet
[0, 1]
sage: FE.output_alphabet
[2, 3]
sage: FE.on_duplicate_transition == duplicate_transition_raise_error
True

equivalence_classes()

Returns a list of equivalence classes of states.

INPUT:

Nothing.

OUTPUT:

A list of equivalence classes of states.

Two states $$a$$ and $$b$$ are equivalent if and only if there is a bijection $$\varphi$$ between paths starting at $$a$$ and paths starting at $$b$$ with the following properties: Let $$p_a$$ be a path from $$a$$ to $$a'$$ and $$p_b$$ a path from $$b$$ to $$b'$$ such that $$\varphi(p_a)=p_b$$, then

• $$p_a.\mathit{word}_\mathit{in}=p_b.\mathit{word}_\mathit{in}$$,
• $$p_a.\mathit{word}_\mathit{out}=p_b.\mathit{word}_\mathit{out}$$,
• $$a'$$ and $$b'$$ have the same output label, and
• $$a'$$ and $$b'$$ are both final or both non-final.

The function equivalence_classes() returns a list of the equivalence classes to this equivalence relation.

This is one step of Moore’s minimization algorithm.

minimization()

EXAMPLES:

sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0),
....:                           ("B", "C", 0, 0), ("B", "C", 1, 1),
....:                           ("C", "D", 0, 1), ("C", "D", 1, 0),
....:                           ("D", "A", 0, 0), ("D", "A", 1, 1)])
sage: fsm.equivalence_classes()
[['A', 'C'], ['B', 'D']]

final_components()

Returns the final components of a finite state machine as finite state machines.

INPUT:

Nothing.

OUTPUT:

A list of finite state machines, each representing a final component of self.

A final component of a transducer T is a strongly connected component C such that there are no transitions of T leaving C.

The final components are the only parts of a transducer which influence the main terms of the asympotic behaviour of the sum of output labels of a transducer, see [HKP2014] and [HKW2014].

EXAMPLES:

sage: T = Transducer([['A', 'B', 0, 0], ['B', 'C', 0, 1],
....:                 ['C', 'B', 0, 1], ['A', 'D', 1, 0],
....:                 ['D', 'D', 0, 0], ['D', 'B', 1, 0],
....:                 ['A', 'E', 2, 0], ['E', 'E', 0, 0]])
sage: FC = T.final_components()
sage: sorted(FC[0].transitions())
[Transition from 'B' to 'C': 0|1,
Transition from 'C' to 'B': 0|1]
sage: FC[1].transitions()
[Transition from 'E' to 'E': 0|0]


Another example (cycle of length 2):

sage: T = Automaton([[0, 1, 0], [1, 0, 0]])
sage: len(T.final_components()) == 1
True
sage: T.final_components()[0].transitions()
[Transition from 0 to 1: 0|-,
Transition from 1 to 0: 0|-]


REFERENCES:

 [HKP2014] Clemens Heuberger, Sara Kropf, and Helmut Prodinger, Asymptotic analysis of the sum of the output of transducer, in preparation.
 [HKW2014] Clemens Heuberger, Sara Kropf, and Stephan Wagner, Combinatorial Characterization of Independent Transducers via Functional Digraphs, Arxiv 1404.3680.
final_states()

Returns a list of all final states.

INPUT:

Nothing.

OUTPUT:

A list of all final states.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_final=True)
sage: B = FSMState('B', is_initial=True)
sage: C = FSMState('C', is_final=True)
sage: F = FiniteStateMachine([(A, B), (A, C)])
sage: F.final_states()
['A', 'C']

graph(edge_labels='words_in_out')

Returns the graph of the finite state machine with labeled vertices and labeled edges.

INPUT:

• edge_label: (default: 'words_in_out') can be
• 'words_in_out' (labels will be strings 'i|o')
• a function with which takes as input a transition and outputs (returns) the label

OUTPUT:

A graph.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: T = Transducer()
sage: T.graph()
Digraph on 0 vertices
'A'
sage: T.graph()
Digraph on 1 vertex
Transition from 'A' to 'A': 0|1
sage: T.graph()
Looped digraph on 1 vertex

has_final_state(state)

Returns whether state is one of the final states of the finite state machine.

INPUT:

OUTPUT:

True or False.

EXAMPLES:

sage: FiniteStateMachine(final_states=['A']).has_final_state('A')
True

has_final_states()

Returns whether the finite state machine has a final state.

INPUT:

Nothing.

OUTPUT:

True or False.

EXAMPLES:

sage: FiniteStateMachine().has_final_states()
False

has_initial_state(state)

Returns whether state is one of the initial states of the finite state machine.

INPUT:

OUTPUT:

True or False.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'A')], initial_states=['A'])
sage: F.has_initial_state('A')
True

has_initial_states()

Returns whether the finite state machine has an initial state.

INPUT:

Nothing.

OUTPUT:

True or False.

EXAMPLES:

sage: FiniteStateMachine().has_initial_states()
False

has_state(state)

Returns whether state is one of the states of the finite state machine.

INPUT:

• state can be a FSMState or a label of a state.

OUTPUT:

True or False.

EXAMPLES:

sage: FiniteStateMachine().has_state('A')
False

has_transition(transition)

Returns whether transition is one of the transitions of the finite state machine.

INPUT:

OUTPUT:

True or False.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMTransition
sage: t = FSMTransition('A', 'A', 0, 1)
sage: FiniteStateMachine().has_transition(t)
False
sage: FiniteStateMachine().has_transition(('A', 'A', 0, 1))
Traceback (most recent call last):
...
TypeError: Transition is not an instance of FSMTransition.

induced_sub_finite_state_machine(states)

Returns a sub-finite-state-machine of the finite state machine induced by the given states.

INPUT:

• states – a list (or an iterator) of states (either labels or instances of FSMState) of the sub-finite-state-machine.

OUTPUT:

A new finite state machine. It consists (of deep copies) of the given states and (deep copies) of all transitions of self between these states.

EXAMPLE:

sage: FSM = FiniteStateMachine([(0, 1, 0), (0, 2, 0),
....:                           (1, 2, 0), (2, 0, 0)])
sage: sub_FSM = FSM.induced_sub_finite_state_machine([0, 1])
sage: sub_FSM.states()
[0, 1]
sage: sub_FSM.transitions()
[Transition from 0 to 1: 0|-]
sage: FSM.induced_sub_finite_state_machine([3])
Traceback (most recent call last):
...
ValueError: 3 is not a state of this finite state machine.


TESTS:

Make sure that the links between transitions and states are still intact:

sage: sub_FSM.transitions()[0].from_state is sub_FSM.state(0)
True

initial_states()

Returns a list of all initial states.

INPUT:

Nothing.

OUTPUT:

A list of all initial states.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_initial=True)
sage: B = FSMState('B')
sage: F = FiniteStateMachine([(A, B, 1, 0)])
sage: F.initial_states()
['A']

input_projection()

Returns an automaton where the output of each transition of self is deleted.

INPUT:

Nothing

OUTPUT:

An automaton.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),
....:                         ('B', 'B', 1, 0)])
sage: G = F.input_projection()
sage: G.transitions()
[Transition from 'A' to 'B': 0|-,
Transition from 'A' to 'A': 1|-,
Transition from 'B' to 'B': 1|-]

intersection(other)

TESTS:

sage: FiniteStateMachine().intersection(FiniteStateMachine())
Traceback (most recent call last):
...
NotImplementedError

is_Markov_chain()

Checks whether self is a Markov chain where the transition probabilities are modeled as input labels.

INPUT:

Nothing.

OUTPUT:

True or False.

on_duplicate_transition must be duplicate_transition_add_input and the sum of the input weights of the transitions leaving a state must add up to 1.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],
....:                 [1, 0, 1/2, 0], [1, 1, 1/2, 1]],
sage: F.is_Markov_chain()
True


sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],
....:                 [1, 0, 1/2, 0], [1, 1, 1/2, 1]])
sage: F.is_Markov_chain()
False


Sum of input labels of the transitions leaving states must be 1:

sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],
....:                 [1, 0, 1/2, 0]],
sage: F.is_Markov_chain()
False

is_complete()

Returns whether the finite state machine is complete.

INPUT:

Nothing.

OUTPUT:

True or False.

A finite state machine is considered to be complete if each transition has an input label of length one and for each pair $$(q, a)$$ where $$q$$ is a state and $$a$$ is an element of the input alphabet, there is exactly one transition from $$q$$ with input label $$a$$.

EXAMPLES:

sage: fsm = FiniteStateMachine([(0, 0, 0, 0),
....:                           (0, 1, 1, 1),
....:                           (1, 1, 0, 0)],
....:                          determine_alphabets=False)
sage: fsm.is_complete()
Traceback (most recent call last):
...
ValueError: No input alphabet is given. Try calling determine_alphabets().
sage: fsm.input_alphabet = [0, 1]
sage: fsm.is_complete()
False
Transition from 1 to 1: 1|1
sage: fsm.is_complete()
True
Transition from 0 to 0: 1|0
sage: fsm.is_complete()
False

is_connected()

TESTS:

sage: FiniteStateMachine().is_connected()
Traceback (most recent call last):
...
NotImplementedError

is_deterministic()

Returns whether the finite finite state machine is deterministic.

INPUT:

Nothing.

OUTPUT:

True or False.

A finite state machine is considered to be deterministic if each transition has input label of length one and for each pair $$(q,a)$$ where $$q$$ is a state and $$a$$ is an element of the input alphabet, there is at most one transition from $$q$$ with input label $$a$$.

TESTS:

sage: fsm = FiniteStateMachine()
Transition from 'A' to 'B': 0|-
sage: fsm.is_deterministic()
True
Transition from 'A' to 'C': 0|-
sage: fsm.is_deterministic()
False
Transition from 'A' to 'B': 0,1|-
sage: fsm.is_deterministic()
False

iter_final_states()

Returns an iterator of the final states.

INPUT:

Nothing.

OUTPUT:

An iterator over all initial states.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_final=True)
sage: B = FSMState('B', is_initial=True)
sage: C = FSMState('C', is_final=True)
sage: F = FiniteStateMachine([(A, B), (A, C)])
sage: [s.label() for s in F.iter_final_states()]
['A', 'C']

iter_initial_states()

Returns an iterator of the initial states.

INPUT:

Nothing.

OUTPUT:

An iterator over all initial states.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_initial=True)
sage: B = FSMState('B')
sage: F = FiniteStateMachine([(A, B, 1, 0)])
sage: [s.label() for s in F.iter_initial_states()]
['A']

iter_process(input_tape=None, initial_state=None, **kwargs)

EXAMPLES:

sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....:     initial_states=['A'], final_states=['A'])
sage: it = inverter.iter_process(input_tape=[0, 1, 1])
sage: for _ in it:
....:     pass
sage: it.output_tape
[1, 0, 0]

iter_states()

Returns an iterator of the states.

INPUT:

Nothing.

OUTPUT:

An iterator of the states of the finite state machine.

EXAMPLES:

sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])
sage: [s.label() for s in FSM.iter_states()]
['1', '2']

iter_transitions(from_state=None)

Returns an iterator of all transitions.

INPUT:

• from_state – (default: None) If from_state is given, then a list of transitions starting there is given.

OUTPUT:

An iterator of all transitions.

EXAMPLES:

sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])
sage: [(t.from_state.label(), t.to_state.label())
....:     for t in FSM.iter_transitions('1')]
[('1', '2')]
sage: [(t.from_state.label(), t.to_state.label())
....:     for t in FSM.iter_transitions('2')]
[('2', '2')]
sage: [(t.from_state.label(), t.to_state.label())
....:     for t in FSM.iter_transitions()]
[('1', '2'), ('2', '2')]

markov_chain_simplification()

Consider self as Markov chain with probabilities as input labels and simplify it.

INPUT:

Nothing.

OUTPUT:

Simplified version of self.

EXAMPLE:

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: T = Transducer([[1, 2, 1/4, 0], [1, -2, 1/4, 0], [1, -2, 1/2, 0],
....:                 [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1],
....:                 [-2, 2, 1/4, 1], [2, 3, 1/2, 2], [-2, 3, 1/2, 2]],
....:                initial_states=[1],
....:                final_states=[3],
sage: T1 = T.markov_chain_simplification()
sage: sorted(T1.transitions())
[Transition from ((1,),) to ((2, -2),): 1|0,
Transition from ((2, -2),) to ((2, -2),): 1/2|1,
Transition from ((2, -2),) to ((3,),): 1/2|2]

merged_transitions()

Merges transitions which have the same from_state, to_state and word_out while adding their word_in.

INPUT:

Nothing.

OUTPUT:

A finite state machine with merged transitions. If no mergers occur, return self.

EXAMPLE:

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: T = Transducer([[1, 2, 1/4, 1], [1, -2, 1/4, 1], [1, -2, 1/2, 1],
....:                 [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1],
....:                 [-2, 2, 1/4, 1], [2, 3, 1/2, 1], [-2, 3, 1/2, 1]],
sage: T1 = T.merged_transitions()
sage: T1 is T
False
sage: sorted(T1.transitions())
[Transition from -2 to -2: 1/4|1,
Transition from -2 to 2: 1/4|1,
Transition from -2 to 3: 1/2|1,
Transition from 1 to 2: 1/4|1,
Transition from 1 to -2: 3/4|1,
Transition from 2 to -2: 1/4|1,
Transition from 2 to 2: 1/4|1,
Transition from 2 to 3: 1/2|1]


Applying the function again does not change the result:

sage: T2 = T1.merged_transitions()
sage: T2 is T1
True

output_projection()

Returns a automaton where the input of each transition of self is deleted and the new input is the original output.

INPUT:

Nothing

OUTPUT:

An automaton.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),
....:                         ('B', 'B', 1, 0)])
sage: G = F.output_projection()
sage: G.transitions()
[Transition from 'A' to 'B': 1|-,
Transition from 'A' to 'A': 1|-,
Transition from 'B' to 'B': 0|-]

plot()

Plots a graph of the finite state machine with labeled vertices and labeled edges.

INPUT:

Nothing.

OUTPUT:

A plot of the graph of the finite state machine.

TESTS:

sage: FiniteStateMachine([('A', 'A', 0)]).plot()

predecessors(state, valid_input=None)

Lists all predecessors of a state.

INPUT:

• state – the state from which the predecessors should be listed.
• valid_input – If valid_input is a list, then we only consider transitions whose input labels are contained in valid_input. state has to be a FSMState (not a label of a state). If input labels of length larger than $$1$$ are used, then valid_input has to be a list of lists.

OUTPUT:

A list of states.

EXAMPLES:

sage: A = Transducer([('I', 'A', 'a', 'b'), ('I', 'B', 'b', 'c'),
....:                 ('I', 'C', 'c', 'a'), ('A', 'F', 'b', 'a'),
....:                 ('B', 'F', ['c', 'b'], 'b'), ('C', 'F', 'a', 'c')],
....:                initial_states=['I'], final_states=['F'])
sage: A.predecessors(A.state('A'))
['A', 'I']
sage: A.predecessors(A.state('F'), valid_input=['b', 'a'])
['F', 'C', 'A', 'I']
sage: A.predecessors(A.state('F'), valid_input=[['c', 'b'], 'a'])
['F', 'C', 'B']

prepone_output()

Apply the following to each state $$s$$ (except initial and final states) of the finite state machine as often as possible:

If the letter a is prefix of the output label of all transitions from $$s$$, then remove it from all these labels and append it to all output labels of all transitions leading to $$s$$.

We assume that the states have no output labels.

INPUT:

Nothing.

OUTPUT:

Nothing.

EXAMPLES:

sage: A = Transducer([('A', 'B', 1, 1), ('B', 'B', 0, 0), ('B', 'C', 1, 0)],
....:                initial_states=['A'], final_states=['C'])
sage: A.prepone_output()
sage: A.transitions()
[Transition from 'A' to 'B': 1|1,0,
Transition from 'B' to 'B': 0|0,
Transition from 'B' to 'C': 1|-]

sage: B = Transducer([('A', 'B', 0, 1), ('B', 'C', 1, [1, 1]), ('B', 'C', 0, 1)],
....:                initial_states=['A'], final_states=['C'])
sage: B.prepone_output()
sage: B.transitions()
[Transition from 'A' to 'B': 0|1,1,
Transition from 'B' to 'C': 1|1,
Transition from 'B' to 'C': 0|-]


If initial states are not labeled as such, unexpected results may be obtained:

sage: C = Transducer([(0,1,0,0)])
sage: C.prepone_output()
prepone_output: All transitions leaving state 0 have an
output label with prefix 0.  However, there is no inbound
transition and it is not an initial state. This routine
(possibly called by simplification) therefore erased this
prefix from all outbound transitions.
sage: C.transitions()
[Transition from 0 to 1: 0|-]


Output labels do not have to be hashable:

sage: C = Transducer([(0, 1, 0, []),
....:                 (1, 0, 0, [vector([0, 0]), 0]),
....:                 (1, 1, 1, [vector([0, 0]), 1]),
....:                 (0, 0, 1, 0)],
....:                 determine_alphabets=False,
....:                 initial_states=[0])
sage: C.prepone_output()
sage: sorted(C.transitions())
[Transition from 0 to 1: 0|(0, 0),
Transition from 0 to 0: 1|0,
Transition from 1 to 0: 0|0,
Transition from 1 to 1: 1|1,(0, 0)]

process(*args, **kwargs)

Returns whether the finite state machine accepts the input, the state where the computation stops and which output is generated.

INPUT:

• input_tape – The input tape can be a list with entries from the input alphabet.
• initial_state – (default: None) The state in which to start. If this parameter is None and there is only one initial state in the machine, then this state is taken.

OUTPUT:

A triple, where

• the first entry is True if the input string is accepted,
• the second gives the reached state after processing the input tape (This is a state with label None if the input could not be processed, i.e., when at one point no transition to go could be found.), and
• the third gives a list of the output labels used during processing (in the case the finite state machine runs as transducer).

Note that in the case the finite state machine is not deterministic, one possible path is gone. This means, that in this case the output can be wrong.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_initial = True, is_final = True)
sage: binary_inverter = FiniteStateMachine({A:[(A, 0, 1), (A, 1, 0)]})
sage: binary_inverter.process([0, 1, 0, 0, 1, 1])
(True, 'A', [1, 0, 1, 1, 0, 0])


Alternatively, we can invoke this function by:

sage: binary_inverter([0, 1, 0, 0, 1, 1])
(True, 'A', [1, 0, 1, 1, 0, 0])

sage: NAF_ = FSMState('_', is_initial = True, is_final = True)
sage: NAF1 = FSMState('1', is_final = True)
sage: NAF = FiniteStateMachine(
....:     {NAF_: [(NAF_, 0), (NAF1, 1)], NAF1: [(NAF_, 0)]})
sage: [NAF.process(w)[0] for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],
....:                           [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]
[True, True, False, True, False, False]

product_FiniteStateMachine(other, function, new_input_alphabet=None, only_accessible_components=True)

Returns a new finite state machine whose states are pairs of states of the original finite state machines.

INPUT:

• other – a finite state machine
• function has to accept two transitions from $$A$$ to $$B$$ and $$C$$ to $$D$$ and returns a pair (word_in, word_out) which is the label of the transition $$(A, C)$$ to $$(B, D)$$. If there is no transition from $$(A, C)$$ to $$(B, D)$$, then function should raise a LookupError.
• new_input_alphabet (optional)– the new input alphabet as a list.
• only_accessible_components – If true (default), then the result is piped through accessible_components. If no new_input_alphabet is given, it is determined by determine_alphabets().

OUTPUT:

A finite state machine whose states are pairs of states of the original finite state machines.

The labels of the transitions are defined by function.

The color of a new state is the tuple of colors of the constituent states of self and other.

EXAMPLES:

sage: F = Automaton([('A', 'B', 1), ('A', 'A', 0), ('B', 'A', 2)],
....:               initial_states=['A'], final_states=['B'],
....:               determine_alphabets=True)
sage: G = Automaton([(1, 1, 1)], initial_states=[1], final_states=[1])
....:     return (transition1.word_in[0] + transition2.word_in[0],
....:             None)
sage: H = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False)
sage: H.transitions()
[Transition from ('A', 1) to ('B', 1): 2|-,
Transition from ('A', 1) to ('A', 1): 1|-,
Transition from ('B', 1) to ('A', 1): 3|-]
sage: H1 = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False)
sage: H1.states()[0].label()[0] is F.states()[0]
True
sage: H1.states()[0].label()[1] is G.states()[0]
True

sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)],
....:                initial_states=[0] )
sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)],
....:                initial_states=[0] )
sage: H = F.product_FiniteStateMachine(
....:         G, lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None))
sage: H.states()
[(0, 0), (1, 0)]

sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)],
....:                initial_states=[0] )
sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)],
....:                initial_states=[0] )
sage: H = F.product_FiniteStateMachine(G,
....:                                  lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None),
....:                                  only_accessible_components=False)
sage: H.states()
[(0, 0), (1, 0), (0, 1), (1, 1)]


TESTS:

Check that colors are correctly dealt with. In particular, the new colors have to be hashable such that Automaton.determinisation() does not fail:

sage: A = Automaton([[0, 0, 0]], initial_states=[0])
sage: B = A.product_FiniteStateMachine(A,
....:                                  lambda t1, t2: (0, None))
sage: B.states()[0].color
(None, None)
sage: B.determinisation()
Automaton with 1 states

projection(what='input')

Returns an Automaton which transition labels are the projection of the transition labels of the input.

INPUT:

• what – (default: input) either input or output.

OUTPUT:

An automaton.

EXAMPLES:

sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),
....:                         ('B', 'B', 1, 0)])
sage: G = F.projection(what='output')
sage: G.transitions()
[Transition from 'A' to 'B': 1|-,
Transition from 'A' to 'A': 1|-,
Transition from 'B' to 'B': 0|-]

quotient(classes)

Constructs the quotient with respect to the equivalence classes.

INPUT:

• classes is a list of equivalence classes of states.

OUTPUT:

A finite state machine.

The labels of the new states are tuples of states of the self, corresponding to classes.

Assume that $$c$$ is a class, and $$a$$ and $$b$$ are states in $$c$$. Then there is a bijection $$\varphi$$ between the transitions from $$a$$ and the transitions from $$b$$ with the following properties: if $$\varphi(t_a)=t_b$$, then

• $$t_a.\mathit{word}_\mathit{in}=t_b.\mathit{word}_\mathit{in}$$,
• $$t_a.\mathit{word}_\mathit{out}=t_b.\mathit{word}_\mathit{out}$$, and
• $$t_a$$ and $$t_b$$ lead to some equivalent states $$a'$$ and $$b'$$.

Non-initial states may be merged with initial states, the resulting state is an initial state.

All states in a class must have the same is_final and word_out values.

EXAMPLES:

sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0),
....:                           ("B", "C", 0, 0), ("B", "C", 1, 1),
....:                           ("C", "D", 0, 1), ("C", "D", 1, 0),
....:                           ("D", "A", 0, 0), ("D", "A", 1, 1)])
sage: fsmq = fsm.quotient([[fsm.state("A"), fsm.state("C")],
....:                      [fsm.state("B"), fsm.state("D")]])
sage: fsmq.transitions()
[Transition from ('A', 'C')
to ('B', 'D'): 0|1,
Transition from ('A', 'C')
to ('B', 'D'): 1|0,
Transition from ('B', 'D')
to ('A', 'C'): 0|0,
Transition from ('B', 'D')
to ('A', 'C'): 1|1]
sage: fsmq.relabeled().transitions()
[Transition from 0 to 1: 0|1,
Transition from 0 to 1: 1|0,
Transition from 1 to 0: 0|0,
Transition from 1 to 0: 1|1]
sage: fsmq1 = fsm.quotient(fsm.equivalence_classes())
sage: fsmq1 == fsmq
True
sage: fsm.quotient([[fsm.state("A"), fsm.state("B"), fsm.state("C"), fsm.state("D")]])
Traceback (most recent call last):
...
AssertionError: Transitions of state 'A' and 'B' are incompatible.

relabeled(memo=None)

Returns a deep copy of the finite state machine, but the states are relabeled by integers starting with 0.

INPUT:

• memo – (default: None) a dictionary storing already processed elements.

OUTPUT:

A new finite state machine.

EXAMPLES:

sage: FSM1 = FiniteStateMachine([('A', 'B'), ('B', 'C'), ('C', 'A')])
sage: FSM1.states()
['A', 'B', 'C']
sage: FSM2 = FSM1.relabeled()
sage: FSM2.states()
[0, 1, 2]

remove_epsilon_transitions()

TESTS:

sage: FiniteStateMachine().remove_epsilon_transitions()
Traceback (most recent call last):
...
NotImplementedError

set_coordinates(coordinates, default=True)

Set coordinates of the states for the LaTeX representation by a dictionary or a function mapping labels to coordinates.

INPUT:

• coordinates – a dictionary or a function mapping labels of states to pairs interpreted as coordinates.
• default – If True, then states not given by coordinates get a default position on a circle of radius 3.

OUTPUT:

Nothing.

EXAMPLES:

sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]])
sage: F.set_coordinates({0: (0, 0), 1: (2, 0), 2: (1, 1)})
sage: F.state(0).coordinates
(0, 0)


We can also use a function to determine the coordinates:

sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]])
sage: F.set_coordinates(lambda l: (l, 3/(l+1)))
sage: F.state(2).coordinates
(2, 1)

split_transitions()

Returns a new transducer, where all transitions in self with input labels consisting of more than one letter are replaced by a path of the corresponding length.

INPUT:

Nothing.

OUTPUT:

A new transducer.

EXAMPLES:

sage: A = Transducer([('A', 'B', [1, 2, 3], 0)],
....:                initial_states=['A'], final_states=['B'])
sage: A.split_transitions().states()
[('A', ()), ('B', ()),
('A', (1,)), ('A', (1, 2))]

state(state)

Returns the state of the finite state machine.

INPUT:

• state – If state is not an instance of FSMState, then it is assumed that it is the label of a state.

OUTPUT:

Returns the state of the finite state machine corresponding to state.

If no state is found, then a LookupError is thrown.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A')
sage: FSM = FiniteStateMachine([(A, 'B'), ('C', A)])
sage: FSM.state('A') == A
True
sage: FSM.state('xyz')
Traceback (most recent call last):
...
LookupError: No state with label xyz found.

states()

Returns the states of the finite state machine.

INPUT:

Nothing.

OUTPUT:

The states of the finite state machine as list.

EXAMPLES:

sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])
sage: FSM.states()
['1', '2']

transition(transition)

Returns the transition of the finite state machine.

INPUT:

• transition – If transition is not an instance of FSMTransition, then it is assumed that it is a tuple (from_state, to_state, word_in, word_out).

OUTPUT:

Returns the transition of the finite state machine corresponding to transition.

If no transition is found, then a LookupError is thrown.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import FSMTransition
sage: t = FSMTransition('A', 'B', 0)
sage: F = FiniteStateMachine([t])
sage: F.transition(('A', 'B', 0))
Transition from 'A' to 'B': 0|-
sage: id(t) == id(F.transition(('A', 'B', 0)))
True

transitions(from_state=None)

Returns a list of all transitions.

INPUT:

• from_state – (default: None) If from_state is given, then a list of transitions starting there is given.

OUTPUT:

A list of all transitions.

EXAMPLES:

sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])
sage: FSM.transitions()
[Transition from '1' to '2': 1|-,
Transition from '2' to '2': 0|-]

transposition()

Returns a new finite state machine, where all transitions of the input finite state machine are reversed.

INPUT:

Nothing.

OUTPUT:

A new finite state machine.

EXAMPLES:

sage: aut = Automaton([('A', 'A', 0), ('A', 'A', 1), ('A', 'B', 0)],
....:                 initial_states=['A'], final_states=['B'])
sage: aut.transposition().transitions('B')
[Transition from 'B' to 'A': 0|-]

sage: aut = Automaton([('1', '1', 1), ('1', '2', 0), ('2', '2', 0)],
....:                 initial_states=['1'], final_states=['1', '2'])
sage: aut.transposition().initial_states()
['1', '2']

class sage.combinat.finite_state_machine.Transducer(data=None, initial_states=None, final_states=None, input_alphabet=None, output_alphabet=None, determine_alphabets=None, store_states_dict=True, on_duplicate_transition=None)

This creates a transducer, which is a finite state machine, whose transitions have input and output labels.

An transducer has additional features like creating a simplified transducer.

EXAMPLES:

We can create a transducer performing the addition of 1 (for numbers given in binary and read from right to left) in the following way:

sage: T = Transducer([('C', 'C', 1, 0), ('C', 'N', 0, 1),
....:                 ('N', 'N', 0, 0), ('N', 'N', 1, 1)],
....:                initial_states=['C'], final_states=['N'])
sage: T
Transducer with 2 states
sage: T([0])
[1]
sage: T([1,1,0])
[0, 0, 1]
sage: ZZ(T(15.digits(base=2)+[0]), base=2)
16


Note that we have padded the binary input sequence by a $$0$$ so that the transducer can reach its final state.

TESTS:

sage: Transducer()
Transducer with 0 states

cartesian_product(other, only_accessible_components=True)

Warning

The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting FSMOldCodeTransducerCartesianProduct to False.

Return a new transducer which can simultaneously process an input with self and other where the output labels are pairs of the original output labels.

INPUT:

• other - a finite state machine
• only_accessible_components – If True (default), then the result is piped through accessible_components. If no new_input_alphabet is given, it is determined by determine_alphabets().

OUTPUT:

A transducer which can simultaneously process an input with self and other.

The set of states of the new transducer is the cartesian product of the set of states of self and other.

Let $$(A, B, a, b)$$ be a transition of self and $$(C, D, c, d)$$ be a transition of other. Then there is a transition $$((A, C), (B, D), a, (b, d))$$ in the new transducer if $$a = c$$.

EXAMPLES:

Originally a different output was constructed by Transducer.cartesian_product. This output is now produced by Transducer.intersection.

sage: transducer1 = Transducer([('A', 'A', 0, 0),
....:                           ('A', 'A', 1, 1)],
....:                          initial_states=['A'],
....:                          final_states=['A'],
....:                          determine_alphabets=True)
sage: transducer2 = Transducer([(0, 1, 0, ['b', 'c']),
....:                           (0, 0, 1, 'b'),
....:                           (1, 1, 0, 'a')],
....:                          initial_states=[0],
....:                          final_states=[1],
....:                          determine_alphabets=True)
sage: result = transducer1.cartesian_product(transducer2)
doctest:1: DeprecationWarning: The output of
Transducer.cartesian_product will change.
Please use Transducer.intersection for the original output.
See http://trac.sagemath.org/16061 for details.
sage: result
Transducer with 0 states


By setting FSMOldCodeTransducerCartesianProduct to False the new desired output is produced.

sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = False
sage: result = transducer1.cartesian_product(transducer2)
sage: result
Transducer with 2 states
sage: result.transitions()
[Transition from ('A', 0) to ('A', 1): 0|(0, 'b'),(None, 'c'),
Transition from ('A', 0) to ('A', 0): 1|(1, 'b'),
Transition from ('A', 1) to ('A', 1): 0|(0, 'a')]
sage: result([1, 0, 0])
[(1, 'b'), (0, 'b'), (None, 'c'),  (0, 'a')]
sage: (transducer1([1, 0, 0]), transducer2([1, 0, 0]))
([1, 0, 0], ['b', 'b', 'c', 'a'])


The following transducer counts the number of 11 blocks minus the number of 10 blocks over the alphabet [0, 1].

sage: count_11 = transducers.CountSubblockOccurrences(
....:     [1, 1],
....:     input_alphabet=[0, 1])
sage: count_10 = transducers.CountSubblockOccurrences(
....:     [1, 0],
....:     input_alphabet=[0, 1])
sage: count_11x10 = count_11.cartesian_product(count_10)
sage: difference = transducers.sub([0, 1])(count_11x10)
sage: T = difference.simplification().relabeled()
sage: T.initial_states()
[1]
sage: sorted(T.transitions())
[Transition from 0 to 1: 0|-1,
Transition from 0 to 0: 1|1,
Transition from 1 to 1: 0|0,
Transition from 1 to 0: 1|0]
sage: input =  [0, 1, 1,  0, 1,  0, 0, 0, 1, 1, 1,  0]
sage: output = [0, 0, 1, -1, 0, -1, 0, 0, 0, 1, 1, -1]
sage: T(input) == output
True


If other is an automaton, then cartesian_product() returns self where the input is restricted to the input accepted by other.

For example, if the transducer transforms the standard binary expansion into the non-adjacent form and the automaton recognizes the binary expansion without adjacent ones, then the cartesian product of these two is a transducer which does not change the input (except for changing a to (a, None) and ignoring a leading $$0$$).

sage: NAF = Transducer([(0, 1, 0, None),
....:                   (0, 2, 1, None),
....:                   (1, 1, 0, 0),
....:                   (1, 2, 1, 0),
....:                   (2, 1, 0, 1),
....:                   (2, 3, 1, -1),
....:                   (3, 2, 0, 0),
....:                   (3, 3, 1, 0)],
....:                  initial_states=[0],
....:                  final_states=[1],
....:                  determine_alphabets=True)
sage: aut11 = Automaton([(0, 0, 0), (0, 1, 1), (1, 0, 0)],
....:                   initial_states=[0],
....:                   final_states=[0, 1],
....:                   determine_alphabets=True)
sage: res = NAF.cartesian_product(aut11)
sage: res([1, 0, 0, 1, 0, 1, 0])
[(1, None), (0, None), (0, None), (1, None), (0, None), (1, None)]


This is obvious because if the standard binary expansion does not have adjacent ones, then it is the same as the non-adjacent form.

Be aware that cartesian_product() is not commutative.

sage: aut11.cartesian_product(NAF)
Traceback (most recent call last):
...
TypeError: Only an automaton can be intersected with an automaton.

intersection(other, only_accessible_components=True)

Returns a new transducer which accepts an input if it is accepted by both given finite state machines producing the same output.

INPUT:

• other – a transducer
• only_accessible_components – If True (default), then the result is piped through accessible_components. If no new_input_alphabet is given, it is determined by determine_alphabets().

OUTPUT:

A new transducer which computes the intersection (see below) of the languages of self and other.

The set of states of the transducer is the cartesian product of the set of states of both given transducer. There is a transition $$((A, B), (C, D), a, b)$$ in the new transducer if there are transitions $$(A, C, a, b)$$ and $$(B, D, a, b)$$ in the old transducers.

EXAMPLES:

sage: transducer1 = Transducer([('1', '2', 1, 0),
....:                           ('2', '2', 1, 0),
....:                           ('2', '2', 0, 1)],
....:                          initial_states=['1'],
....:                          final_states=['2'],
....:                          determine_alphabets=True)
sage: transducer2 = Transducer([('A', 'A', 1, 0),
....:                           ('A', 'B', 0, 0),
....:                           ('B', 'B', 0, 1),
....:                           ('B', 'A', 1, 1)],
....:                          initial_states=['A'],
....:                          final_states=['B'],
....:                          determine_alphabets=True)
sage: res = transducer1.intersection(transducer2)
sage: res.transitions()
[Transition from ('1', 'A') to ('2', 'A'): 1|0,
Transition from ('2', 'A') to ('2', 'A'): 1|0]


In general, transducers are not closed under intersection. But for transducer which do not have epsilon-transitions, the intersection is well defined (cf. [BaWo2012]). However, in the next example the intersection of the two transducers is not well defined. The intersection of the languages consists of $$(a^n, b^n c^n)$$. This set is not recognizable by a finite transducer.

sage: t1 = Transducer([(0, 0, 'a', 'b'),
....:                  (0, 1, None, 'c'),
....:                  (1, 1, None, 'c')],
....:                 initial_states=[0],
....:                 final_states=[0, 1],
....:                 determine_alphabets=True)
sage: t2 = Transducer([('A', 'A', None, 'b'),
....:                  ('A', 'B', 'a', 'c'),
....:                  ('B', 'B', 'a', 'c')],
....:                 initial_states=['A'],
....:                 final_states=['A', 'B'],
....:                 determine_alphabets=True)
sage: t2.intersection(t1)
Traceback (most recent call last):
...
ValueError: An epsilon-transition (with empty input or output)
was found.


REFERENCES:

 [BaWo2012] Javier Baliosian and Dina Wonsever, Finite State Transducers, chapter in Handbook of Finite State Based Models and Applications, edited by Jiacun Wang, Chapman and Hall/CRC, 2012.
process(*args, **kwargs)

Warning

The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting FSMOldProcessOutput to False.

Returns whether the transducer accepts the input, the state where the computation stops and which output is generated.

INPUT:

• input_tape – The input tape can be a list with entries from the input alphabet.
• initial_state – (default: None) The state in which to start. If this parameter is None and there is only one initial state in the machine, then this state is taken.
• full_output – (default: True) If set, then the full output is given, otherwise only the generated output (the third entry below only). If the input is not accepted, a ValueError is raised.

OUTPUT:

The full output is a triple, where

• the first entry is True if the input string is accepted,
• the second gives the reached state after processing the input tape (This is a state with label None if the input could not be processed, i.e., when at one point no transition to go could be found.), and
• the third gives a list of the output labels used during processing.

Note that in the case the transducer is not deterministic, one possible path is gone. This means, that in this case the output can be wrong.

By setting FSMOldProcessOutput to False the new desired output is produced.

EXAMPLES:

sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False  # activate new output behavior
sage: from sage.combinat.finite_state_machine import FSMState
sage: A = FSMState('A', is_initial = True, is_final = True)
sage: binary_inverter = Transducer({A:[(A, 0, 1), (A, 1, 0)]})
sage: binary_inverter.process([0, 1, 0, 0, 1, 1])
(True, 'A', [1, 0, 1, 1, 0, 0])


If we are only interested in the output, we can also use:

sage: binary_inverter([0, 1, 0, 0, 1, 1])
[1, 0, 1, 1, 0, 0]


The following transducer transforms $$0^n 1$$ to $$1^n 2$$:

sage: T = Transducer([(0, 0, 0, 1), (0, 1, 1, 2)])
sage: T.state(0).is_initial = True
sage: T.state(1).is_final = True


We can see the different possibilites of the output by:

sage: [T.process(w) for w in [[1], [0, 1], [0, 0, 1], [0, 1, 1],
....:                         [0], [0, 0], [2, 0], [0, 1, 2]]]
[(True, 1, [2]), (True, 1, [1, 2]),
(True, 1, [1, 1, 2]), (False, None, None),
(False, 0, [1]), (False, 0, [1, 1]),
(False, None, None), (False, None, None)]


If we just want a condensed output, we use:

sage: [T.process(w, full_output=False)
....:      for w in [[1], [0, 1], [0, 0, 1]]]
[[2], [1, 2], [1, 1, 2]]
sage: T.process([0, 1, 2], full_output=False)
Traceback (most recent call last):
...
ValueError: Invalid input sequence.


It is equivalent to:

sage: [T(w) for w in [[1], [0, 1], [0, 0, 1]]]
[[2], [1, 2], [1, 1, 2]]
sage: T([0, 1, 2])
Traceback (most recent call last):
...
ValueError: Invalid input sequence.

simplification()

Returns a simplified transducer.

INPUT:

Nothing.

OUTPUT:

A new transducer.

This function simplifies a transducer by Moore’s algorithm, first moving common output labels of transitions leaving a state to output labels of transitions entering the state (cf. prepone_output()).

The resulting transducer implements the same function as the original transducer.

EXAMPLES:

sage: fsm = Transducer([("A", "B", 0, 1), ("A", "B", 1, 0),
....:                           ("B", "C", 0, 0), ("B", "C", 1, 1),
....:                           ("C", "D", 0, 1), ("C", "D", 1, 0),
....:                           ("D", "A", 0, 0), ("D", "A", 1, 1)])
sage: fsms = fsm.simplification()
sage: fsms
Transducer with 2 states
sage: fsms.transitions()
[Transition from ('A', 'C')
to ('B', 'D'): 0|1,
Transition from ('A', 'C')
to ('B', 'D'): 1|0,
Transition from ('B', 'D')
to ('A', 'C'): 0|0,
Transition from ('B', 'D')
to ('A', 'C'): 1|1]
sage: fsms.relabeled().transitions()
[Transition from 0 to 1: 0|1,
Transition from 0 to 1: 1|0,
Transition from 1 to 0: 0|0,
Transition from 1 to 0: 1|1]

sage: fsm = Transducer([("A", "A", 0, 0),
....:                   ("A", "B", 1, 1),
....:                   ("A", "C", 1, -1),
....:                   ("B", "A", 2, 0),
....:                   ("C", "A", 2, 0)])
sage: fsm_simplified = fsm.simplification()
sage: fsm_simplified
Transducer with 2 states
sage: fsm_simplified.transitions()
[Transition from ('A',) to ('A',): 0|0,
Transition from ('A',) to ('B', 'C'): 1|1,0,
Transition from ('A',) to ('B', 'C'): 1|-1,0,
Transition from ('B', 'C') to ('A',): 2|-]

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: T = Transducer([('A', 'A', 1/2, 0),
....:                 ('A', 'B', 1/4, 1),
....:                 ('A', 'C', 1/4, 1),
....:                 ('B', 'A', 1, 0),
....:                 ('C', 'A', 1, 0)],
....:                initial_states=[0],
....:                final_states=['A', 'B', 'C'],
sage: sorted(T.simplification().transitions())
[Transition from ('A',) to ('A',): 1/2|0,
Transition from ('A',) to ('B', 'C'): 1/2|1,
Transition from ('B', 'C') to ('A',): 1|0]


Illustrating the use of colors in order to avoid identification of states:

sage: T = Transducer( [[0,0,0,0], [0,1,1,1],
....:                  [1,0,0,0], [1,1,1,1]],
....:                 initial_states=[0],
....:                 final_states=[0,1])
sage: sorted(T.simplification().transitions())
[Transition from (0, 1) to (0, 1): 0|0,
Transition from (0, 1) to (0, 1): 1|1]
sage: T.state(0).color = 0
sage: T.state(0).color = 1
sage: sorted(T.simplification().transitions())
[Transition from (0,) to (0,): 0|0,
Transition from (0,) to (1,): 1|1,
Transition from (1,) to (0,): 0|0,
Transition from (1,) to (1,): 1|1]


Alternative function for handling duplicate transitions in finite state machines. This implementation adds the input label of the new transition to the input label of the old transition. This is intended for the case where a Markov chain is modelled by a finite state machine using the input labels as transition probabilities.

See the documentation of the on_duplicate_transition parameter of FiniteStateMachine.

INPUT:

• old_transition – A transition in a finite state machine.
• new_transition – A transition, identical to old_transition, which is to be inserted into the finite state machine.

OUTPUT:

A transition whose input weight is the sum of the input weights of old_transition and new_transition.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input
sage: from sage.combinat.finite_state_machine import FSMTransition
....:                                FSMTransition('a', 'a', 1/2))
Transition from 'a' to 'a': 1|-


Input labels must be lists of length 1:

sage: duplicate_transition_add_input(FSMTransition('a', 'a', [1, 1]),
....:                                FSMTransition('a', 'a', [1, 1]))
Traceback (most recent call last):
...
TypeError: Trying to use duplicate_transition_add_input on
"Transition from 'a' to 'a': 1,1|-" and
"Transition from 'a' to 'a': 1,1|-",
but input words are assumed to be lists of length 1

sage.combinat.finite_state_machine.duplicate_transition_ignore(old_transition, new_transition)

Default function for handling duplicate transitions in finite state machines. This implementation ignores the occurrence.

See the documentation of the on_duplicate_transition parameter of FiniteStateMachine.

INPUT:

• old_transition – A transition in a finite state machine.
• new_transition – A transition, identical to old_transition, which is to be inserted into the finite state machine.

OUTPUT:

The same transition, unchanged.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import duplicate_transition_ignore
sage: from sage.combinat.finite_state_machine import FSMTransition
sage: duplicate_transition_ignore(FSMTransition(0, 0, 1),
....:                             FSMTransition(0, 0, 1))
Transition from 0 to 0: 1|-

sage.combinat.finite_state_machine.duplicate_transition_raise_error(old_transition, new_transition)

Alternative function for handling duplicate transitions in finite state machines. This implementation raises a ValueError.

See the documentation of the on_duplicate_transition parameter of FiniteStateMachine.

INPUT:

• old_transition – A transition in a finite state machine.
• new_transition – A transition, identical to old_transition, which is to be inserted into the finite state machine.

OUTPUT:

Nothing. A ValueError is raised.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error
sage: from sage.combinat.finite_state_machine import FSMTransition
sage: duplicate_transition_raise_error(FSMTransition(0, 0, 1),
....:                                  FSMTransition(0, 0, 1))
Traceback (most recent call last):
...
ValueError: Attempting to re-insert transition Transition from 0 to 0: 1|-

sage.combinat.finite_state_machine.full_group_by(l, key=<function <lambda> at 0x68062a8>)

Group iterable l by values of key.

INPUT:

• iterable l
• key function key

OUTPUT:

A list of pairs (k, elements) such that key(e)=k for all e in elements.

This is similar to itertools.groupby except that lists are returned instead of iterables and no prior sorting is required.

We do not require

• that the keys are sortable (in contrast to the approach via sorted and itertools.groupby) and
• that the keys are hashable (in contrast to the implementation proposed in http://stackoverflow.com/a/15250161).

However, it is required

• that distinct keys have distinct str-representations.

The implementation is inspired by http://stackoverflow.com/a/15250161, but non-hashable keys are allowed.

EXAMPLES:

sage: from sage.combinat.finite_state_machine import full_group_by
sage: t = [2/x, 1/x, 2/x]
sage: r = full_group_by([0,1,2], key=lambda i:t[i])
sage: sorted(r, key=lambda p:p[1])
[(2/x, [0, 2]), (1/x, [1])]
sage: from itertools import groupby
sage: for k, elements in groupby(sorted([0,1,2],
....:                            key=lambda i:t[i]),
....:                            key=lambda i:t[i]):
....:     print k, list(elements)
2/x [0]
1/x [1]
2/x [2]


Note that the behavior is different from itertools.groupby because neither $$1/x<2/x$$ nor $$2/x<1/x$$ does hold.

Here, the result r has been sorted in order to guarantee a consistent order for the doctest suite.

sage.combinat.finite_state_machine.is_Automaton(FSM)

Tests whether or not FSM inherits from Automaton.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Automaton
sage: is_Automaton(FiniteStateMachine())
False
sage: is_Automaton(Automaton())
True
sage: is_FiniteStateMachine(Automaton())
True

sage.combinat.finite_state_machine.is_FSMProcessIterator(PI)

Tests whether or not PI inherits from FSMProcessIterator.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FSMProcessIterator, FSMProcessIterator
sage: is_FSMProcessIterator(FSMProcessIterator(FiniteStateMachine([[0, 0, 0, 0]], initial_states=[0])))
True

sage.combinat.finite_state_machine.is_FSMState(S)

Tests whether or not S inherits from FSMState.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FSMState, FSMState
sage: is_FSMState(FSMState('A'))
True

sage.combinat.finite_state_machine.is_FSMTransition(T)

Tests whether or not T inherits from FSMTransition.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FSMTransition, FSMTransition
sage: is_FSMTransition(FSMTransition('A', 'B'))
True

sage.combinat.finite_state_machine.is_FiniteStateMachine(FSM)

Tests whether or not FSM inherits from FiniteStateMachine.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine
sage: is_FiniteStateMachine(FiniteStateMachine())
True
sage: is_FiniteStateMachine(Automaton())
True
sage: is_FiniteStateMachine(Transducer())
True

sage.combinat.finite_state_machine.is_Transducer(FSM)

Tests whether or not FSM inherits from Transducer.

TESTS:

sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Transducer
sage: is_Transducer(FiniteStateMachine())
False
sage: is_Transducer(Transducer())
True
sage: is_FiniteStateMachine(Transducer())
True

sage.combinat.finite_state_machine.setup_latex_preamble()

This function adds the package tikz with support for automata to the preamble of Latex so that the finite state machines can be drawn nicely.

INPUT:

Nothing.

OUTPUT:

Nothing.

TESTS:

sage: from sage.combinat.finite_state_machine import setup_latex_preamble
sage: setup_latex_preamble()