code stringlengths 17 6.64M |
|---|
def duplicate_transition_raise_error(old_transition, new_transition):
'\n Alternative function for handling duplicate transitions in finite\n state machines. This implementation raises a ``ValueError``.\n\n See the documentation of the ``on_duplicate_transition`` parameter\n of :class:`FiniteStateMachine`.\n\n INPUT:\n\n - ``old_transition`` -- A transition in a finite state machine.\n\n - ``new_transition`` -- A transition, identical to ``old_transition``,\n which is to be inserted into the finite state machine.\n\n OUTPUT:\n\n Nothing. A ``ValueError`` is raised.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: duplicate_transition_raise_error(FSMTransition(0, 0, 1),\n ....: FSMTransition(0, 0, 1))\n Traceback (most recent call last):\n ...\n ValueError: Attempting to re-insert transition Transition from 0 to 0: 1|-\n '
raise ValueError(('Attempting to re-insert transition %s' % old_transition))
|
def duplicate_transition_add_input(old_transition, new_transition):
'\n Alternative function for handling duplicate transitions in finite\n state machines. This implementation adds the input label of the\n new transition to the input label of the old transition. This is\n intended for the case where a Markov chain is modelled by a finite\n state machine using the input labels as transition probabilities.\n\n See the documentation of the ``on_duplicate_transition`` parameter\n of :class:`FiniteStateMachine`.\n\n INPUT:\n\n - ``old_transition`` -- A transition in a finite state machine.\n\n - ``new_transition`` -- A transition, identical to ``old_transition``,\n which is to be inserted into the finite state machine.\n\n OUTPUT:\n\n A transition whose input weight is the sum of the input\n weights of ``old_transition`` and ``new_transition``.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: duplicate_transition_add_input(FSMTransition(\'a\', \'a\', 1/2),\n ....: FSMTransition(\'a\', \'a\', 1/2))\n Transition from \'a\' to \'a\': 1|-\n\n Input labels must be lists of length 1::\n\n sage: duplicate_transition_add_input(FSMTransition(\'a\', \'a\', [1, 1]),\n ....: FSMTransition(\'a\', \'a\', [1, 1]))\n Traceback (most recent call last):\n ...\n TypeError: Trying to use duplicate_transition_add_input on\n "Transition from \'a\' to \'a\': 1,1|-" and\n "Transition from \'a\' to \'a\': 1,1|-",\n but input words are assumed to be lists of length 1\n '
if (isinstance(old_transition.word_in, Iterable) and (len(old_transition.word_in) == 1) and isinstance(new_transition.word_in, Iterable) and (len(new_transition.word_in) == 1)):
old_transition.word_in = [(old_transition.word_in[0] + new_transition.word_in[0])]
else:
raise TypeError((('Trying to use duplicate_transition_add_input on ' + ('"%s" and "%s", ' % (old_transition, new_transition))) + 'but input words are assumed to be lists of length 1'))
return old_transition
|
class FiniteStateMachine(SageObject):
'\n Class for a finite state machine.\n\n A finite state machine is a finite set of states connected by\n transitions.\n\n INPUT:\n\n - ``data`` -- can be any of the following:\n\n #. a dictionary of dictionaries (of transitions),\n\n #. a dictionary of lists (of states or transitions),\n\n #. a list (of transitions),\n\n #. a function (transition function),\n\n #. an other instance of a finite state machine.\n\n - ``initial_states`` and ``final_states`` -- the initial and\n final states of this machine\n\n - ``input_alphabet`` and ``output_alphabet`` -- the input and\n output alphabets of this machine\n\n - ``determine_alphabets`` -- If ``True``, then the function\n :meth:`.determine_alphabets` is called after ``data`` was read and\n processed, if ``False``, then not. If it is ``None``, then it is\n decided during the construction of the finite state machine\n whether :meth:`.determine_alphabets` should be called.\n\n - ``with_final_word_out`` -- If given (not ``None``), then the\n function :meth:`.with_final_word_out` (more precisely, its inplace\n pendant :meth:`.construct_final_word_out`) is called with input\n ``letters=with_final_word_out`` at the end of the creation\n process.\n\n - ``store_states_dict`` -- If ``True``, then additionally the states\n are stored in an internal dictionary for speed up.\n\n - ``on_duplicate_transition`` -- A function which is called when a\n transition is inserted into ``self`` which already existed (same\n ``from_state``, same ``to_state``, same ``word_in``, same ``word_out``).\n\n This function is assumed to take two arguments, the first being\n the already existing transition, the second being the new\n transition (as an :class:`FSMTransition`). The function must\n return the (possibly modified) original transition.\n\n By default, we have ``on_duplicate_transition=None``, which is\n interpreted as\n ``on_duplicate_transition=duplicate_transition_ignore``, where\n ``duplicate_transition_ignore`` is a predefined function\n ignoring the occurrence. Other such predefined functions are\n ``duplicate_transition_raise_error`` and\n ``duplicate_transition_add_input``.\n\n OUTPUT:\n\n A finite state machine.\n\n The object creation of :class:`Automaton` and :class:`Transducer`\n is the same as the one described here (i.e. just replace the word\n ``FiniteStateMachine`` by ``Automaton`` or ``Transducer``).\n\n Each transition of an automaton has an input label. Automata can,\n for example, be determinised (see\n :meth:`Automaton.determinisation`) and minimized (see\n :meth:`Automaton.minimization`). Each transition of a transducer\n has an input and an output label. Transducers can, for example, be\n simplified (see :meth:`Transducer.simplification`).\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n\n See documentation for more examples.\n\n We illustrate the different input formats:\n\n #. The input-data can be a dictionary of dictionaries, where\n\n - the keys of the outer dictionary are state-labels (from-states of\n transitions),\n - the keys of the inner dictionaries are state-labels (to-states of\n transitions),\n - the values of the inner dictionaries specify the transition\n more precisely.\n\n The easiest is to use a tuple consisting of an input and an\n output word::\n\n sage: FiniteStateMachine({\'a\':{\'b\':(0, 1), \'c\':(1, 1)}})\n Finite state machine with 3 states\n\n Instead of the tuple anything iterable (e.g. a list) can be\n used as well.\n\n If you want to use the arguments of :class:`FSMTransition`\n directly, you can use a dictionary::\n\n sage: FiniteStateMachine({\'a\':{\'b\':{\'word_in\':0, \'word_out\':1},\n ....: \'c\':{\'word_in\':1, \'word_out\':1}}})\n Finite state machine with 3 states\n\n In the case you already have instances of\n :class:`FSMTransition`, it is possible to use them directly::\n\n sage: FiniteStateMachine({\'a\':{\'b\':FSMTransition(\'a\', \'b\', 0, 1),\n ....: \'c\':FSMTransition(\'a\', \'c\', 1, 1)}})\n Finite state machine with 3 states\n\n #. The input-data can be a dictionary of lists, where the keys\n are states or label of states.\n\n The list-elements can be states::\n\n sage: a = FSMState(\'a\')\n sage: b = FSMState(\'b\')\n sage: c = FSMState(\'c\')\n sage: FiniteStateMachine({a:[b, c]})\n Finite state machine with 3 states\n\n Or the list-elements can simply be labels of states::\n\n sage: FiniteStateMachine({\'a\':[\'b\', \'c\']})\n Finite state machine with 3 states\n\n The list-elements can also be transitions::\n\n sage: FiniteStateMachine({\'a\':[FSMTransition(\'a\', \'b\', 0, 1),\n ....: FSMTransition(\'a\', \'c\', 1, 1)]})\n Finite state machine with 3 states\n\n Or they can be tuples of a label, an input word and an output\n word specifying a transition::\n\n sage: FiniteStateMachine({\'a\':[(\'b\', 0, 1), (\'c\', 1, 1)]})\n Finite state machine with 3 states\n\n #. The input-data can be a list, where its elements specify\n transitions::\n\n sage: FiniteStateMachine([FSMTransition(\'a\', \'b\', 0, 1),\n ....: FSMTransition(\'a\', \'c\', 1, 1)])\n Finite state machine with 3 states\n\n It is possible to skip ``FSMTransition`` in the example above::\n\n sage: FiniteStateMachine([(\'a\', \'b\', 0, 1), (\'a\', \'c\', 1, 1)])\n Finite state machine with 3 states\n\n The parameters of the transition are given in tuples. Anyhow,\n anything iterable (e.g. a list) is possible.\n\n You can also name the parameters of the transition. For this\n purpose you take a dictionary::\n\n sage: FiniteStateMachine([{\'from_state\':\'a\', \'to_state\':\'b\',\n ....: \'word_in\':0, \'word_out\':1},\n ....: {\'from_state\':\'a\', \'to_state\':\'c\',\n ....: \'word_in\':1, \'word_out\':1}])\n Finite state machine with 3 states\n\n Other arguments, which :class:`FSMTransition` accepts, can be\n added, too.\n\n #. The input-data can also be function acting as transition\n function:\n\n This function has two input arguments:\n\n #. a label of a state (from which the transition starts),\n\n #. a letter of the (input-)alphabet (as input-label of the transition).\n\n It returns a tuple with the following entries:\n\n #. a label of a state (to which state the transition goes),\n\n #. a letter of or a word over the (output-)alphabet (as\n output-label of the transition).\n\n It may also output a list of such tuples if several\n transitions from the from-state and the input letter exist\n (this means that the finite state machine is\n non-deterministic).\n\n If the transition does not exist, the function should raise a\n ``LookupError`` or return an empty list.\n\n When constructing a finite state machine in this way, some\n initial states and an input alphabet have to be specified.\n\n ::\n\n sage: def f(state_from, read):\n ....: if int(state_from) + read <= 2:\n ....: state_to = 2*int(state_from)+read\n ....: write = 0\n ....: else:\n ....: state_to = 2*int(state_from) + read - 5\n ....: write = 1\n ....: return (str(state_to), write)\n sage: F = FiniteStateMachine(f, input_alphabet=[0, 1],\n ....: initial_states=[\'0\'],\n ....: final_states=[\'0\'])\n sage: F([1, 0, 1])\n (True, \'0\', [0, 0, 1])\n\n #. The input-data can be an other instance of a finite state machine::\n\n sage: F = FiniteStateMachine()\n sage: G = Transducer(F)\n sage: G == F\n True\n\n The other parameters cannot be specified in that case. If you\n want to change these, use the attributes\n :attr:`FSMState.is_initial`, :attr:`FSMState.is_final`,\n :attr:`input_alphabet`, :attr:`output_alphabet`,\n :attr:`on_duplicate_transition` and methods\n :meth:`.determine_alphabets`,\n :meth:`.construct_final_word_out` on the new machine,\n respectively.\n\n The following examples demonstrate the use of ``on_duplicate_transition``::\n\n sage: F = FiniteStateMachine([[\'a\', \'a\', 1/2], [\'a\', \'a\', 1/2]])\n sage: F.transitions()\n [Transition from \'a\' to \'a\': 1/2|-]\n\n ::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error\n sage: F1 = FiniteStateMachine([[\'a\', \'a\', 1/2], [\'a\', \'a\', 1/2]],\n ....: on_duplicate_transition=duplicate_transition_raise_error)\n Traceback (most recent call last):\n ...\n ValueError: Attempting to re-insert transition Transition from \'a\' to \'a\': 1/2|-\n\n Use ``duplicate_transition_add_input`` to emulate a Markov chain,\n the input labels are considered as transition probabilities::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: F = FiniteStateMachine([[\'a\', \'a\', 1/2], [\'a\', \'a\', 1/2]],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: F.transitions()\n [Transition from \'a\' to \'a\': 1|-]\n\n Use ``with_final_word_out`` to construct final output::\n\n sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0],\n ....: with_final_word_out=0)\n sage: for s in T.iter_final_states():\n ....: print("{} {}".format(s, s.final_word_out))\n 0 []\n 1 [0]\n\n TESTS::\n\n sage: a = FSMState(\'S_a\', \'a\')\n sage: b = FSMState(\'S_b\', \'b\')\n sage: c = FSMState(\'S_c\', \'c\')\n sage: d = FSMState(\'S_d\', \'d\')\n sage: FiniteStateMachine({a:[b, c], b:[b, c, d],\n ....: c:[a, b], d:[a, c]})\n Finite state machine with 4 states\n\n We have several constructions which lead to the same finite\n state machine::\n\n sage: A = FSMState(\'A\')\n sage: B = FSMState(\'B\')\n sage: C = FSMState(\'C\')\n sage: FSM1 = FiniteStateMachine(\n ....: {A:{B:{\'word_in\':0, \'word_out\':1},\n ....: C:{\'word_in\':1, \'word_out\':1}}})\n sage: FSM2 = FiniteStateMachine({A:{B:(0, 1), C:(1, 1)}})\n sage: FSM3 = FiniteStateMachine(\n ....: {A:{B:FSMTransition(A, B, 0, 1),\n ....: C:FSMTransition(A, C, 1, 1)}})\n sage: FSM4 = FiniteStateMachine({A:[(B, 0, 1), (C, 1, 1)]})\n sage: FSM5 = FiniteStateMachine(\n ....: {A:[FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)]})\n sage: FSM6 = FiniteStateMachine(\n ....: [{\'from_state\':A, \'to_state\':B, \'word_in\':0, \'word_out\':1},\n ....: {\'from_state\':A, \'to_state\':C, \'word_in\':1, \'word_out\':1}])\n sage: FSM7 = FiniteStateMachine([(A, B, 0, 1), (A, C, 1, 1)])\n sage: FSM8 = FiniteStateMachine(\n ....: [FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)])\n\n sage: FSM1 == FSM2 == FSM3 == FSM4 == FSM5 == FSM6 == FSM7 == FSM8\n True\n\n It is possible to skip ``FSMTransition`` in the example above.\n\n Some more tests for different input-data::\n\n sage: FiniteStateMachine({\'a\':{\'a\':[0, 0], \'b\':[1, 1]},\n ....: \'b\':{\'b\':[1, 0]}})\n Finite state machine with 2 states\n\n sage: a = FSMState(\'S_a\', \'a\')\n sage: b = FSMState(\'S_b\', \'b\')\n sage: c = FSMState(\'S_c\', \'c\')\n sage: d = FSMState(\'S_d\', \'d\')\n sage: t1 = FSMTransition(a, b)\n sage: t2 = FSMTransition(b, c)\n sage: t3 = FSMTransition(b, d)\n sage: t4 = FSMTransition(c, d)\n sage: FiniteStateMachine([t1, t2, t3, t4])\n Finite state machine with 4 states\n\n We test that no input parameter is allowed when creating a finite\n state machine from an existing instance::\n\n sage: F = FiniteStateMachine()\n sage: FiniteStateMachine(F, initial_states=[1])\n Traceback (most recent call last):\n ...\n ValueError: initial_states cannot be specified when\n copying another finite state machine.\n sage: FiniteStateMachine(F, final_states=[1])\n Traceback (most recent call last):\n ...\n ValueError: final_states cannot be specified when\n copying another finite state machine.\n sage: FiniteStateMachine(F, input_alphabet=[1])\n Traceback (most recent call last):\n ...\n ValueError: input_alphabet cannot be specified when\n copying another finite state machine.\n sage: FiniteStateMachine(F, output_alphabet=[1])\n Traceback (most recent call last):\n ...\n ValueError: output_alphabet cannot be specified when\n copying another finite state machine.\n sage: from sage.combinat.finite_state_machine import (\n ....: duplicate_transition_add_input)\n sage: FiniteStateMachine(F,\n ....: on_duplicate_transition=duplicate_transition_add_input)\n Traceback (most recent call last):\n ...\n ValueError: on_duplicate_transition cannot be specified when\n copying another finite state machine.\n sage: FiniteStateMachine(F, determine_alphabets=False)\n Traceback (most recent call last):\n ...\n ValueError: determine_alphabets cannot be specified when\n copying another finite state machine.\n sage: FiniteStateMachine(F, with_final_word_out=[1])\n Traceback (most recent call last):\n ...\n ValueError: with_final_word_out cannot be specified when\n copying another finite state machine.\n\n :trac:`19454` rewrote automatic detection of the alphabets::\n\n sage: def transition_function(state, letter):\n ....: return (0, 3 + letter)\n sage: T1 = Transducer(transition_function,\n ....: input_alphabet=[0, 1],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T1.output_alphabet\n [3, 4]\n sage: T2 = Transducer([(0, 0, 0, 3), (0, 0, 0, 4)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T2.output_alphabet\n [3, 4]\n sage: T = Transducer([(0, 0, 1, 2)])\n sage: (T.input_alphabet, T.output_alphabet)\n ([1], [2])\n sage: T = Transducer([(0, 0, 1, 2)], determine_alphabets=False)\n sage: (T.input_alphabet, T.output_alphabet)\n (None, None)\n sage: T = Transducer([(0, 0, 1, 2)], input_alphabet=[0, 1])\n sage: (T.input_alphabet, T.output_alphabet)\n ([0, 1], [2])\n sage: T = Transducer([(0, 0, 1, 2)], output_alphabet=[2, 3])\n sage: (T.input_alphabet, T.output_alphabet)\n ([1], [2, 3])\n sage: T = Transducer([(0, 0, 1, 2)], input_alphabet=[0, 1],\n ....: output_alphabet=[2, 3])\n sage: (T.input_alphabet, T.output_alphabet)\n ([0, 1], [2, 3])\n\n .. automethod:: __call__\n '
on_duplicate_transition = duplicate_transition_ignore
'\n Which function to call when a duplicate transition is inserted.\n\n It can be set by the parameter ``on_duplicate_transition`` when\n initializing a finite state machine, see\n :class:`FiniteStateMachine`.\n\n .. SEEALSO::\n\n :class:`FiniteStateMachine`, :meth:`is_Markov_chain`,\n :meth:`markov_chain_simplification`.\n '
input_alphabet = None
'\n A list of letters representing the input alphabet of the finite\n state machine.\n\n It can be set by the parameter ``input_alphabet`` when initializing\n a finite state machine, see :class:`FiniteStateMachine`.\n\n It can also be set by the method :meth:`determine_alphabets`.\n\n .. SEEALSO::\n\n :class:`FiniteStateMachine`, :meth:`determine_alphabets`,\n :attr:`output_alphabet`.\n '
output_alphabet = None
'\n A list of letters representing the output alphabet of the finite\n state machine.\n\n It can be set by the parameter ``output_alphabet`` when initializing\n a finite state machine, see :class:`FiniteStateMachine`.\n\n It can also be set by the method :meth:`determine_alphabets`.\n\n .. SEEALSO::\n\n :class:`FiniteStateMachine`,\n :meth:`determine_alphabets`,\n :attr:`input_alphabet`.\n '
def __init__(self, data=None, initial_states=None, final_states=None, input_alphabet=None, output_alphabet=None, determine_alphabets=None, with_final_word_out=None, store_states_dict=True, on_duplicate_transition=None):
'\n See :class:`FiniteStateMachine` for more information.\n\n TESTS::\n\n sage: FiniteStateMachine()\n Empty finite state machine\n '
self._states_ = []
if store_states_dict:
self._states_dict_ = {}
self._allow_composition_ = True
if is_FiniteStateMachine(data):
if (initial_states is not None):
raise ValueError('initial_states cannot be specified when copying another finite state machine.')
if (final_states is not None):
raise ValueError('final_states cannot be specified when copying another finite state machine.')
if (input_alphabet is not None):
raise ValueError('input_alphabet cannot be specified when copying another finite state machine.')
if (output_alphabet is not None):
raise ValueError('output_alphabet cannot be specified when copying another finite state machine.')
if (on_duplicate_transition is not None):
raise ValueError('on_duplicate_transition cannot be specified when copying another finite state machine.')
if (determine_alphabets is not None):
raise ValueError('determine_alphabets cannot be specified when copying another finite state machine.')
if (with_final_word_out is not None):
raise ValueError('with_final_word_out cannot be specified when copying another finite state machine.')
self._copy_from_other_(data)
return
if (initial_states is not None):
if (not isinstance(initial_states, Iterable)):
raise TypeError('Initial states must be iterable (e.g. a list of states).')
for s in initial_states:
state = self.add_state(s)
state.is_initial = True
if (final_states is not None):
if (not isinstance(final_states, Iterable)):
raise TypeError('Final states must be iterable (e.g. a list of states).')
for s in final_states:
state = self.add_state(s)
state.is_final = True
self.input_alphabet = input_alphabet
self.output_alphabet = output_alphabet
if (on_duplicate_transition is None):
on_duplicate_transition = duplicate_transition_ignore
if callable(on_duplicate_transition):
self.on_duplicate_transition = on_duplicate_transition
else:
raise TypeError('on_duplicate_transition must be callable')
if (data is None):
pass
elif isinstance(data, Mapping):
for (sf, iter_transitions) in data.items():
self.add_state(sf)
if isinstance(iter_transitions, Mapping):
for (st, transition) in iter_transitions.items():
self.add_state(st)
if is_FSMTransition(transition):
self.add_transition(transition)
elif isinstance(transition, Mapping):
self.add_transition(sf, st, **transition)
elif isinstance(transition, Iterable):
self.add_transition(sf, st, *transition)
else:
self.add_transition(sf, st, transition)
elif isinstance(iter_transitions, Iterable):
for transition in iter_transitions:
if isinstance(transition, Iterable):
L = [sf]
L.extend(transition)
elif is_FSMTransition(transition):
L = transition
else:
L = [sf, transition]
self.add_transition(L)
else:
raise TypeError('Wrong input data for transition.')
elif isinstance(data, Iterable):
for transition in data:
if is_FSMTransition(transition):
self.add_transition(transition)
elif isinstance(transition, Mapping):
self.add_transition(transition)
elif isinstance(transition, Iterable):
self.add_transition(transition)
else:
raise TypeError('Wrong input data for transition.')
elif callable(data):
self.add_from_transition_function(data)
else:
raise TypeError('Cannot decide what to do with data.')
if ((determine_alphabets is None) and (data is not None)):
if (input_alphabet is None):
self.determine_input_alphabet()
if (output_alphabet is None):
self.determine_output_alphabet()
elif determine_alphabets:
self.determine_alphabets()
if (with_final_word_out is not None):
self.construct_final_word_out(with_final_word_out)
def __copy__(self):
'\n Return a (shallow) copy of the finite state machine.\n\n OUTPUT:\n\n A new finite state machine.\n\n TESTS::\n\n sage: copy(FiniteStateMachine())\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
copy = __copy__
def empty_copy(self, memo=None, new_class=None):
"\n Return an empty deep copy of the finite state machine, i.e.,\n ``input_alphabet``, ``output_alphabet``, ``on_duplicate_transition``\n are preserved, but states and transitions are not.\n\n INPUT:\n\n - ``memo`` -- a dictionary storing already processed elements.\n\n - ``new_class`` -- a class for the copy. By default\n (``None``), the class of ``self`` is used.\n\n OUTPUT:\n\n A new finite state machine.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error\n sage: F = FiniteStateMachine([('A', 'A', 0, 2), ('A', 'A', 1, 3)],\n ....: input_alphabet=[0, 1],\n ....: output_alphabet=[2, 3],\n ....: on_duplicate_transition=duplicate_transition_raise_error)\n sage: FE = F.empty_copy(); FE\n Empty finite state machine\n sage: FE.input_alphabet\n [0, 1]\n sage: FE.output_alphabet\n [2, 3]\n sage: FE.on_duplicate_transition == duplicate_transition_raise_error\n True\n\n TESTS::\n\n sage: T = Transducer()\n sage: type(T.empty_copy())\n <class 'sage.combinat.finite_state_machine.Transducer'>\n sage: type(T.empty_copy(new_class=Automaton))\n <class 'sage.combinat.finite_state_machine.Automaton'>\n "
if (new_class is None):
new = self.__class__()
else:
new = new_class()
new._copy_from_other_(self, memo=memo, empty=True)
return new
def __deepcopy__(self, memo):
"\n Return a deep copy of the finite state machine.\n\n INPUT:\n\n - ``memo`` -- a dictionary storing already processed elements.\n\n OUTPUT:\n\n A new finite state machine.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)])\n sage: deepcopy(F)\n Finite state machine with 1 state\n "
new = self.__class__()
new._copy_from_other_(self)
return new
def deepcopy(self, memo=None):
"\n Return a deep copy of the finite state machine.\n\n INPUT:\n\n - ``memo`` -- (default: ``None``) a dictionary storing already\n processed elements.\n\n OUTPUT:\n\n A new finite state machine.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)])\n sage: deepcopy(F)\n Finite state machine with 1 state\n\n TESTS:\n\n Make sure that the links between transitions and states\n are still intact::\n\n sage: C = deepcopy(F)\n sage: C.transitions()[0].from_state is C.state('A')\n True\n sage: C.transitions()[0].to_state is C.state('A')\n True\n "
return deepcopy(self, memo)
def _copy_from_other_(self, other, memo=None, empty=False):
'\n Copy all data from other to self, to be used in the constructor.\n\n INPUT:\n\n - ``other`` -- a :class:`FiniteStateMachine`.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: A = Automaton([(0, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: B = Automaton()\n sage: B._copy_from_other_(A)\n sage: A == B\n True\n '
if (memo is None):
memo = {}
self.input_alphabet = deepcopy(other.input_alphabet, memo)
self.output_alphabet = deepcopy(other.output_alphabet, memo)
self.on_duplicate_transition = other.on_duplicate_transition
if (not empty):
relabel = hasattr(other, '_deepcopy_relabel_')
relabel_iter = itertools.count(0)
for state in other.iter_states():
if relabel:
if (other._deepcopy_labels_ is None):
state._deepcopy_relabel_ = next(relabel_iter)
elif callable(other._deepcopy_labels_):
state._deepcopy_relabel_ = other._deepcopy_labels_(state.label())
elif hasattr(other._deepcopy_labels_, '__getitem__'):
state._deepcopy_relabel_ = other._deepcopy_labels_[state.label()]
else:
raise TypeError('labels must be None, a callable or a dictionary.')
s = deepcopy(state, memo)
if relabel:
del state._deepcopy_relabel_
self.add_state(s)
for transition in other.iter_transitions():
self.add_transition(deepcopy(transition, memo))
def __getstate__(self):
'\n Return state for pickling excluding outgoing transitions.\n\n OUTPUT:\n\n A dictionary.\n\n Outgoing transitions are in fact stored in states,\n but must be pickled by the finite state machine\n in order to avoid deep recursion.\n\n TESTS::\n\n sage: A = Automaton([(0, 1, 0)])\n sage: loads(dumps(A)) == A\n True\n '
odict = self.__dict__.copy()
odict.update({'transitions': self.transitions()})
return odict
def __setstate__(self, d):
'\n Set state from pickling.\n\n INPUT:\n\n - `d` -- a dictionary\n\n OUTPUT:\n\n None.\n\n As transitions are in fact stored in states but not saved\n by states in order to avoid deep recursion, transitions\n have to be manually restored here.\n\n TESTS::\n\n sage: A = Automaton([(0, 1, 0)])\n sage: loads(dumps(A)) == A\n True\n '
transitions = d.pop('transitions')
self.__dict__.update(d)
for state in self.iter_states():
state.transitions = []
for transition in transitions:
self.add_transition(transition)
def relabeled(self, memo=None, labels=None):
"\n Return a deep copy of the finite state machine, but the\n states are relabeled.\n\n INPUT:\n\n - ``memo`` -- (default: ``None``) a dictionary storing already\n processed elements.\n\n - ``labels`` -- (default: ``None``) a dictionary or callable\n mapping old labels to new labels. If ``None``, then the new\n labels are integers starting with 0.\n\n OUTPUT:\n\n A new finite state machine.\n\n EXAMPLES::\n\n sage: FSM1 = FiniteStateMachine([('A', 'B'), ('B', 'C'), ('C', 'A')])\n sage: FSM1.states()\n ['A', 'B', 'C']\n sage: FSM2 = FSM1.relabeled()\n sage: FSM2.states()\n [0, 1, 2]\n sage: FSM3 = FSM1.relabeled(labels={'A': 'a', 'B': 'b', 'C': 'c'})\n sage: FSM3.states()\n ['a', 'b', 'c']\n sage: FSM4 = FSM2.relabeled(labels=lambda x: 2*x)\n sage: FSM4.states()\n [0, 2, 4]\n\n TESTS::\n\n sage: FSM2.relabeled(labels=1)\n Traceback (most recent call last):\n ...\n TypeError: labels must be None, a callable or a dictionary.\n "
self._deepcopy_relabel_ = True
self._deepcopy_labels_ = labels
new = deepcopy(self, memo)
del self._deepcopy_relabel_
del self._deepcopy_labels_
return new
def induced_sub_finite_state_machine(self, states):
'\n Return a sub-finite-state-machine of the finite state machine\n induced by the given states.\n\n INPUT:\n\n - ``states`` -- a list (or an iterator) of states (either labels or\n instances of :class:`FSMState`) of the sub-finite-state-machine.\n\n OUTPUT:\n\n A new finite state machine. It consists (of deep copies) of\n the given states and (deep copies) of all transitions of ``self``\n between these states.\n\n EXAMPLES::\n\n sage: FSM = FiniteStateMachine([(0, 1, 0), (0, 2, 0),\n ....: (1, 2, 0), (2, 0, 0)])\n sage: sub_FSM = FSM.induced_sub_finite_state_machine([0, 1])\n sage: sub_FSM.states()\n [0, 1]\n sage: sub_FSM.transitions()\n [Transition from 0 to 1: 0|-]\n sage: FSM.induced_sub_finite_state_machine([3])\n Traceback (most recent call last):\n ...\n ValueError: 3 is not a state of this finite state machine.\n\n TESTS:\n\n Make sure that the links between transitions and states\n are still intact::\n\n sage: sub_FSM.transitions()[0].from_state is sub_FSM.state(0)\n True\n '
good_states = set()
for state in states:
if (not self.has_state(state)):
raise ValueError(('%s is not a state of this finite state machine.' % state))
good_states.add(self.state(state))
memo = {}
new = self.empty_copy(memo=memo)
for state in good_states:
s = deepcopy(state, memo)
new.add_state(s)
for state in good_states:
for transition in self.iter_transitions(state):
if (transition.to_state in good_states):
new.add_transition(deepcopy(transition, memo))
return new
def __hash__(self):
'\n Since finite state machines are mutable, they should not be\n hashable, so we return a type error.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n The hash of this finite state machine.\n\n EXAMPLES::\n\n sage: hash(FiniteStateMachine())\n Traceback (most recent call last):\n ...\n TypeError: Finite state machines are mutable, and thus not hashable.\n '
if getattr(self, '_immutable', False):
return hash((tuple(self.states()), tuple(self.transitions())))
raise TypeError('Finite state machines are mutable, and thus not hashable.')
def __or__(self, other):
"\n Return the disjoint union of this and another finite state machine.\n\n INPUT:\n\n - ``other`` -- a finite state machine.\n\n OUTPUT:\n\n A new finite state machine.\n\n .. SEEALSO::\n\n :meth:`.disjoint_union`, :meth:`.__and__`,\n :meth:`Automaton.intersection`,\n :meth:`Transducer.intersection`.\n\n TESTS::\n\n sage: FiniteStateMachine() | FiniteStateMachine([('A', 'B')])\n Finite state machine with 2 states\n sage: FiniteStateMachine() | 42\n Traceback (most recent call last):\n ...\n TypeError: Can only add finite state machine\n "
if is_FiniteStateMachine(other):
return self.disjoint_union(other)
else:
raise TypeError('Can only add finite state machine')
__add__ = __or__
def __iadd__(self, other):
'\n TESTS::\n\n sage: F = FiniteStateMachine()\n sage: F += FiniteStateMachine()\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
def __and__(self, other):
"\n Return the intersection of ``self`` with ``other``.\n\n TESTS::\n\n sage: FiniteStateMachine() & FiniteStateMachine([('A', 'B')])\n Traceback (most recent call last):\n ...\n NotImplementedError\n "
if is_FiniteStateMachine(other):
return self.intersection(other)
def __imul__(self, other):
'\n TESTS::\n\n sage: F = FiniteStateMachine()\n sage: F *= FiniteStateMachine()\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
def __call__(self, *args, **kwargs):
"\n Call either method :meth:`.composition` or :meth:`.process`\n (with ``full_output=False``). If the input is not finite\n (``is_finite`` of input is ``False``), then\n :meth:`.iter_process` (with ``iterator_type='simple'``) is\n called. Moreover, the flag ``automatic_output_type`` is set\n (unless ``format_output`` is specified).\n See the documentation of these functions for possible\n parameters.\n\n EXAMPLES:\n\n The following code performs a :meth:`composition`::\n\n sage: F = Transducer([('A', 'B', 1, 0), ('B', 'B', 1, 1),\n ....: ('B', 'B', 0, 0)],\n ....: initial_states=['A'], final_states=['B'])\n sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),\n ....: (2, 2, 0, 1), (2, 1, 1, 1)],\n ....: initial_states=[1], final_states=[1])\n sage: H = G(F)\n sage: H.states()\n [('A', 1), ('B', 1), ('B', 2)]\n\n An automaton or transducer can also act on an input (a list\n or other iterable of letters)::\n\n sage: binary_inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: binary_inverter([0, 1, 0, 0, 1, 1])\n [1, 0, 1, 1, 0, 0]\n\n We can also let them act on :doc:`words <words/words>`::\n\n sage: # needs sage.combinat\n sage: W = Words([0, 1]); W\n Finite and infinite words over {0, 1}\n sage: binary_inverter(W([0, 1, 1, 0, 1, 1]))\n word: 100100\n\n Infinite words work as well::\n\n sage: # needs sage.combinat\n sage: words.FibonacciWord()\n word: 0100101001001010010100100101001001010010...\n sage: binary_inverter(words.FibonacciWord())\n word: 1011010110110101101011011010110110101101...\n\n When only one successful path is found in a non-deterministic\n transducer, the result of that path is returned.\n\n ::\n\n sage: T = Transducer([(0, 1, 0, 1), (0, 2, 0, 2)],\n ....: initial_states=[0], final_states=[1])\n sage: T.process([0])\n [(False, 2, [2]), (True, 1, [1])]\n sage: T([0])\n [1]\n\n .. SEEALSO::\n\n :meth:`.composition`,\n :meth:`~FiniteStateMachine.process`,\n :meth:`~FiniteStateMachine.iter_process`,\n :meth:`Automaton.process`,\n :meth:`Transducer.process`.\n\n TESTS::\n\n sage: F = FiniteStateMachine([(0, 1, 1, 'a'), (0, 2, 2, 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: A = Automaton([(0, 1, 1), (0, 2, 2)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: T = Transducer([(0, 1, 1, 'a'), (0, 2, 2, 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: F([1])\n (True, 1, ['a'])\n sage: A([1])\n True\n sage: T([1])\n ['a']\n sage: F([2])\n (False, 2, ['b'])\n sage: A([2])\n False\n sage: T([2])\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: F([3])\n (False, None, None)\n sage: A([3])\n False\n sage: T([3])\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n\n ::\n\n sage: F = FiniteStateMachine([(11, 11, 1, 'a'), (11, 12, 2, 'b'),\n ....: (11, 13, 3, 'c'), (11, 14, 4, 'd'),\n ....: (12, 13, 3, 'e'), (12, 13, 3, 'f'),\n ....: (12, 14, 4, 'g'), (12, 14, 4, 'h'),\n ....: (12, 13, 2, 'i'), (12, 14, 2, 'j')],\n ....: initial_states=[11],\n ....: final_states=[13])\n sage: def f(o):\n ....: return ''.join(o)\n sage: F([0], format_output=f)\n (False, None, None)\n sage: F([3], format_output=f)\n (True, 13, 'c')\n sage: F([4], format_output=f)\n (False, 14, 'd')\n sage: F([2, 2], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Got more than one output, but only allowed to show\n one. Change list_of_outputs option.\n sage: F([2, 2], format_output=f, list_of_outputs=True)\n [(False, 14, 'bj'), (True, 13, 'bi')]\n sage: F([2, 3], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Got more than one output, but only allowed to show\n one. Change list_of_outputs option.\n sage: F([2, 3], format_output=f, list_of_outputs=True)\n [(True, 13, 'be'), (True, 13, 'bf')]\n sage: F([2, 4], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Got more than one output, but only allowed to show\n one. Change list_of_outputs option.\n sage: F([2, 4], format_output=f, list_of_outputs=True)\n [(False, 14, 'bg'), (False, 14, 'bh')]\n\n ::\n\n sage: A = Automaton([(11, 11, 1), (11, 12, 2),\n ....: (11, 13, 3), (11, 14, 4),\n ....: (12, 13, 3), (12, 14, 4),\n ....: (12, 32, 3), (12, 42, 4),\n ....: (12, 13, 2), (12, 14, 2)],\n ....: initial_states=[11],\n ....: final_states=[13, 32])\n sage: def f(o):\n ....: return ''.join(o)\n sage: A([0], format_output=f)\n False\n sage: A([3], format_output=f)\n True\n sage: A([4], format_output=f)\n False\n sage: A([2, 2], format_output=f)\n True\n sage: A([2, 2], format_output=f, list_of_outputs=True)\n [False, True]\n sage: A([2, 3], format_output=f)\n True\n sage: A([2, 3], format_output=f, list_of_outputs=True)\n [True, True]\n sage: A([2, 4], format_output=f)\n False\n sage: A([2, 4], format_output=f, list_of_outputs=True)\n [False, False]\n\n ::\n\n sage: T = Transducer([(11, 11, 1, 'a'), (11, 12, 2, 'b'),\n ....: (11, 13, 3, 'c'), (11, 14, 4, 'd'),\n ....: (12, 13, 3, 'e'), (12, 13, 3, 'f'),\n ....: (12, 14, 4, 'g'), (12, 14, 4, 'h'),\n ....: (12, 13, 2, 'i'), (12, 14, 2, 'j')],\n ....: initial_states=[11],\n ....: final_states=[13])\n sage: def f(o):\n ....: return ''.join(o)\n sage: T([0], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T([3], format_output=f)\n 'c'\n sage: T([4], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T([2, 2], format_output=f)\n 'bi'\n sage: T([2, 2], format_output=f, list_of_outputs=True)\n [None, 'bi']\n sage: T([2, 2], format_output=f,\n ....: list_of_outputs=True, only_accepted=True)\n ['bi']\n sage: T.process([2, 2], format_output=f, list_of_outputs=True)\n [(False, 14, 'bj'), (True, 13, 'bi')]\n sage: T([2, 3], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Found more than one accepting path.\n sage: T([2, 3], format_output=f, list_of_outputs=True)\n ['be', 'bf']\n sage: T([2, 4], format_output=f)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T([2, 4], format_output=f, list_of_outputs=True)\n [None, None]\n\n ::\n\n sage: from itertools import islice\n sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: inverter(words.FibonacciWord()) # needs sage.combinat\n word: 1011010110110101101011011010110110101101...\n sage: inverter(words.FibonacciWord(), automatic_output_type=True) # needs sage.combinat\n word: 1011010110110101101011011010110110101101...\n sage: tuple(islice(inverter(words.FibonacciWord(), # needs sage.combinat\n ....: automatic_output_type=False), 10r))\n (1, 0, 1, 1, 0, 1, 0, 1, 1, 0)\n sage: type(inverter((1, 0, 1, 1, 0, 1, 0, 1, 1, 0),\n ....: automatic_output_type=False))\n <class 'list'>\n sage: type(inverter((1, 0, 1, 1, 0, 1, 0, 1, 1, 0),\n ....: automatic_output_type=True))\n <class 'tuple'>\n "
if (not args):
raise TypeError('Called with too few arguments.')
if is_FiniteStateMachine(args[0]):
return self.composition(*args, **kwargs)
if isinstance(args[0], Iterable):
if ('full_output' not in kwargs):
kwargs['full_output'] = False
if ('list_of_outputs' not in kwargs):
kwargs['list_of_outputs'] = False
if ('automatic_output_type' not in kwargs):
kwargs['automatic_output_type'] = ('format_output' not in kwargs)
input_tape = args[0]
if (hasattr(input_tape, 'is_finite') and (not input_tape.is_finite())):
if ('iterator_type' not in kwargs):
kwargs['iterator_type'] = 'simple'
return self.iter_process(*args, **kwargs)
return self.process(*args, **kwargs)
raise TypeError('Do not know what to do with that arguments.')
def __bool__(self):
'\n Return True if the finite state machine consists of at least\n one state.\n\n OUTPUT:\n\n True or False.\n\n TESTS::\n\n sage: bool(FiniteStateMachine())\n False\n '
return bool(self._states_)
def __eq__(self, other):
"\n Return ``True`` if the two finite state machines are equal,\n i.e., if they have the same states and the same transitions.\n\n INPUT:\n\n - ``self`` -- a finite state machine.\n\n - ``other`` -- a finite state machine.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n Note that this function compares all attributes of a state (by\n using :meth:`FSMState.fully_equal`) except for colors. Colors\n are handled as follows: If the colors coincide, then the\n finite state machines are also considered equal. If not, then\n they are considered as equal if both finite state machines are\n monochromatic.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 1)])\n sage: F == FiniteStateMachine()\n False\n sage: G = FiniteStateMachine([('A', 'B', 1)],\n ....: initial_states=['A'])\n sage: F == G\n False\n sage: F.state('A').is_initial = True\n sage: F == G\n True\n\n This shows the behavior when the states have colors::\n\n sage: F.state('A').color = 'red'\n sage: G.state('A').color = 'red'\n sage: F == G\n True\n sage: G.state('A').color = 'blue'\n sage: F == G\n False\n sage: F.state('B').color = 'red'\n sage: F.is_monochromatic()\n True\n sage: G.state('B').color = 'blue'\n sage: G.is_monochromatic()\n True\n sage: F == G\n True\n "
if (not is_FiniteStateMachine(other)):
return False
if (len(self._states_) != len(other._states_)):
return False
colors_equal = True
for state in self.iter_states():
try:
other_state = other.state(state.label())
except LookupError:
return False
if (not state.fully_equal(other_state, compare_color=False)):
return False
if (state.color != other_state.color):
colors_equal = False
self_transitions = state.transitions
other_transitions = other.state(state).transitions
if (len(self_transitions) != len(other_transitions)):
return False
for t in self_transitions:
if (t not in other_transitions):
return False
if colors_equal:
return True
return (self.is_monochromatic() and other.is_monochromatic())
def __ne__(self, other):
"\n Tests for inequality, complement of :meth:`.__eq__`.\n\n INPUT:\n\n - ``self`` -- a finite state machine.\n\n - ``other`` -- a finite state machine.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: E = FiniteStateMachine([('A', 'B', 0)])\n sage: F = Automaton([('A', 'B', 0)])\n sage: G = Transducer([('A', 'B', 0, 1)])\n sage: E == F\n True\n sage: E == G\n False\n "
return (not (self == other))
def __contains__(self, item):
"\n Return ``True``, if the finite state machine contains the\n state or transition item.\n\n Note that only the labels of the\n states and the input and output words are tested.\n\n INPUT:\n\n - ``item`` -- a state or a transition.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n sage: F = FiniteStateMachine([('A', 'B', 0), ('B', 'A', 1)])\n sage: FSMState('A', is_initial=True) in F\n True\n sage: 'A' in F\n False\n sage: FSMTransition('A', 'B', 0) in F\n True\n "
if is_FSMState(item):
return self.has_state(item)
if is_FSMTransition(item):
return self.has_transition(item)
return False
def is_Markov_chain(self, is_zero=None):
"\n Checks whether ``self`` is a Markov chain where the transition\n probabilities are modeled as input labels.\n\n INPUT:\n\n - ``is_zero`` -- by default (``is_zero=None``), checking for\n zero is simply done by\n :meth:`~sage.structure.element.Element.is_zero`. This\n parameter can be used to provide a more sophisticated check\n for zero, e.g. in the case of symbolic probabilities, see\n the examples below.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n :attr:`on_duplicate_transition` must be\n :func:`duplicate_transition_add_input`, the sum of the input weights\n of the transitions leaving a state must add up to 1 and the sum of\n initial probabilities must add up to 1 (or all be ``None``).\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],\n ....: [1, 0, 1/2, 0], [1, 1, 1/2, 1]],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: F.is_Markov_chain()\n True\n\n :attr:`on_duplicate_transition` must be\n :func:`duplicate_transition_add_input`::\n\n sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],\n ....: [1, 0, 1/2, 0], [1, 1, 1/2, 1]])\n sage: F.is_Markov_chain()\n False\n\n Sum of input labels of the transitions leaving states must be 1::\n\n sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],\n ....: [1, 0, 1/2, 0]],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: F.is_Markov_chain()\n False\n\n The initial probabilities of all states must be ``None`` or they must\n sum up to 1. The initial probabilities of all states have to be set in the latter case::\n\n sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1],\n ....: [1, 0, 1, 0]],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: F.is_Markov_chain()\n True\n sage: F.state(0).initial_probability = 1/4\n sage: F.is_Markov_chain()\n False\n sage: F.state(1).initial_probability = 7\n sage: F.is_Markov_chain()\n False\n sage: F.state(1).initial_probability = 3/4\n sage: F.is_Markov_chain()\n True\n\n If the probabilities are variables in the symbolic ring,\n :func:`~sage.symbolic.assumptions.assume` will do the trick::\n\n sage: # needs sage.symbolic\n sage: var('p q')\n (p, q)\n sage: F = Transducer([(0, 0, p, 1), (0, 0, q, 0)],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: assume(p + q == 1)\n sage: (p + q - 1).is_zero()\n True\n sage: F.is_Markov_chain()\n True\n sage: forget()\n sage: del(p, q)\n\n If the probabilities are variables in some polynomial ring,\n the parameter ``is_zero`` can be used::\n\n sage: R.<p, q> = PolynomialRing(QQ)\n sage: def is_zero_polynomial(polynomial):\n ....: return polynomial in (p + q - 1)*R\n sage: F = Transducer([(0, 0, p, 1), (0, 0, q, 0)],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: F.state(0).initial_probability = p + q\n sage: F.is_Markov_chain()\n False\n sage: F.is_Markov_chain(is_zero_polynomial) # needs sage.libs.singular\n True\n "
def default_is_zero(expression):
return expression.is_zero()
is_zero_function = default_is_zero
if (is_zero is not None):
is_zero_function = is_zero
if (self.on_duplicate_transition != duplicate_transition_add_input):
return False
if (any(((s.initial_probability is not None) for s in self.iter_states())) and any(((s.initial_probability is None) for s in self.iter_states()))):
return False
if (any(((s.initial_probability is not None) for s in self.iter_states())) and (not is_zero_function((sum((s.initial_probability for s in self.iter_states())) - 1)))):
return False
return all((is_zero_function((sum((t.word_in[0] for t in state.transitions)) - 1)) for state in self.iter_states()))
def _repr_(self):
'\n Represents the finite state machine as "Finite state machine\n with n states" where n is the number of states.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: FiniteStateMachine()._repr_()\n \'Empty finite state machine\'\n\n TESTS::\n\n sage: F = FiniteStateMachine()\n sage: F\n Empty finite state machine\n sage: F.add_state(42)\n 42\n sage: F\n Finite state machine with 1 state\n sage: F.add_state(43)\n 43\n sage: F\n Finite state machine with 2 states\n\n '
if (not self._states_):
return 'Empty finite state machine'
if (len(self._states_) == 1):
return 'Finite state machine with 1 state'
else:
return ('Finite state machine with %s states' % len(self._states_))
default_format_letter = latex
format_letter = default_format_letter
def format_letter_negative(self, letter):
"\n Format negative numbers as overlined numbers, everything\n else by standard LaTeX formatting.\n\n INPUT:\n\n ``letter`` -- anything.\n\n OUTPUT:\n\n Overlined absolute value if letter is a negative integer,\n :func:`latex(letter) <sage.misc.latex.latex>` otherwise.\n\n EXAMPLES::\n\n sage: A = Automaton([(0, 0, -1)])\n sage: list(map(A.format_letter_negative, [-1, 0, 1, 'a', None]))\n ['\\\\overline{1}', 0, 1, \\text{\\texttt{a}}, \\mathrm{None}]\n sage: A.latex_options(format_letter=A.format_letter_negative)\n sage: print(latex(A))\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$0$};\n \\path[->] (v0) edge[loop above] node {$\\overline{1}$} ();\n \\end{tikzpicture}\n "
if ((letter in ZZ) and (letter < 0)):
return ('\\overline{%d}' % (- letter))
else:
return latex(letter)
def format_transition_label_reversed(self, word):
"\n Format words in transition labels in reversed order.\n\n INPUT:\n\n ``word`` -- list of letters.\n\n OUTPUT:\n\n String representation of ``word`` suitable to be typeset in\n mathematical mode, letters are written in reversed order.\n\n This is the reversed version of\n :meth:`.default_format_transition_label`.\n\n In digit expansions, digits are frequently processed from the\n least significant to the most significant position, but it is\n customary to write the least significant digit at the\n right-most position. Therefore, the labels have to be\n reversed.\n\n EXAMPLES::\n\n sage: T = Transducer([(0, 0, 0, [1, 2, 3])])\n sage: T.format_transition_label_reversed([1, 2, 3])\n '3 2 1'\n sage: T.latex_options(format_transition_label=T.format_transition_label_reversed)\n sage: print(latex(T))\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$0$};\n \\path[->] (v0) edge[loop above] node {$0\\mid 3 2 1$} ();\n \\end{tikzpicture}\n\n TESTS:\n\n Check that :trac:`16357` is fixed::\n\n sage: T = Transducer()\n sage: T.format_transition_label_reversed([])\n '\\\\varepsilon'\n "
return self.default_format_transition_label(reversed(word))
def default_format_transition_label(self, word):
'\n Default formatting of words in transition labels for LaTeX output.\n\n INPUT:\n\n ``word`` -- list of letters\n\n OUTPUT:\n\n String representation of ``word`` suitable to be typeset in\n mathematical mode.\n\n - For a non-empty word: Concatenation of the letters, piped through\n ``self.format_letter`` and separated by blanks.\n - For an empty word:\n ``sage.combinat.finite_state_machine.EmptyWordLaTeX``.\n\n There is also a variant :meth:`.format_transition_label_reversed`\n writing the words in reversed order.\n\n EXAMPLES:\n\n #. Example of a non-empty word::\n\n sage: T = Transducer()\n sage: print(T.default_format_transition_label(\n ....: [\'a\', \'alpha\', \'a_1\', \'0\', 0, (0, 1)]))\n \\text{\\texttt{a}} \\text{\\texttt{alpha}}\n \\text{\\texttt{a{\\char`\\_}1}} 0 0 \\left(0, 1\\right)\n\n #. In the example above, ``\'a\'`` and ``\'alpha\'`` should perhaps\n be symbols::\n\n sage: var(\'a alpha a_1\') # needs sage.symbolic\n (a, alpha, a_1)\n sage: print(T.default_format_transition_label([a, alpha, a_1])) # needs sage.symbolic\n a \\alpha a_{1}\n\n #. Example of an empty word::\n\n sage: print(T.default_format_transition_label([]))\n \\varepsilon\n\n We can change this by setting\n ``sage.combinat.finite_state_machine.EmptyWordLaTeX``::\n\n sage: sage.combinat.finite_state_machine.EmptyWordLaTeX = \'\'\n sage: T.default_format_transition_label([])\n \'\'\n\n Finally, we restore the default value::\n\n sage: sage.combinat.finite_state_machine.EmptyWordLaTeX = r\'\\varepsilon\'\n\n #. This method is the default value for\n ``FiniteStateMachine.format_transition_label``. That can be changed to be\n any other function::\n\n sage: A = Automaton([(0, 1, 0)])\n sage: def custom_format_transition_label(word):\n ....: return "t"\n sage: A.latex_options(format_transition_label=custom_format_transition_label)\n sage: print(latex(A))\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$0$};\n \\node[state] (v1) at (-3.000000, 0.000000) {$1$};\n \\path[->] (v0) edge node[rotate=360.00, anchor=south] {$t$} (v1);\n \\end{tikzpicture}\n\n TESTS:\n\n Check that :trac:`16357` is fixed::\n\n sage: T = Transducer()\n sage: T.default_format_transition_label([])\n \'\\\\varepsilon\'\n sage: T.default_format_transition_label(iter([]))\n \'\\\\varepsilon\'\n '
result = ' '.join((self.format_letter(u) for u in word))
if result:
return result
else:
return EmptyWordLaTeX
format_transition_label = default_format_transition_label
def latex_options(self, coordinates=None, format_state_label=None, format_letter=None, format_transition_label=None, loop_where=None, initial_where=None, accepting_style=None, accepting_distance=None, accepting_where=None, accepting_show_empty=None):
'\n Set options for LaTeX output via\n :func:`~sage.misc.latex.latex` and therefore\n :func:`~sage.misc.latex.view`.\n\n INPUT:\n\n - ``coordinates`` -- a dictionary or a function mapping labels\n of states to pairs interpreted as coordinates. If no\n coordinates are given, states a placed equidistantly on a\n circle of radius `3`. See also :meth:`.set_coordinates`.\n\n - ``format_state_label`` -- a function mapping labels of\n states to a string suitable for typesetting in LaTeX\'s\n mathematics mode. If not given, :func:`~sage.misc.latex.latex`\n is used.\n\n - ``format_letter`` -- a function mapping letters of the input\n and output alphabets to a string suitable for typesetting in\n LaTeX\'s mathematics mode. If not given,\n :meth:`.default_format_transition_label` uses\n :func:`~sage.misc.latex.latex`.\n\n - ``format_transition_label`` -- a function mapping words over\n the input and output alphabets to a string suitable for\n typesetting in LaTeX\'s mathematics mode. If not given,\n :meth:`.default_format_transition_label` is used.\n\n - ``loop_where`` -- a dictionary or a function mapping labels of\n initial states to one of ``\'above\'``, ``\'left\'``, ``\'below\'``,\n ``\'right\'``. If not given, ``\'above\'`` is used.\n\n - ``initial_where`` -- a dictionary or a function mapping\n labels of initial states to one of ``\'above\'``, ``\'left\'``,\n ``\'below\'``, ``\'right\'``. If not given, TikZ\' default\n (currently ``\'left\'``) is used.\n\n - ``accepting_style`` -- one of ``\'accepting by double\'`` and\n ``\'accepting by arrow\'``. If not given, ``\'accepting by\n double\'`` is used unless there are non-empty final output\n words.\n\n - ``accepting_distance`` -- a string giving a LaTeX length\n used for the length of the arrow leading from a final state.\n If not given, TikZ\' default (currently ``\'3ex\'``) is used\n unless there are non-empty final output words, in which case\n ``\'7ex\'`` is used.\n\n - ``accepting_where`` -- a dictionary or a function mapping\n labels of final states to one of ``\'above\'``, ``\'left\'``,\n ``\'below\'``, ``\'right\'``. If not given, TikZ\' default\n (currently ``\'right\'``) is used. If the final state has a\n final output word, it is also possible to give an angle\n in degrees.\n\n - ``accepting_show_empty`` -- if ``True`` the arrow of an\n empty final output word is labeled as well. Note that this\n implicitly implies ``accepting_style=\'accepting by\n arrow\'``. If not given, the default ``False`` is used.\n\n OUTPUT:\n\n Nothing.\n\n As TikZ (cf. the :wikipedia:`PGF/TikZ`) is used to typeset\n the graphics, the syntax is oriented on TikZ\' syntax.\n\n This is a convenience function collecting all options for\n LaTeX output. All of its functionality can also be achieved by\n directly setting the attributes\n\n - ``coordinates``, ``format_label``, ``loop_where``,\n ``initial_where``, and ``accepting_where`` of\n :class:`FSMState` (here, ``format_label`` is a callable\n without arguments, everything else is a specific value);\n\n - ``format_label`` of :class:`FSMTransition` (``format_label``\n is a callable without arguments);\n\n - ``format_state_label``, ``format_letter``,\n ``format_transition_label``, ``accepting_style``,\n ``accepting_distance``, and ``accepting_show_empty``\n of :class:`FiniteStateMachine`.\n\n This function, however, also (somewhat) checks its input and\n serves to collect documentation on all these options.\n\n The function can be called several times, only those arguments\n which are not ``None`` are taken into account. By the same\n means, it can be combined with directly setting some\n attributes as outlined above.\n\n EXAMPLES:\n\n See also the section on :ref:`finite_state_machine_LaTeX_output`\n in the introductory examples of this module.\n\n ::\n\n sage: T = Transducer(initial_states=[4],\n ....: final_states=[0, 3])\n sage: for j in srange(4):\n ....: T.add_transition(4, j, 0, [0, j])\n ....: T.add_transition(j, 4, 0, [0, -j])\n ....: T.add_transition(j, j, 0, 0)\n Transition from 4 to 0: 0|0,0\n Transition from 0 to 4: 0|0,0\n Transition from 0 to 0: 0|0\n Transition from 4 to 1: 0|0,1\n Transition from 1 to 4: 0|0,-1\n Transition from 1 to 1: 0|0\n Transition from 4 to 2: 0|0,2\n Transition from 2 to 4: 0|0,-2\n Transition from 2 to 2: 0|0\n Transition from 4 to 3: 0|0,3\n Transition from 3 to 4: 0|0,-3\n Transition from 3 to 3: 0|0\n sage: T.add_transition(4, 4, 0, 0)\n Transition from 4 to 4: 0|0\n sage: T.state(3).final_word_out = [0, 0]\n sage: T.latex_options(\n ....: coordinates={4: (0, 0),\n ....: 0: (-6, 3),\n ....: 1: (-2, 3),\n ....: 2: (2, 3),\n ....: 3: (6, 3)},\n ....: format_state_label=lambda x: r\'\\mathbf{%s}\' % x,\n ....: format_letter=lambda x: r\'w_{%s}\' % x,\n ....: format_transition_label=lambda x:\n ....: r"{\\scriptstyle %s}" % T.default_format_transition_label(x),\n ....: loop_where={4: \'below\', 0: \'left\', 1: \'above\',\n ....: 2: \'right\', 3:\'below\'},\n ....: initial_where=lambda x: \'above\',\n ....: accepting_style=\'accepting by double\',\n ....: accepting_distance=\'10ex\',\n ....: accepting_where={0: \'left\', 3: 45}\n ....: )\n sage: T.state(4).format_label=lambda: r\'\\mathcal{I}\'\n sage: latex(T)\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state, initial, initial where=above] (v0) at (0.000000, 0.000000) {$\\mathcal{I}$};\n \\node[state, accepting, accepting where=left] (v1) at (-6.000000, 3.000000) {$\\mathbf{0}$};\n \\node[state, accepting, accepting where=45] (v2) at (6.000000, 3.000000) {$\\mathbf{3}$};\n \\path[->] (v2.45.00) edge node[rotate=45.00, anchor=south] {$\\$ \\mid {\\scriptstyle w_{0} w_{0}}$} ++(45.00:10ex);\n \\node[state] (v3) at (-2.000000, 3.000000) {$\\mathbf{1}$};\n \\node[state] (v4) at (2.000000, 3.000000) {$\\mathbf{2}$};\n \\path[->] (v1) edge[loop left] node[rotate=90, anchor=south] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0}}$} ();\n \\path[->] (v1.-21.57) edge node[rotate=-26.57, anchor=south] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{0}}$} (v0.148.43);\n \\path[->] (v3) edge[loop above] node {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0}}$} ();\n \\path[->] (v3.-51.31) edge node[rotate=-56.31, anchor=south] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{-1}}$} (v0.118.69);\n \\path[->] (v4) edge[loop right] node[rotate=90, anchor=north] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0}}$} ();\n \\path[->] (v4.-118.69) edge node[rotate=56.31, anchor=north] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{-2}}$} (v0.51.31);\n \\path[->] (v2) edge[loop below] node {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0}}$} ();\n \\path[->] (v2.-148.43) edge node[rotate=26.57, anchor=north] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{-3}}$} (v0.21.57);\n \\path[->] (v0.158.43) edge node[rotate=333.43, anchor=north] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{0}}$} (v1.328.43);\n \\path[->] (v0.128.69) edge node[rotate=303.69, anchor=north] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{1}}$} (v3.298.69);\n \\path[->] (v0.61.31) edge node[rotate=56.31, anchor=south] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{2}}$} (v4.231.31);\n \\path[->] (v0.31.57) edge node[rotate=26.57, anchor=south] {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0} w_{3}}$} (v2.201.57);\n \\path[->] (v0) edge[loop below] node {${\\scriptstyle w_{0}}\\mid {\\scriptstyle w_{0}}$} ();\n \\end{tikzpicture}\n sage: view(T) # not tested\n\n To actually see this, use the live documentation in the Sage notebook\n and execute the cells.\n\n By changing some of the options, we get the following output::\n\n sage: T.latex_options(\n ....: format_transition_label=T.default_format_transition_label,\n ....: accepting_style=\'accepting by arrow\',\n ....: accepting_show_empty=True\n ....: )\n sage: latex(T)\n \\begin{tikzpicture}[auto, initial text=, >=latex, accepting text=, accepting/.style=accepting by arrow, accepting distance=10ex]\n \\node[state, initial, initial where=above] (v0) at (0.000000, 0.000000) {$\\mathcal{I}$};\n \\node[state] (v1) at (-6.000000, 3.000000) {$\\mathbf{0}$};\n \\path[->] (v1.180.00) edge node[rotate=360.00, anchor=south] {$\\$ \\mid \\varepsilon$} ++(180.00:10ex);\n \\node[state] (v2) at (6.000000, 3.000000) {$\\mathbf{3}$};\n \\path[->] (v2.45.00) edge node[rotate=45.00, anchor=south] {$\\$ \\mid w_{0} w_{0}$} ++(45.00:10ex);\n \\node[state] (v3) at (-2.000000, 3.000000) {$\\mathbf{1}$};\n \\node[state] (v4) at (2.000000, 3.000000) {$\\mathbf{2}$};\n \\path[->] (v1) edge[loop left] node[rotate=90, anchor=south] {$w_{0}\\mid w_{0}$} ();\n \\path[->] (v1.-21.57) edge node[rotate=-26.57, anchor=south] {$w_{0}\\mid w_{0} w_{0}$} (v0.148.43);\n \\path[->] (v3) edge[loop above] node {$w_{0}\\mid w_{0}$} ();\n \\path[->] (v3.-51.31) edge node[rotate=-56.31, anchor=south] {$w_{0}\\mid w_{0} w_{-1}$} (v0.118.69);\n \\path[->] (v4) edge[loop right] node[rotate=90, anchor=north] {$w_{0}\\mid w_{0}$} ();\n \\path[->] (v4.-118.69) edge node[rotate=56.31, anchor=north] {$w_{0}\\mid w_{0} w_{-2}$} (v0.51.31);\n \\path[->] (v2) edge[loop below] node {$w_{0}\\mid w_{0}$} ();\n \\path[->] (v2.-148.43) edge node[rotate=26.57, anchor=north] {$w_{0}\\mid w_{0} w_{-3}$} (v0.21.57);\n \\path[->] (v0.158.43) edge node[rotate=333.43, anchor=north] {$w_{0}\\mid w_{0} w_{0}$} (v1.328.43);\n \\path[->] (v0.128.69) edge node[rotate=303.69, anchor=north] {$w_{0}\\mid w_{0} w_{1}$} (v3.298.69);\n \\path[->] (v0.61.31) edge node[rotate=56.31, anchor=south] {$w_{0}\\mid w_{0} w_{2}$} (v4.231.31);\n \\path[->] (v0.31.57) edge node[rotate=26.57, anchor=south] {$w_{0}\\mid w_{0} w_{3}$} (v2.201.57);\n \\path[->] (v0) edge[loop below] node {$w_{0}\\mid w_{0}$} ();\n \\end{tikzpicture}\n sage: view(T) # not tested\n\n TESTS::\n\n sage: T.latex_options(format_state_label=\'Nothing\')\n Traceback (most recent call last):\n ...\n TypeError: format_state_label must be callable.\n sage: T.latex_options(format_letter=\'\')\n Traceback (most recent call last):\n ...\n TypeError: format_letter must be callable.\n sage: T.latex_options(format_transition_label=\'\')\n Traceback (most recent call last):\n ...\n TypeError: format_transition_label must be callable.\n sage: T.latex_options(loop_where=37)\n Traceback (most recent call last):\n ...\n TypeError: loop_where must be a callable or a\n dictionary.\n sage: T.latex_options(loop_where=lambda x: \'top\')\n Traceback (most recent call last):\n ...\n ValueError: loop_where for 4 must be in [\'above\',\n \'below\', \'left\', \'right\'].\n sage: T.latex_options(initial_where=90)\n Traceback (most recent call last):\n ...\n TypeError: initial_where must be a callable or a\n dictionary.\n sage: T.latex_options(initial_where=lambda x: \'top\')\n Traceback (most recent call last):\n ...\n ValueError: initial_where for 4 must be in [\'above\',\n \'below\', \'left\', \'right\'].\n sage: T.latex_options(accepting_style=\'fancy\')\n Traceback (most recent call last):\n ...\n ValueError: accepting_style must be in [\'accepting by\n arrow\', \'accepting by double\'].\n sage: T.latex_options(accepting_where=90)\n Traceback (most recent call last):\n ...\n TypeError: accepting_where must be a callable or a\n dictionary.\n sage: T.latex_options(accepting_where=lambda x: \'top\')\n Traceback (most recent call last):\n ...\n ValueError: accepting_where for 0 must be in [\'above\',\n \'below\', \'left\', \'right\'].\n sage: T.latex_options(accepting_where={0: \'above\', 3: \'top\'})\n Traceback (most recent call last):\n ...\n ValueError: accepting_where for 3 must be a real number or\n be in [\'above\', \'below\', \'left\', \'right\'].\n '
if (coordinates is not None):
self.set_coordinates(coordinates)
if (format_state_label is not None):
if (not callable(format_state_label)):
raise TypeError('format_state_label must be callable.')
self.format_state_label = format_state_label
if (format_letter is not None):
if (not callable(format_letter)):
raise TypeError('format_letter must be callable.')
self.format_letter = format_letter
if (format_transition_label is not None):
if (not callable(format_transition_label)):
raise TypeError('format_transition_label must be callable.')
self.format_transition_label = format_transition_label
if (loop_where is not None):
permissible = list(tikz_automata_where)
for state in self.states():
if callable(loop_where):
where = loop_where(state.label())
else:
try:
where = loop_where[state.label()]
except TypeError:
raise TypeError('loop_where must be a callable or a dictionary.')
except KeyError:
continue
if (where in permissible):
state.loop_where = where
else:
raise ValueError(('loop_where for %s must be in %s.' % (state.label(), sorted(permissible))))
if (initial_where is not None):
permissible = list(tikz_automata_where)
for state in self.iter_initial_states():
if callable(initial_where):
where = initial_where(state.label())
else:
try:
where = initial_where[state.label()]
except TypeError:
raise TypeError('initial_where must be a callable or a dictionary.')
except KeyError:
continue
if (where in permissible):
state.initial_where = where
else:
raise ValueError(('initial_where for %s must be in %s.' % (state.label(), sorted(permissible))))
if (accepting_style is not None):
permissible = ['accepting by double', 'accepting by arrow']
if (accepting_style in permissible):
self.accepting_style = accepting_style
else:
raise ValueError(('accepting_style must be in %s.' % sorted(permissible)))
if (accepting_distance is not None):
self.accepting_distance = accepting_distance
if (accepting_where is not None):
permissible = list(tikz_automata_where)
for state in self.iter_final_states():
if callable(accepting_where):
where = accepting_where(state.label())
else:
try:
where = accepting_where[state.label()]
except TypeError:
raise TypeError('accepting_where must be a callable or a dictionary.')
except KeyError:
continue
if (where in permissible):
state.accepting_where = where
elif (hasattr(state, 'final_word_out') and state.final_word_out):
if (where in RR):
state.accepting_where = where
else:
raise ValueError(('accepting_where for %s must be a real number or be in %s.' % (state.label(), sorted(permissible))))
else:
raise ValueError(('accepting_where for %s must be in %s.' % (state.label(), sorted(permissible))))
if (accepting_show_empty is not None):
self.accepting_show_empty = accepting_show_empty
def _latex_(self):
"\n Return a LaTeX code for the graph of the finite state machine.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 1, 2)],\n ....: initial_states=['A'],\n ....: final_states=['B'])\n sage: F.state('A').initial_where='below'\n sage: print(latex(F)) # indirect doctest\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state, initial, initial where=below] (v0) at (3.000000, 0.000000) {$\\text{\\texttt{A}}$};\n \\node[state, accepting] (v1) at (-3.000000, 0.000000) {$\\text{\\texttt{B}}$};\n \\path[->] (v0) edge node[rotate=360.00, anchor=south] {$ $} (v1);\n \\end{tikzpicture}\n\n TESTS:\n\n Check that :trac:`16943` is fixed::\n\n sage: latex(Transducer(\n ....: [(0, 1), (1, 1), (2, 2), (3, 3), (4, 4)]))\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$0$};\n \\node[state] (v1) at (0.927051, 2.853170) {$1$};\n \\node[state] (v2) at (-2.427051, 1.763356) {$2$};\n \\node[state] (v3) at (-2.427051, -1.763356) {$3$};\n \\node[state] (v4) at (0.927051, -2.853170) {$4$};\n \\path[->] (v0) edge node[rotate=306.00, anchor=south] {$\\varepsilon\\mid \\varepsilon$} (v1);\n \\path[->] (v1) edge[loop above] node {$\\varepsilon\\mid \\varepsilon$} ();\n \\path[->] (v2) edge[loop above] node {$\\varepsilon\\mid \\varepsilon$} ();\n \\path[->] (v3) edge[loop above] node {$\\varepsilon\\mid \\varepsilon$} ();\n \\path[->] (v4) edge[loop above] node {$\\varepsilon\\mid \\varepsilon$} ();\n \\end{tikzpicture}\n "
from math import sin, cos, pi, atan2
def label_rotation(angle, both_directions):
'\n Given an angle of a transition, compute the TikZ string to\n rotate the label.\n '
angle_label = angle
anchor_label = 'south'
if ((angle > 90) or (angle <= (- 90))):
angle_label = (angle + 180)
if both_directions:
anchor_label = 'north'
if hasattr(angle_label, 'n'):
angle_label = angle_label.n()
return ('rotate=%.2f, anchor=%s' % (angle_label, anchor_label))
setup_latex_preamble()
options = ['auto', 'initial text=', '>=latex']
nonempty_final_word_out = False
for state in self.iter_final_states():
if state.final_word_out:
nonempty_final_word_out = True
break
if hasattr(self, 'accepting_style'):
accepting_style = self.accepting_style
elif nonempty_final_word_out:
accepting_style = 'accepting by arrow'
else:
accepting_style = 'accepting by double'
if (accepting_style == 'accepting by arrow'):
options.append('accepting text=')
options.append(('accepting/.style=%s' % accepting_style))
if hasattr(self, 'accepting_distance'):
accepting_distance = self.accepting_distance
elif nonempty_final_word_out:
accepting_distance = '7ex'
else:
accepting_distance = None
if ((accepting_style == 'accepting by arrow') and accepting_distance):
options.append(('accepting distance=%s' % accepting_distance))
if hasattr(self, 'accepting_show_empty'):
accepting_show_empty = self.accepting_show_empty
else:
accepting_show_empty = False
result = ('\\begin{tikzpicture}[%s]\n' % ', '.join(options))
j = 0
for vertex in self.iter_states():
if (not hasattr(vertex, 'coordinates')):
vertex.coordinates = ((3 * cos((((2 * pi) * j) / len(self.states())))), (3 * sin((((2 * pi) * j) / len(self.states())))))
options = ''
if vertex.is_final:
if ((not (vertex.final_word_out and (accepting_style == 'accepting by arrow'))) and (not accepting_show_empty)):
options += ', accepting'
if hasattr(vertex, 'accepting_where'):
options += (', accepting where=%s' % (vertex.accepting_where,))
if vertex.is_initial:
options += ', initial'
if hasattr(vertex, 'initial_where'):
options += (', initial where=%s' % vertex.initial_where)
if hasattr(vertex, 'format_label'):
label = vertex.format_label()
elif hasattr(self, 'format_state_label'):
label = self.format_state_label(vertex)
else:
label = latex(vertex.label())
result += ('\\node[state%s] (v%d) at (%f, %f) {$%s$};\n' % (options, j, vertex.coordinates[0], vertex.coordinates[1], label))
vertex._number_ = j
if (vertex.is_final and (vertex.final_word_out or accepting_show_empty)):
angle = 0
if hasattr(vertex, 'accepting_where'):
angle = tikz_automata_where.get(vertex.accepting_where, vertex.accepting_where)
result += ('\\path[->] (v%d.%.2f) edge node[%s] {$%s \\mid %s$} ++(%.2f:%s);\n' % (j, angle, label_rotation(angle, False), EndOfWordLaTeX, self.format_transition_label(vertex.final_word_out), angle, accepting_distance))
j += 1
def key_function(s):
return (s.from_state, s.to_state)
adjacent = OrderedDict(((pair, list(transitions)) for (pair, transitions) in itertools.groupby(sorted(self.iter_transitions(), key=key_function), key=key_function)))
for ((source, target), transitions) in adjacent.items():
if transitions:
labels = []
for transition in transitions:
if hasattr(transition, 'format_label'):
labels.append(transition.format_label())
else:
labels.append(self._latex_transition_label_(transition, self.format_transition_label))
label = ', '.join(labels)
if (source != target):
angle = ((atan2((target.coordinates[1] - source.coordinates[1]), (target.coordinates[0] - source.coordinates[0])) * 180) / pi)
both_directions = ((target, source) in adjacent)
if both_directions:
angle_source = ('.%.2f' % (angle + 5))
angle_target = ('.%.2f' % (angle + 175))
else:
angle_source = ''
angle_target = ''
result += ('\\path[->] (v%d%s) edge node[%s] {$%s$} (v%d%s);\n' % (source._number_, angle_source, label_rotation(angle, both_directions), label, target._number_, angle_target))
else:
loop_where = 'above'
if hasattr(source, 'loop_where'):
loop_where = source.loop_where
rotation = {'left': '[rotate=90, anchor=south]', 'right': '[rotate=90, anchor=north]'}
result += ('\\path[->] (v%d) edge[loop %s] node%s {$%s$} ();\n' % (source._number_, loop_where, rotation.get(loop_where, ''), label))
result += '\\end{tikzpicture}'
return result
def _latex_transition_label_(self, transition, format_function=None):
"\n Return the proper transition label.\n\n INPUT:\n\n - ``transition`` -- a transition\n\n - ``format_function`` -- a function formatting the labels\n\n OUTPUT:\n\n A string.\n\n TESTS::\n\n sage: F = FiniteStateMachine([('A', 'B', 0, 1)])\n sage: t = F.transitions()[0]\n sage: F._latex_transition_label_(t)\n ' '\n "
return ' '
def set_coordinates(self, coordinates, default=True):
'\n Set coordinates of the states for the LaTeX representation by\n a dictionary or a function mapping labels to coordinates.\n\n INPUT:\n\n - ``coordinates`` -- a dictionary or a function mapping labels\n of states to pairs interpreted as coordinates.\n\n - ``default`` -- If ``True``, then states not given by\n ``coordinates`` get a default position on a circle of\n radius 3.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]])\n sage: F.set_coordinates({0: (0, 0), 1: (2, 0), 2: (1, 1)})\n sage: F.state(0).coordinates\n (0, 0)\n\n We can also use a function to determine the coordinates::\n\n sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]])\n sage: F.set_coordinates(lambda l: (l, 3/(l+1)))\n sage: F.state(2).coordinates\n (2, 1)\n '
from math import sin, cos, pi
states_without_coordinates = []
for state in self.iter_states():
try:
state.coordinates = coordinates[state.label()]
continue
except (KeyError, TypeError):
pass
try:
state.coordinates = coordinates(state.label())
continue
except TypeError:
pass
states_without_coordinates.append(state)
if default:
n = len(states_without_coordinates)
for (j, state) in enumerate(states_without_coordinates):
state.coordinates = ((3 * cos((((2 * pi) * j) / n))), (3 * sin((((2 * pi) * j) / n))))
def _matrix_(self, R=None):
"\n Return the adjacency matrix of the finite state machine.\n\n See :meth:`.adjacency_matrix` for more information.\n\n EXAMPLES::\n\n sage: B = FiniteStateMachine({0: {0: (0, 0), 'a': (1, 0)},\n ....: 'a': {2: (0, 0), 3: (1, 0)},\n ....: 2:{0:(1, 1), 4:(0, 0)},\n ....: 3:{'a':(0, 1), 2:(1, 1)},\n ....: 4:{4:(1, 1), 3:(0, 1)}},\n ....: initial_states=[0])\n sage: B._matrix_() # needs sage.symbolic\n [1 1 0 0 0]\n [0 0 1 1 0]\n [x 0 0 0 1]\n [0 x x 0 0]\n [0 0 0 x x]\n "
return self.adjacency_matrix()
def adjacency_matrix(self, input=None, entry=None):
"\n Return the adjacency matrix of the underlying graph.\n\n INPUT:\n\n - ``input`` -- Only transitions with input label ``input`` are\n respected.\n\n - ``entry`` -- The function ``entry`` takes a transition and the\n return value is written in the matrix as the entry\n ``(transition.from_state, transition.to_state)``. The default\n value (``None``) of entry takes the variable ``x`` to the\n power of the sum of the output word of the transition.\n\n OUTPUT:\n\n A matrix.\n\n If any label of a state is not an integer, the finite state\n machine is relabeled at the beginning. If there are more than\n one transitions between two states, then the different return\n values of ``entry`` are added up.\n\n EXAMPLES::\n\n sage: B = FiniteStateMachine({0:{0:(0, 0), 'a':(1, 0)},\n ....: 'a':{2:(0, 0), 3:(1, 0)},\n ....: 2:{0:(1, 1), 4:(0, 0)},\n ....: 3:{'a':(0, 1), 2:(1, 1)},\n ....: 4:{4:(1, 1), 3:(0, 1)}},\n ....: initial_states=[0])\n sage: B.adjacency_matrix() # needs sage.symbolic\n [1 1 0 0 0]\n [0 0 1 1 0]\n [x 0 0 0 1]\n [0 x x 0 0]\n [0 0 0 x x]\n\n This is equivalent to::\n\n sage: matrix(B) # needs sage.symbolic\n [1 1 0 0 0]\n [0 0 1 1 0]\n [x 0 0 0 1]\n [0 x x 0 0]\n [0 0 0 x x]\n\n It is also possible to use other entries in the adjacency matrix::\n\n sage: B.adjacency_matrix(entry=(lambda transition: 1))\n [1 1 0 0 0]\n [0 0 1 1 0]\n [1 0 0 0 1]\n [0 1 1 0 0]\n [0 0 0 1 1]\n sage: var('t') # needs sage.symbolic\n t\n sage: B.adjacency_matrix(1, entry=(lambda transition: # needs sage.symbolic\n ....: exp(I*transition.word_out[0]*t)))\n [ 0 1 0 0 0]\n [ 0 0 0 1 0]\n [e^(I*t) 0 0 0 0]\n [ 0 0 e^(I*t) 0 0]\n [ 0 0 0 0 e^(I*t)]\n sage: a = Automaton([(0, 1, 0),\n ....: (1, 2, 0),\n ....: (2, 0, 1),\n ....: (2, 1, 0)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: a.adjacency_matrix() # needs sage.symbolic\n [0 1 0]\n [0 0 1]\n [1 1 0]\n\n "
if (entry is None):
from sage.symbolic.ring import SR
x = SR.var('x')
def default_function(transition):
return (x ** sum(transition.word_out))
entry = default_function
relabeledFSM = self
l = len(relabeledFSM.states())
for state in self.iter_states():
if ((state.label() not in ZZ) or (state.label() >= l) or (state.label() < 0)):
relabeledFSM = self.relabeled()
break
dictionary = {}
for transition in relabeledFSM.iter_transitions():
if ((input is None) or (transition.word_in == [input])):
if ((transition.from_state.label(), transition.to_state.label()) in dictionary):
dictionary[(transition.from_state.label(), transition.to_state.label())] += entry(transition)
else:
dictionary[(transition.from_state.label(), transition.to_state.label())] = entry(transition)
return matrix(len(relabeledFSM.states()), dictionary)
def determine_input_alphabet(self, reset=True):
'\n Determine the input alphabet according to the transitions\n of this finite state machine.\n\n INPUT:\n\n - ``reset`` -- a boolean (default: ``True``). If ``True``, then\n the existing input alphabet is erased, otherwise new letters are\n appended to the existing alphabet.\n\n OUTPUT:\n\n Nothing.\n\n After this operation the input alphabet of this finite state machine\n is a list of letters.\n\n .. TODO::\n\n At the moment, the letters of the alphabet need to be hashable.\n\n EXAMPLES::\n\n sage: T = Transducer([(1, 1, 1, 0), (1, 2, 2, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: final_states=[1],\n ....: determine_alphabets=False)\n sage: (T.input_alphabet, T.output_alphabet)\n (None, None)\n sage: T.determine_input_alphabet()\n sage: (T.input_alphabet, T.output_alphabet)\n ([0, 1, 2], None)\n\n .. SEEALSO::\n\n :meth:`determine_output_alphabet`,\n :meth:`determine_alphabets`.\n '
if reset:
ain = set()
else:
ain = set(self.input_alphabet)
for t in self.iter_transitions():
for letter in t.word_in:
ain.add(letter)
self.input_alphabet = list(ain)
def determine_output_alphabet(self, reset=True):
'\n Determine the output alphabet according to the transitions\n of this finite state machine.\n\n INPUT:\n\n - ``reset`` -- a boolean (default: ``True``). If ``True``, then\n the existing output alphabet is erased, otherwise new letters are\n appended to the existing alphabet.\n\n OUTPUT:\n\n Nothing.\n\n After this operation the output alphabet of this finite state machine\n is a list of letters.\n\n .. TODO::\n\n At the moment, the letters of the alphabet need to be hashable.\n\n EXAMPLES::\n\n sage: T = Transducer([(1, 1, 1, 0), (1, 2, 2, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: final_states=[1],\n ....: determine_alphabets=False)\n sage: T.state(1).final_word_out = [1, 4]\n sage: (T.input_alphabet, T.output_alphabet)\n (None, None)\n sage: T.determine_output_alphabet()\n sage: (T.input_alphabet, T.output_alphabet)\n (None, [0, 1, 4])\n\n .. SEEALSO::\n\n :meth:`determine_input_alphabet`,\n :meth:`determine_alphabets`.\n '
if reset:
aout = set()
else:
aout = set(self.output_alphabet)
for t in self.iter_transitions():
for letter in t.word_out:
aout.add(letter)
for s in self.iter_final_states():
for letter in s.final_word_out:
aout.add(letter)
self.output_alphabet = list(aout)
def determine_alphabets(self, reset=True):
'\n Determine the input and output alphabet according to the\n transitions in this finite state machine.\n\n INPUT:\n\n - ``reset`` -- If reset is ``True``, then the existing input\n and output alphabets are erased, otherwise new letters are\n appended to the existing alphabets.\n\n OUTPUT:\n\n Nothing.\n\n After this operation the input alphabet and the output\n alphabet of this finite state machine are a list of letters.\n\n .. TODO::\n\n At the moment, the letters of the alphabets need to be hashable.\n\n EXAMPLES::\n\n sage: T = Transducer([(1, 1, 1, 0), (1, 2, 2, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: final_states=[1],\n ....: determine_alphabets=False)\n sage: T.state(1).final_word_out = [1, 4]\n sage: (T.input_alphabet, T.output_alphabet)\n (None, None)\n sage: T.determine_alphabets()\n sage: (T.input_alphabet, T.output_alphabet)\n ([0, 1, 2], [0, 1, 4])\n\n .. SEEALSO::\n\n :meth:`determine_input_alphabet`,\n :meth:`determine_output_alphabet`.\n '
self.determine_input_alphabet(reset)
self.determine_output_alphabet(reset)
def states(self):
"\n Return the states of the finite state machine.\n\n OUTPUT:\n\n The states of the finite state machine as list.\n\n EXAMPLES::\n\n sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])\n sage: FSM.states()\n ['1', '2']\n "
return copy(self._states_)
def iter_states(self):
"\n Return an iterator of the states.\n\n OUTPUT:\n\n An iterator of the states of the finite state machine.\n\n EXAMPLES::\n\n sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])\n sage: [s.label() for s in FSM.iter_states()]\n ['1', '2']\n "
return iter(self._states_)
def transitions(self, from_state=None):
"\n Return a list of all transitions.\n\n INPUT:\n\n - ``from_state`` -- (default: ``None``) If ``from_state`` is\n given, then a list of transitions starting there is given.\n\n OUTPUT:\n\n A list of all transitions.\n\n EXAMPLES::\n\n sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])\n sage: FSM.transitions()\n [Transition from '1' to '2': 1|-,\n Transition from '2' to '2': 0|-]\n "
return list(self.iter_transitions(from_state))
def iter_transitions(self, from_state=None):
"\n Return an iterator of all transitions.\n\n INPUT:\n\n - ``from_state`` -- (default: ``None``) If ``from_state`` is\n given, then a list of transitions starting there is given.\n\n OUTPUT:\n\n An iterator of all transitions.\n\n EXAMPLES::\n\n sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])\n sage: [(t.from_state.label(), t.to_state.label())\n ....: for t in FSM.iter_transitions('1')]\n [('1', '2')]\n sage: [(t.from_state.label(), t.to_state.label())\n ....: for t in FSM.iter_transitions('2')]\n [('2', '2')]\n sage: [(t.from_state.label(), t.to_state.label())\n ....: for t in FSM.iter_transitions()]\n [('1', '2'), ('2', '2')]\n "
if (from_state is None):
return self._iter_transitions_all_()
else:
return iter(self.state(from_state).transitions)
def _iter_transitions_all_(self):
"\n Return an iterator over all transitions.\n\n OUTPUT:\n\n An iterator over all transitions.\n\n EXAMPLES::\n\n sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)])\n sage: [(t.from_state.label(), t.to_state.label())\n ....: for t in FSM._iter_transitions_all_()]\n [('1', '2'), ('2', '2')]\n "
for state in self.iter_states():
(yield from state.transitions)
def initial_states(self):
"\n Return a list of all initial states.\n\n OUTPUT:\n\n A list of all initial states.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_initial=True)\n sage: B = FSMState('B')\n sage: F = FiniteStateMachine([(A, B, 1, 0)])\n sage: F.initial_states()\n ['A']\n "
return list(self.iter_initial_states())
def iter_initial_states(self):
"\n Return an iterator of the initial states.\n\n OUTPUT:\n\n An iterator over all initial states.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_initial=True)\n sage: B = FSMState('B')\n sage: F = FiniteStateMachine([(A, B, 1, 0)])\n sage: [s.label() for s in F.iter_initial_states()]\n ['A']\n "
return (s for s in self.iter_states() if s.is_initial)
def final_states(self):
"\n Return a list of all final states.\n\n OUTPUT:\n\n A list of all final states.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_final=True)\n sage: B = FSMState('B', is_initial=True)\n sage: C = FSMState('C', is_final=True)\n sage: F = FiniteStateMachine([(A, B), (A, C)])\n sage: F.final_states()\n ['A', 'C']\n "
return list(self.iter_final_states())
def iter_final_states(self):
"\n Return an iterator of the final states.\n\n OUTPUT:\n\n An iterator over all initial states.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_final=True)\n sage: B = FSMState('B', is_initial=True)\n sage: C = FSMState('C', is_final=True)\n sage: F = FiniteStateMachine([(A, B), (A, C)])\n sage: [s.label() for s in F.iter_final_states()]\n ['A', 'C']\n "
return (s for s in self.iter_states() if s.is_final)
def state(self, state):
"\n Return the state of the finite state machine.\n\n INPUT:\n\n - ``state`` -- If ``state`` is not an instance of\n :class:`FSMState`, then it is assumed that it is the label\n of a state.\n\n OUTPUT:\n\n The state of the finite state machine corresponding to ``state``.\n\n If no state is found, then a ``LookupError`` is thrown.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: FSM = FiniteStateMachine([(A, 'B'), ('C', A)])\n sage: FSM.state('A') == A\n True\n sage: FSM.state('xyz')\n Traceback (most recent call last):\n ...\n LookupError: No state with label xyz found.\n "
def what(s, switch):
if switch:
return s.label()
else:
return s
switch = is_FSMState(state)
try:
return self._states_dict_[what(state, switch)]
except AttributeError:
for s in self.iter_states():
if (what(s, (not switch)) == state):
return s
except KeyError:
pass
raise LookupError(('No state with label %s found.' % (what(state, switch),)))
def transition(self, transition):
"\n Return the transition of the finite state machine.\n\n INPUT:\n\n - ``transition`` -- If ``transition`` is not an instance of\n :class:`FSMTransition`, then it is assumed that it is a\n tuple ``(from_state, to_state, word_in, word_out)``.\n\n OUTPUT:\n\n The transition of the finite state machine corresponding\n to ``transition``.\n\n If no transition is found, then a ``LookupError`` is thrown.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t = FSMTransition('A', 'B', 0)\n sage: F = FiniteStateMachine([t])\n sage: F.transition(('A', 'B', 0))\n Transition from 'A' to 'B': 0|-\n sage: id(t) == id(F.transition(('A', 'B', 0)))\n True\n "
if (not is_FSMTransition(transition)):
transition = FSMTransition(*transition)
for s in self.iter_transitions(transition.from_state):
if (s == transition):
return s
raise LookupError('No transition found.')
def has_state(self, state):
"\n Return whether ``state`` is one of the states of the finite\n state machine.\n\n INPUT:\n\n - ``state`` can be a :class:`FSMState` or a label of a state.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: FiniteStateMachine().has_state('A')\n False\n "
try:
self.state(state)
return True
except LookupError:
return False
def has_transition(self, transition):
"\n Return whether ``transition`` is one of the transitions of\n the finite state machine.\n\n INPUT:\n\n - ``transition`` has to be a :class:`FSMTransition`.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t = FSMTransition('A', 'A', 0, 1)\n sage: FiniteStateMachine().has_transition(t)\n False\n sage: FiniteStateMachine().has_transition(('A', 'A', 0, 1))\n Traceback (most recent call last):\n ...\n TypeError: Transition is not an instance of FSMTransition.\n "
if is_FSMTransition(transition):
return (transition in self.iter_transitions())
raise TypeError('Transition is not an instance of FSMTransition.')
def has_initial_state(self, state):
"\n Return whether ``state`` is one of the initial states of the\n finite state machine.\n\n INPUT:\n\n - ``state`` can be a :class:`FSMState` or a label.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'A')], initial_states=['A'])\n sage: F.has_initial_state('A')\n True\n "
try:
return self.state(state).is_initial
except LookupError:
return False
def has_initial_states(self):
'\n Return whether the finite state machine has an initial state.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: FiniteStateMachine().has_initial_states()\n False\n '
return bool(self.initial_states())
def has_final_state(self, state):
"\n Return whether ``state`` is one of the final states of the\n finite state machine.\n\n INPUT:\n\n - ``state`` can be a :class:`FSMState` or a label.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: FiniteStateMachine(final_states=['A']).has_final_state('A')\n True\n "
try:
return self.state(state).is_final
except LookupError:
return False
def has_final_states(self):
'\n Return whether the finite state machine has a final state.\n\n OUTPUT:\n\n True or False.\n\n EXAMPLES::\n\n sage: FiniteStateMachine().has_final_states()\n False\n '
return bool(self.final_states())
def is_deterministic(self):
"\n Return whether the finite finite state machine is deterministic.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n A finite state machine is considered to be deterministic if\n each transition has input label of length one and for each\n pair `(q,a)` where `q` is a state and `a` is an element of the\n input alphabet, there is at most one transition from `q` with\n input label `a`. Furthermore, the finite state may not have\n more than one initial state.\n\n EXAMPLES::\n\n sage: fsm = FiniteStateMachine()\n sage: fsm.add_transition(('A', 'B', 0, []))\n Transition from 'A' to 'B': 0|-\n sage: fsm.is_deterministic()\n True\n sage: fsm.add_transition(('A', 'C', 0, []))\n Transition from 'A' to 'C': 0|-\n sage: fsm.is_deterministic()\n False\n sage: fsm.add_transition(('A', 'B', [0,1], []))\n Transition from 'A' to 'B': 0,1|-\n sage: fsm.is_deterministic()\n False\n\n Check that :trac:`18556` is fixed::\n\n sage: Automaton().is_deterministic()\n True\n sage: Automaton(initial_states=[0]).is_deterministic()\n True\n sage: Automaton(initial_states=[0, 1]).is_deterministic()\n False\n "
if (len(self.initial_states()) > 1):
return False
for state in self.iter_states():
for transition in state.transitions:
if (len(transition.word_in) != 1):
return False
transition_classes_by_word_in = full_group_by(state.transitions, key=(lambda t: t.word_in))
for (_, transition_class) in transition_classes_by_word_in:
if (len(transition_class) > 1):
return False
return True
def is_complete(self):
'\n Return whether the finite state machine is complete.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n A finite state machine is considered to be complete if\n each transition has an input label of length one and for each\n pair `(q, a)` where `q` is a state and `a` is an element of the\n input alphabet, there is exactly one transition from `q` with\n input label `a`.\n\n EXAMPLES::\n\n sage: fsm = FiniteStateMachine([(0, 0, 0, 0),\n ....: (0, 1, 1, 1),\n ....: (1, 1, 0, 0)],\n ....: determine_alphabets=False)\n sage: fsm.is_complete()\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given. Try calling determine_alphabets().\n sage: fsm.input_alphabet = [0, 1]\n sage: fsm.is_complete()\n False\n sage: fsm.add_transition((1, 1, 1, 1))\n Transition from 1 to 1: 1|1\n sage: fsm.is_complete()\n True\n sage: fsm.add_transition((0, 0, 1, 0))\n Transition from 0 to 0: 1|0\n sage: fsm.is_complete()\n False\n '
if (self.input_alphabet is None):
raise ValueError('No input alphabet is given. Try calling determine_alphabets().')
for state in self.iter_states():
for transition in state.transitions:
if (len(transition.word_in) != 1):
return False
transition_classes_by_word_in = full_group_by(state.transitions, key=(lambda t: t.word_in))
for (key, transition_class) in transition_classes_by_word_in:
if (len(transition_class) > 1):
return False
outgoing_alphabet = [key[0] for (key, transition_class) in transition_classes_by_word_in]
if (not (sorted(self.input_alphabet) == sorted(outgoing_alphabet))):
return False
return True
def is_connected(self):
'\n TESTS::\n\n sage: FiniteStateMachine().is_connected()\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
_process_default_options_ = {'full_output': True, 'list_of_outputs': None, 'only_accepted': False, 'always_include_output': False, 'automatic_output_type': False}
def process(self, *args, **kwargs):
"\n Return whether the finite state machine accepts the input, the state\n where the computation stops and which output is generated.\n\n INPUT:\n\n - ``input_tape`` -- the input tape can be a list or an\n iterable with entries from the input alphabet. If we are\n working with a multi-tape machine (see parameter\n ``use_multitape_input`` and notes below), then the tape is a\n list or tuple of tracks, each of which can be a list or an\n iterable with entries from the input alphabet.\n\n - ``initial_state`` or ``initial_states`` -- the initial\n state(s) in which the machine starts. Either specify a\n single one with ``initial_state`` or a list of them with\n ``initial_states``. If both are given, ``initial_state``\n will be appended to ``initial_states``. If neither is\n specified, the initial states of the finite state machine\n are taken.\n\n - ``list_of_outputs`` -- (default: ``None``) a boolean or\n ``None``. If ``True``, then the outputs are given in list form\n (even if we have no or only one single output). If\n ``False``, then the result is never a list (an exception is\n raised if the result cannot be returned). If\n ``list_of_outputs=None``, the method determines automatically\n what to do (e.g. if a non-deterministic machine returns more\n than one path, then the output is returned in list form).\n\n - ``only_accepted`` -- (default: ``False``) a boolean. If set,\n then the first argument in the output is guaranteed to be\n ``True`` (if the output is a list, then the first argument\n of each element will be ``True``).\n\n - ``always_include_output`` -- if set (not by default), always\n include the output. This is inconsequential for a\n :class:`FiniteStateMachine`, but can be used in derived\n classes where the output is suppressed by default,\n cf. :meth:`Automaton.process`.\n\n - ``format_output`` -- a function that translates the written\n output (which is in form of a list) to something more\n readable. By default (``None``) identity is used here.\n\n - ``check_epsilon_transitions`` -- (default: ``True``) a\n boolean. If ``False``, then epsilon transitions are not\n taken into consideration during process.\n\n - ``write_final_word_out`` -- (default: ``True``) a boolean\n specifying whether the final output words should be written\n or not.\n\n - ``use_multitape_input`` -- (default: ``False``) a\n boolean. If ``True``, then the multi-tape mode of the\n process iterator is activated. See also the notes below for\n multi-tape machines.\n\n - ``process_all_prefixes_of_input`` -- (default: ``False``) a\n boolean. If ``True``, then each prefix of the input word is\n processed (instead of processing the whole input word at\n once). Consequently, there is an output generated for each\n of these prefixes.\n\n - ``process_iterator_class`` -- (default: ``None``) a class\n inherited from :class:`FSMProcessIterator`. If ``None``,\n then :class:`FSMProcessIterator` is taken. An instance of this\n class is created and is used during the processing.\n\n - ``automatic_output_type`` -- (default: ``False``) a boolean.\n If set and the input has a parent, then the\n output will have the same parent. If the input does not have\n a parent, then the output will be of the same type as the\n input.\n\n OUTPUT:\n\n A triple (or a list of triples,\n cf. parameter ``list_of_outputs``), where\n\n - the first entry is ``True`` if the input string is accepted,\n\n - the second gives the reached state after processing the\n input tape (This is a state with label ``None`` if the input\n could not be processed, i.e., if at one point no\n transition to go on could be found.), and\n\n - the third gives a list of the output labels written during\n processing (in the case the finite state machine runs as\n transducer).\n\n Note that in the case the finite state machine is not\n deterministic, all possible paths are taken into account.\n\n This function uses an iterator which, in its simplest form, goes\n from one state to another in each step. To decide which way to\n go, it uses the input words of the outgoing transitions and\n compares them to the input tape. More precisely, in each step,\n the iterator takes an outgoing transition of the current state,\n whose input label equals the input letter of the tape. The\n output label of the transition, if present, is written on the\n output tape.\n\n If the choice of the outgoing transition is not unique (i.e.,\n we have a non-deterministic finite state machine), all\n possibilities are followed. This is done by splitting the\n process into several branches, one for each of the possible\n outgoing transitions.\n\n The process (iteration) stops if all branches are finished,\n i.e., for no branch, there is any transition whose input word\n coincides with the processed input tape. This can simply\n happen when the entire tape was read.\n\n Also see :meth:`~FiniteStateMachine.__call__` for a version of\n :meth:`.process` with shortened output.\n\n Internally this function creates and works with an instance of\n :class:`FSMProcessIterator`. This iterator can also be obtained\n with :meth:`iter_process`.\n\n If working with multi-tape finite state machines, all input\n words of transitions are words of `k`-tuples of letters.\n Moreover, the input tape has to consist of `k` tracks, i.e.,\n be a list or tuple of `k` iterators, one for each track.\n\n .. WARNING::\n\n Working with multi-tape finite state machines is still\n experimental and can lead to wrong outputs.\n\n EXAMPLES::\n\n sage: binary_inverter = FiniteStateMachine({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: binary_inverter.process([0, 1, 0, 0, 1, 1])\n (True, 'A', [1, 0, 1, 1, 0, 0])\n\n Alternatively, we can invoke this function by::\n\n sage: binary_inverter([0, 1, 0, 0, 1, 1])\n (True, 'A', [1, 0, 1, 1, 0, 0])\n\n Below we construct a finite state machine which tests if an input\n is a non-adjacent form, i.e., no two neighboring letters are\n both nonzero (see also the example on\n :ref:`non-adjacent forms <finite_state_machine_recognizing_NAFs_example>`\n in the documentation of the module\n :doc:`finite_state_machine`)::\n\n sage: NAF = FiniteStateMachine(\n ....: {'_': [('_', 0), (1, 1)], 1: [('_', 0)]},\n ....: initial_states=['_'], final_states=['_', 1])\n sage: [NAF.process(w)[0] for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],\n ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]\n [True, True, False, True, False, False]\n\n Working only with the first component (i.e., returning whether\n accepted or not) usually corresponds to using the more\n specialized class :class:`Automaton`.\n\n Non-deterministic finite state machines can be handled as well.\n\n ::\n\n sage: T = Transducer([(0, 1, 0, 0), (0, 2, 0, 0)],\n ....: initial_states=[0])\n sage: T.process([0])\n [(False, 1, [0]), (False, 2, [0])]\n\n Here is another non-deterministic finite state machine. Note\n that we use ``format_output`` (see\n :class:`FSMProcessIterator`) to convert the written outputs\n (all characters) to strings.\n\n ::\n\n sage: T = Transducer([(0, 1, [0, 0], 'a'), (0, 2, [0, 0, 1], 'b'),\n ....: (0, 1, 1, 'c'), (1, 0, [], 'd'),\n ....: (1, 1, 1, 'e')],\n ....: initial_states=[0], final_states=[0, 1])\n sage: T.process([0], format_output=lambda o: ''.join(o))\n (False, None, None)\n sage: T.process([0, 0], format_output=lambda o: ''.join(o))\n [(True, 0, 'ad'), (True, 1, 'a')]\n sage: T.process([1], format_output=lambda o: ''.join(o))\n [(True, 0, 'cd'), (True, 1, 'c')]\n sage: T.process([1, 1], format_output=lambda o: ''.join(o))\n [(True, 0, 'cdcd'), (True, 0, 'ced'),\n (True, 1, 'cdc'), (True, 1, 'ce')]\n sage: T.process([0, 0, 1], format_output=lambda o: ''.join(o))\n [(False, 2, 'b'),\n (True, 0, 'adcd'),\n (True, 0, 'aed'),\n (True, 1, 'adc'),\n (True, 1, 'ae')]\n sage: T.process([0, 0, 1], format_output=lambda o: ''.join(o),\n ....: only_accepted=True)\n [(True, 0, 'adcd'), (True, 0, 'aed'),\n (True, 1, 'adc'), (True, 1, 'ae')]\n\n A simple example of a multi-tape finite state machine is the\n following: It writes the length of the first tape many letters\n ``a`` and then the length of the second tape many letters\n ``b``::\n\n sage: M = FiniteStateMachine([(0, 0, (1, None), 'a'),\n ....: (0, 1, [], []),\n ....: (1, 1, (None, 1), 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: M.process(([1, 1], [1]), use_multitape_input=True)\n (True, 1, ['a', 'a', 'b'])\n\n .. SEEALSO::\n\n :meth:`Automaton.process`,\n :meth:`Transducer.process`,\n :meth:`~FiniteStateMachine.iter_process`,\n :meth:`~FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, [0, 0], 0), (0, 2, [0, 0, 1], 0),\n ....: (0, 1, 1, 2), (1, 0, [], 1), (1, 1, 1, 3)],\n ....: initial_states=[0], final_states=[0, 1])\n sage: T.process([0])\n (False, None, None)\n sage: T.process([0, 0])\n [(True, 0, [0, 1]), (True, 1, [0])]\n sage: T.process([1])\n [(True, 0, [2, 1]), (True, 1, [2])]\n sage: T.process([1, 1])\n [(True, 0, [2, 1, 2, 1]), (True, 0, [2, 3, 1]),\n (True, 1, [2, 1, 2]), (True, 1, [2, 3])]\n\n ::\n\n sage: F = FiniteStateMachine([(0, 0, 0, 0)],\n ....: initial_states=[0])\n sage: F.process([0], only_accepted=True)\n []\n sage: F.process([0], only_accepted=True, list_of_outputs=False)\n Traceback (most recent call last):\n ...\n ValueError: No accepting output was found but according to the\n given options, an accepting output should be returned. Change\n only_accepted and/or list_of_outputs options.\n sage: F.process([0], only_accepted=True, list_of_outputs=True)\n []\n sage: F.process([0], only_accepted=False)\n (False, 0, [0])\n sage: F.process([0], only_accepted=False, list_of_outputs=False)\n (False, 0, [0])\n sage: F.process([0], only_accepted=False, list_of_outputs=True)\n [(False, 0, [0])]\n sage: F.process([1], only_accepted=True)\n []\n sage: F.process([1], only_accepted=True, list_of_outputs=False)\n Traceback (most recent call last):\n ...\n ValueError: No accepting output was found but according to the\n given options, an accepting output should be returned. Change\n only_accepted and/or list_of_outputs options.\n sage: F.process([1], only_accepted=True, list_of_outputs=True)\n []\n sage: F.process([1], only_accepted=False)\n (False, None, None)\n sage: F.process([1], only_accepted=False, list_of_outputs=False)\n (False, None, None)\n sage: F.process([1], only_accepted=False, list_of_outputs=True)\n []\n\n ::\n\n sage: F = FiniteStateMachine([(0, 1, 1, 'a'), (0, 2, 2, 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: A = Automaton([(0, 1, 1), (0, 2, 2)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: T = Transducer([(0, 1, 1, 'a'), (0, 2, 2, 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: F.process([1])\n (True, 1, ['a'])\n sage: A.process([1])\n (True, 1)\n sage: T.process([1])\n (True, 1, ['a'])\n sage: F.process([2])\n (False, 2, ['b'])\n sage: A.process([2])\n (False, 2)\n sage: T.process([2])\n (False, 2, ['b'])\n sage: F.process([3])\n (False, None, None)\n sage: A.process([3])\n (False, None)\n sage: T.process([3])\n (False, None, None)\n "
options = copy(self._process_default_options_)
options.update(kwargs)
it = self.iter_process(*args, **options)
for _ in it:
pass
only_accepted = options['only_accepted']
it_output = [result for result in it.result() if ((not only_accepted) or result[0])]
if (((len(it_output) > 1) and (options['list_of_outputs'] is None)) or options['list_of_outputs']):
return [self._process_convert_output_(out, **options) for out in sorted(it_output)]
if (options['list_of_outputs'] is False):
if ((not it_output) and only_accepted):
raise ValueError('No accepting output was found but according to the given options, an accepting output should be returned. Change only_accepted and/or list_of_outputs options.')
elif (len(it_output) > 1):
raise ValueError('Got more than one output, but only allowed to show one. Change list_of_outputs option.')
if (not it_output):
if only_accepted:
return []
NoneState = FSMState(None, allow_label_None=True)
it_output = [(False, NoneState, None)]
return self._process_convert_output_(it_output[0], **options)
def _process_convert_output_(self, output_data, **kwargs):
"\n Helper function which converts the output of\n :meth:`FiniteStateMachine.process`. This is the identity.\n\n INPUT:\n\n - ``output_data`` -- a triple.\n\n - ``full_output`` -- a boolean.\n\n OUTPUT:\n\n The converted output.\n\n This function is overridden in :class:`Automaton` and\n :class:`Transducer`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: F = FiniteStateMachine()\n sage: F._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=False)\n (True, 'a', [1, 0, 1])\n sage: F._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=True)\n (True, 'a', [1, 0, 1])\n "
(accept_input, current_state, output) = output_data
return (accept_input, current_state, output)
def iter_process(self, input_tape=None, initial_state=None, process_iterator_class=None, iterator_type=None, automatic_output_type=False, **kwargs):
"\n This function returns an iterator for processing the input.\n See :meth:`.process` (which runs this iterator until the end)\n for more information.\n\n INPUT:\n\n - ``iterator_type`` -- If ``None`` (default), then\n an instance of :class:`FSMProcessIterator` is returned. If\n this is ``'simple'`` only an iterator over one output is\n returned (an exception is raised if this is not the case, i.e.,\n if the process has branched).\n\n See :meth:`process` for a description of the other parameters.\n\n OUTPUT:\n\n An iterator.\n\n EXAMPLES:\n\n We can use :meth:`iter_process` to deal with infinite words::\n\n sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n\n sage: # needs sage.combinat\n sage: words.FibonacciWord()\n word: 0100101001001010010100100101001001010010...\n sage: it = inverter.iter_process(\n ....: words.FibonacciWord(), iterator_type='simple')\n sage: Words([0,1])(it)\n word: 1011010110110101101011011010110110101101...\n\n This can also be done by::\n\n sage: inverter.iter_process(words.FibonacciWord(), # needs sage.combinat\n ....: iterator_type='simple',\n ....: automatic_output_type=True)\n word: 1011010110110101101011011010110110101101...\n\n or even simpler by::\n\n sage: inverter(words.FibonacciWord()) # needs sage.combinat\n word: 1011010110110101101011011010110110101101...\n\n To see what is going on, we use :meth:`iter_process` without\n arguments::\n\n sage: # needs sage.combinat\n sage: from itertools import islice\n sage: it = inverter.iter_process(words.FibonacciWord())\n sage: for current in islice(it, 4r):\n ....: print(current)\n process (1 branch)\n + at state 'A'\n +-- tape at 1, [[1]]\n process (1 branch)\n + at state 'A'\n +-- tape at 2, [[1, 0]]\n process (1 branch)\n + at state 'A'\n +-- tape at 3, [[1, 0, 1]]\n process (1 branch)\n + at state 'A'\n +-- tape at 4, [[1, 0, 1, 1]]\n\n The following show the difference between using the ``'simple'``-option\n and not using it. With this option, we have\n ::\n\n sage: it = inverter.iter_process(input_tape=[0, 1, 1],\n ....: iterator_type='simple')\n sage: for i, o in enumerate(it):\n ....: print('step %s: output %s' % (i, o))\n step 0: output 1\n step 1: output 0\n step 2: output 0\n\n So :meth:`iter_process` is a generator expression which gives\n a new output letter in each step (and not more). In many cases\n this is sufficient.\n\n Doing the same without the ``'simple'``-option does not give\n the output directly; it has to be extracted first. On the\n other hand, additional information is presented::\n\n sage: it = inverter.iter_process(input_tape=[0, 1, 1])\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 'A'\n +-- tape at 1, [[1]]\n process (1 branch)\n + at state 'A'\n +-- tape at 2, [[1, 0]]\n process (1 branch)\n + at state 'A'\n +-- tape at 3, [[1, 0, 0]]\n process (0 branches)\n sage: it.result()\n [Branch(accept=True, state='A', output=[1, 0, 0])]\n\n One can see the growing of the output (the list of lists at\n the end of each entry).\n\n Even if the transducer has transitions with empty or multiletter\n output, the simple iterator returns one new output letter in\n each step::\n\n sage: T = Transducer([(0, 0, 0, []),\n ....: (0, 0, 1, [1]),\n ....: (0, 0, 2, [2, 2])],\n ....: initial_states=[0])\n sage: it = T.iter_process(input_tape=[0, 1, 2, 0, 1, 2],\n ....: iterator_type='simple')\n sage: for i, o in enumerate(it):\n ....: print('step %s: output %s' % (i, o))\n step 0: output 1\n step 1: output 2\n step 2: output 2\n step 3: output 1\n step 4: output 2\n step 5: output 2\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.process`,\n :meth:`Automaton.process`,\n :meth:`Transducer.process`,\n :meth:`~FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n "
if (automatic_output_type and ('format_output' in kwargs)):
raise ValueError("Parameter 'automatic_output_type' set, but 'format_output' specified as well.")
if automatic_output_type:
try:
kwargs['format_output'] = input_tape.parent()
except AttributeError:
kwargs['format_output'] = type(input_tape)
if (process_iterator_class is None):
process_iterator_class = FSMProcessIterator
it = process_iterator_class(self, input_tape=input_tape, initial_state=initial_state, **kwargs)
if (iterator_type is None):
return it
elif (iterator_type == 'simple'):
simple_it = self._iter_process_simple_(it)
try:
return kwargs['format_output'](simple_it)
except KeyError:
return simple_it
else:
raise ValueError(('Iterator type %s unknown.' % (iterator_type,)))
def _iter_process_simple_(self, iterator):
"\n Converts a :class:`process iterator <FSMProcessIterator>` to a simpler\n iterator, which only outputs the written letters.\n\n INPUT:\n\n - ``iterator`` -- in instance of :class:`FSMProcessIterator`.\n\n OUTPUT:\n\n A generator.\n\n An exception is raised if the process branches.\n\n EXAMPLES::\n\n sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: it = inverter.iter_process(words.FibonacciWord()[:10]) # needs sage.combinat\n sage: it_simple = inverter._iter_process_simple_(it) # needs sage.combinat\n sage: list(it_simple) # needs sage.combinat\n [1, 0, 1, 1, 0, 1, 0, 1, 1, 0]\n\n .. SEEALSO::\n\n :meth:`iter_process`,\n :meth:`FiniteStateMachine.process`,\n :meth:`Automaton.process`,\n :meth:`Transducer.process`,\n :meth:`~FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n\n TESTS::\n\n sage: T = Transducer([(0, 0, [0, 0], 0), (0, 1, 0, 0)],\n ....: initial_states=[0], final_states=[0])\n sage: list(T.iter_process([0, 0], iterator_type='simple'))\n Traceback (most recent call last):\n ...\n RuntimeError: Process has branched (2 branches exist).\n The 'simple' iterator cannot be used here.\n sage: T = Transducer([(0, 0, 0, 0), (0, 1, 0, 0)],\n ....: initial_states=[0], final_states=[0])\n sage: list(T.iter_process([0], iterator_type='simple'))\n Traceback (most recent call last):\n ...\n RuntimeError: Process has branched (visiting 2 states in branch).\n The 'simple' iterator cannot be used here.\n sage: T = Transducer([(0, 1, 0, 1), (0, 1, 0, 2)],\n ....: initial_states=[0], final_states=[0])\n sage: list(T.iter_process([0], iterator_type='simple'))\n Traceback (most recent call last):\n ...\n RuntimeError: Process has branched. (2 different outputs in branch).\n The 'simple' iterator cannot be used here.\n "
for current in iterator:
if (not current):
return
if (len(current) > 1):
raise RuntimeError(("Process has branched (%s branches exist). The 'simple' iterator cannot be used here." % (len(current),)))
(_, states) = next(iter(current.items()))
if (len(states) > 1):
raise RuntimeError(("Process has branched (visiting %s states in branch). The 'simple' iterator cannot be used here." % (len(states),)))
(_, branch) = next(iter(states.items()))
if (len(branch.outputs) > 1):
raise RuntimeError(("Process has branched. (%s different outputs in branch). The 'simple' iterator cannot be used here." % (len(branch.outputs),)))
(yield from branch.outputs[0])
branch.outputs[0] = []
def add_state(self, state):
"\n Adds a state to the finite state machine and returns the new\n state. If the state already exists, that existing state is\n returned.\n\n INPUT:\n\n - ``state`` is either an instance of\n :class:`FSMState` or,\n otherwise, a label of a state.\n\n OUTPUT:\n\n The new or existing state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: F = FiniteStateMachine()\n sage: A = FSMState('A', is_initial=True)\n sage: F.add_state(A)\n 'A'\n "
try:
return self.state(state)
except LookupError:
pass
if is_FSMState(state):
s = state
else:
s = FSMState(state)
s.transitions = list()
self._states_.append(s)
try:
self._states_dict_[s.label()] = s
except AttributeError:
pass
return s
def add_states(self, states):
"\n Adds several states. See add_state for more information.\n\n INPUT:\n\n - ``states`` -- a list of states or iterator over states.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine()\n sage: F.add_states(['A', 'B'])\n sage: F.states()\n ['A', 'B']\n "
for state in states:
self.add_state(state)
def add_transition(self, *args, **kwargs):
"\n Adds a transition to the finite state machine and returns the\n new transition.\n\n If the transition already exists, the return value of\n ``self.on_duplicate_transition`` is returned. See the\n documentation of :class:`FiniteStateMachine`.\n\n INPUT:\n\n The following forms are all accepted:\n\n ::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n sage: A = FSMState('A')\n sage: B = FSMState('B')\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition(FSMTransition(A, B, 0, 1))\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition(A, B, 0, 1)\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition(A, B, word_in=0, word_out=1)\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition('A', 'B', {'word_in': 0, 'word_out': 1})\n Transition from 'A' to 'B': {'word_in': 0, 'word_out': 1}|-\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition(from_state=A, to_state=B,\n ....: word_in=0, word_out=1)\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition({'from_state': A, 'to_state': B,\n ....: 'word_in': 0, 'word_out': 1})\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition((A, B, 0, 1))\n Transition from 'A' to 'B': 0|1\n\n sage: FSM = FiniteStateMachine()\n sage: FSM.add_transition([A, B, 0, 1])\n Transition from 'A' to 'B': 0|1\n\n If the states ``A`` and ``B`` are not instances of\n :class:`FSMState`, then it is assumed that they are labels of\n states.\n\n OUTPUT:\n\n The new transition.\n "
if ((len(args) + len(kwargs)) == 0):
return
if ((len(args) + len(kwargs)) == 1):
if (len(args) == 1):
d = args[0]
if is_FSMTransition(d):
return self._add_fsm_transition_(d)
else:
d = next(iter(kwargs.values()))
if isinstance(d, Mapping):
args = []
kwargs = d
elif isinstance(d, Iterable):
args = d
kwargs = {}
else:
raise TypeError('Cannot decide what to do with input.')
data = dict(zip(('from_state', 'to_state', 'word_in', 'word_out', 'hook'), args))
data.update(kwargs)
data['from_state'] = self.add_state(data['from_state'])
data['to_state'] = self.add_state(data['to_state'])
return self._add_fsm_transition_(FSMTransition(**data))
def _add_fsm_transition_(self, t):
"\n Adds a transition.\n\n INPUT:\n\n - ``t`` -- an instance of :class:`FSMTransition`.\n\n OUTPUT:\n\n The new transition.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: F = FiniteStateMachine()\n sage: F._add_fsm_transition_(FSMTransition('A', 'B'))\n Transition from 'A' to 'B': -|-\n "
try:
existing_transition = self.transition(t)
except LookupError:
pass
else:
return self.on_duplicate_transition(existing_transition, t)
from_state = self.add_state(t.from_state)
self.add_state(t.to_state)
from_state.transitions.append(t)
return t
def add_from_transition_function(self, function, initial_states=None, explore_existing_states=True):
"\n Constructs a finite state machine from a transition function.\n\n INPUT:\n\n - ``function`` may return a tuple (new_state, output_word) or a\n list of such tuples.\n\n - ``initial_states`` -- If no initial states are given, the\n already existing initial states of self are taken.\n\n - If ``explore_existing_states`` is True (default), then\n already existing states in self (e.g. already given final\n states) will also be processed if they are reachable from\n the initial states.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine(initial_states=['A'],\n ....: input_alphabet=[0, 1])\n sage: def f(state, input):\n ....: return [('A', input), ('B', 1-input)]\n sage: F.add_from_transition_function(f)\n sage: F.transitions()\n [Transition from 'A' to 'A': 0|0,\n Transition from 'A' to 'B': 0|1,\n Transition from 'A' to 'A': 1|1,\n Transition from 'A' to 'B': 1|0,\n Transition from 'B' to 'A': 0|0,\n Transition from 'B' to 'B': 0|1,\n Transition from 'B' to 'A': 1|1,\n Transition from 'B' to 'B': 1|0]\n\n Initial states can also be given as a parameter::\n\n sage: F = FiniteStateMachine(input_alphabet=[0,1])\n sage: def f(state, input):\n ....: return [('A', input), ('B', 1-input)]\n sage: F.add_from_transition_function(f,initial_states=['A'])\n sage: F.initial_states()\n ['A']\n\n Already existing states in the finite state machine (the final\n states in the example below) are also explored::\n\n sage: F = FiniteStateMachine(initial_states=[0],\n ....: final_states=[1],\n ....: input_alphabet=[0])\n sage: def transition_function(state, letter):\n ....: return 1 - state, []\n sage: F.add_from_transition_function(transition_function)\n sage: F.transitions()\n [Transition from 0 to 1: 0|-,\n Transition from 1 to 0: 0|-]\n\n If ``explore_existing_states=False``, however, this behavior\n is turned off, i.e., already existing states are not\n explored::\n\n sage: F = FiniteStateMachine(initial_states=[0],\n ....: final_states=[1],\n ....: input_alphabet=[0])\n sage: def transition_function(state, letter):\n ....: return 1 - state, []\n sage: F.add_from_transition_function(transition_function,\n ....: explore_existing_states=False)\n sage: F.transitions()\n [Transition from 0 to 1: 0|-]\n\n TESTS::\n\n sage: F = FiniteStateMachine(initial_states=['A'])\n sage: def f(state, input):\n ....: return [('A', input), ('B', 1-input)]\n sage: F.add_from_transition_function(f)\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given.\n Try calling determine_alphabets().\n\n ::\n\n sage: def transition(state, where):\n ....: return (vector([0, 0]), 1)\n sage: Transducer(transition, input_alphabet=[0], initial_states=[0])\n Traceback (most recent call last):\n ...\n TypeError: mutable vectors are unhashable\n "
if (self.input_alphabet is None):
raise ValueError('No input alphabet is given. Try calling determine_alphabets().')
if (initial_states is None):
not_done = self.initial_states()
elif isinstance(initial_states, Iterable):
not_done = []
for s in initial_states:
state = self.add_state(s)
state.is_initial = True
not_done.append(state)
else:
raise TypeError('Initial states must be iterable (e.g. a list of states).')
if (not not_done):
raise ValueError('No state is initial.')
if explore_existing_states:
ignore_done = self.states()
for s in not_done:
try:
ignore_done.remove(s)
except ValueError:
pass
else:
ignore_done = []
while not_done:
s = not_done.pop(0)
for letter in self.input_alphabet:
try:
return_value = function(s.label(), letter)
except LookupError:
continue
if (not hasattr(return_value, 'pop')):
return_value = [return_value]
try:
for (st_label, word) in return_value:
pass
except TypeError:
raise ValueError(('The callback function for add_from_transition is expected to return a pair (new_state, output_label) or a list of such pairs. For the state %s and the input letter %s, it however returned %s, which is not acceptable.' % (s.label(), letter, return_value)))
for (st_label, word) in return_value:
if (not self.has_state(st_label)):
not_done.append(self.add_state(st_label))
elif ignore_done:
u = self.state(st_label)
if (u in ignore_done):
not_done.append(u)
ignore_done.remove(u)
self.add_transition(s, st_label, word_in=letter, word_out=word)
def add_transitions_from_function(self, function, labels_as_input=True):
"\n Adds one or more transitions if ``function(state, state)``\n says that there are some.\n\n INPUT:\n\n - ``function`` -- a transition function. Given two states\n ``from_state`` and ``to_state`` (or their labels if\n ``label_as_input`` is true), this function shall return a\n tuple ``(word_in, word_out)`` to add a transition from\n ``from_state`` to ``to_state`` with input and output labels\n ``word_in`` and ``word_out``, respectively. If no such\n addition is to be added, the transition function shall\n return ``None``. The transition function may also return\n a list of such tuples in order to add multiple transitions\n between the pair of states.\n\n - ``label_as_input`` -- (default: ``True``)\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine()\n sage: F.add_states(['A', 'B', 'C'])\n sage: def f(state1, state2):\n ....: if state1 == 'C':\n ....: return None\n ....: return (0, 1)\n sage: F.add_transitions_from_function(f)\n sage: len(F.transitions())\n 6\n\n Multiple transitions are also possible::\n\n sage: F = FiniteStateMachine()\n sage: F.add_states([0, 1])\n sage: def f(state1, state2):\n ....: if state1 != state2:\n ....: return [(0, 1), (1, 0)]\n ....: else:\n ....: return None\n sage: F.add_transitions_from_function(f)\n sage: F.transitions()\n [Transition from 0 to 1: 0|1,\n Transition from 0 to 1: 1|0,\n Transition from 1 to 0: 0|1,\n Transition from 1 to 0: 1|0]\n\n TESTS::\n\n sage: F = FiniteStateMachine()\n sage: F.add_state(0)\n 0\n sage: def f(state1, state2):\n ....: return 1\n sage: F.add_transitions_from_function(f)\n Traceback (most recent call last):\n ...\n ValueError: The callback function for add_transitions_from_function\n is expected to return a pair (word_in, word_out) or a list of such\n pairs. For states 0 and 0 however, it returned 1,\n which is not acceptable.\n\n "
for s_from in self.iter_states():
for s_to in self.iter_states():
try:
if labels_as_input:
return_value = function(s_from.label(), s_to.label())
else:
return_value = function(s_from, s_to)
except LookupError:
continue
if (return_value is None):
continue
if (not hasattr(return_value, 'pop')):
transitions = [return_value]
else:
transitions = return_value
for t in transitions:
if (not hasattr(t, '__getitem__')):
raise 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 %s and %s however, it returned %s, which is not acceptable.' % (s_from, s_to, return_value)))
label_in = t[0]
try:
label_out = t[1]
except LookupError:
label_out = None
self.add_transition(s_from, s_to, label_in, label_out)
def delete_transition(self, t):
"\n Deletes a transition by removing it from the list of transitions of\n the state, where the transition starts.\n\n INPUT:\n\n - ``t`` -- a transition.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 0), ('B', 'A', 1)])\n sage: F.delete_transition(('A', 'B', 0))\n sage: F.transitions()\n [Transition from 'B' to 'A': 1|-]\n "
transition = self.transition(t)
transition.from_state.transitions.remove(transition)
def delete_state(self, s):
"\n Deletes a state and all transitions coming or going to this state.\n\n INPUT:\n\n - ``s`` -- a label of a state or an :class:`FSMState`.\n\n OUTPUT:\n\n Nothing.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t1 = FSMTransition('A', 'B', 0)\n sage: t2 = FSMTransition('B', 'B', 1)\n sage: F = FiniteStateMachine([t1, t2])\n sage: F.delete_state('A')\n sage: F.transitions()\n [Transition from 'B' to 'B': 1|-]\n\n TESTS:\n\n This shows that :trac:`16024` is fixed. ::\n\n sage: F._states_\n ['B']\n sage: F._states_dict_\n {'B': 'B'}\n "
state = self.state(s)
for transition in self.transitions():
if (transition.to_state == state):
self.delete_transition(transition)
self._states_.remove(state)
try:
del self._states_dict_[state.label()]
except AttributeError:
pass
def remove_epsilon_transitions(self):
'\n TESTS::\n\n sage: FiniteStateMachine().remove_epsilon_transitions()\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
def epsilon_successors(self, state):
"\n Return the dictionary with states reachable from ``state``\n without reading anything from an input tape as keys. The\n values are lists of outputs.\n\n INPUT:\n\n - ``state`` -- the state whose epsilon successors should be\n determined.\n\n OUTPUT:\n\n A dictionary mapping states to a list of output words.\n\n The states in the output are the epsilon successors of\n ``state``. Each word of the list of output words is a word\n written when taking a path from ``state`` to the corresponding\n state.\n\n EXAMPLES::\n\n sage: T = Transducer([(0, 1, None, 'a'), (1, 2, None, 'b')])\n sage: T.epsilon_successors(0)\n {1: [['a']], 2: [['a', 'b']]}\n sage: T.epsilon_successors(1)\n {2: [['b']]}\n sage: T.epsilon_successors(2)\n {}\n\n If there is a cycle with only epsilon transitions, then this\n cycle is only processed once and there is no infinite loop::\n\n sage: S = Transducer([(0, 1, None, 'a'), (1, 0, None, 'b')])\n sage: S.epsilon_successors(0)\n {0: [['a', 'b']], 1: [['a']]}\n sage: S.epsilon_successors(1)\n {0: [['b']], 1: [['b', 'a']]}\n "
return self.state(state)._epsilon_successors_(self)
def accessible_components(self):
'\n Return a new finite state machine with the accessible states\n of self and all transitions between those states.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A finite state machine with the accessible states of self and\n all transitions between those states.\n\n A state is accessible if there is a directed path from an\n initial state to the state. If self has no initial states then\n a copy of the finite state machine self is returned.\n\n EXAMPLES::\n\n sage: F = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1)],\n ....: initial_states=[0])\n sage: F.accessible_components()\n Automaton with 2 states\n\n ::\n\n sage: F = Automaton([(0, 0, 1), (0, 0, 1), (1, 1, 0), (1, 0, 1)],\n ....: initial_states=[0])\n sage: F.accessible_components()\n Automaton with 1 state\n\n .. SEEALSO::\n :meth:`coaccessible_components`\n\n TESTS:\n\n Check whether input of length > 1 works::\n\n sage: F = Automaton([(0, 1, [0, 1]), (0, 2, 0)],\n ....: initial_states=[0])\n sage: F.accessible_components()\n Automaton with 3 states\n '
if (not self.initial_states()):
return deepcopy(self)
memo = {}
def accessible(from_state, read):
return [(deepcopy(x.to_state, memo), x.word_out) for x in self.iter_transitions(from_state) if (x.word_in[0] == read)]
new_initial_states = [deepcopy(x, memo) for x in self.initial_states()]
result = self.empty_copy()
result.add_from_transition_function(accessible, initial_states=new_initial_states)
for final_state in self.iter_final_states():
try:
new_final_state = result.state(final_state.label)
new_final_state.is_final = True
except LookupError:
pass
return result
def coaccessible_components(self):
'\n Return the sub-machine induced by the coaccessible states of this\n finite state machine.\n\n OUTPUT:\n\n A finite state machine of the same type as this finite state\n machine.\n\n EXAMPLES::\n\n sage: A = automata.ContainsWord([1, 1],\n ....: input_alphabet=[0, 1]).complement().minimization().relabeled()\n sage: A.transitions()\n [Transition from 0 to 0: 0|-,\n Transition from 0 to 0: 1|-,\n Transition from 1 to 2: 0|-,\n Transition from 1 to 0: 1|-,\n Transition from 2 to 2: 0|-,\n Transition from 2 to 1: 1|-]\n sage: A.initial_states()\n [2]\n sage: A.final_states()\n [1, 2]\n sage: C = A.coaccessible_components()\n sage: C.transitions()\n [Transition from 1 to 2: 0|-,\n Transition from 2 to 2: 0|-,\n Transition from 2 to 1: 1|-]\n\n .. SEEALSO::\n :meth:`accessible_components`,\n :meth:`induced_sub_finite_state_machine`\n '
DG = self.digraph().reverse()
coaccessible_states = DG.breadth_first_search([_.label() for _ in self.iter_final_states()])
return self.induced_sub_finite_state_machine([self.state(_) for _ in coaccessible_states])
def disjoint_union(self, other):
'\n Return the disjoint union of this and another finite state\n machine.\n\n INPUT:\n\n - ``other`` -- a :class:`FiniteStateMachine`.\n\n OUTPUT:\n\n A finite state machine of the same type as this finite state\n machine.\n\n In general, the disjoint union of two finite state machines is\n non-deterministic. In the case of a automata, the language\n accepted by the disjoint union is the union of the languages\n accepted by the constituent automata. In the case of\n transducer, for each successful path in one of the constituent\n transducers, there will be one successful path with the same input\n and output labels in the disjoint union.\n\n The labels of the states of the disjoint union are pairs ``(i,\n s)``: for each state ``s`` of this finite state machine, there\n is a state ``(0, s)`` in the disjoint union; for each state\n ``s`` of the other finite state machine, there is a state ``(1,\n s)`` in the disjoint union.\n\n The input alphabet is the union of the input alphabets (if\n possible) and ``None`` otherwise. In the latter case, try\n calling :meth:`.determine_alphabets`.\n\n The disjoint union can also be written as ``A + B`` or ``A | B``.\n\n EXAMPLES::\n\n sage: A = Automaton([(0, 1, 0), (1, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: A([0, 1, 0, 1])\n True\n sage: B = Automaton([(0, 1, 0), (1, 2, 0), (2, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: B([0, 0, 1])\n True\n sage: C = A.disjoint_union(B)\n sage: C\n Automaton with 5 states\n sage: C.transitions()\n [Transition from (0, 0) to (0, 1): 0|-,\n Transition from (0, 1) to (0, 0): 1|-,\n Transition from (1, 0) to (1, 1): 0|-,\n Transition from (1, 1) to (1, 2): 0|-,\n Transition from (1, 2) to (1, 0): 1|-]\n sage: C([0, 0, 1])\n True\n sage: C([0, 1, 0, 1])\n True\n sage: C([1])\n False\n sage: C.initial_states()\n [(0, 0), (1, 0)]\n\n Instead of ``.disjoint_union``, alternative notations are\n available::\n\n sage: C1 = A + B\n sage: C1 == C\n True\n sage: C2 = A | B\n sage: C2 == C\n True\n\n In general, the disjoint union is not deterministic.::\n\n sage: C.is_deterministic()\n False\n sage: D = C.determinisation().minimization()\n sage: D.is_equivalent(Automaton([(0, 0, 0), (0, 0, 1),\n ....: (1, 7, 0), (1, 0, 1), (2, 6, 0), (2, 0, 1),\n ....: (3, 5, 0), (3, 0, 1), (4, 0, 0), (4, 2, 1),\n ....: (5, 0, 0), (5, 3, 1), (6, 4, 0), (6, 0, 1),\n ....: (7, 4, 0), (7, 3, 1)],\n ....: initial_states=[1],\n ....: final_states=[1, 2, 3]))\n True\n\n Disjoint union of transducers::\n\n sage: T1 = Transducer([(0, 0, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T2 = Transducer([(0, 0, 0, 2)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T1([0])\n [1]\n sage: T2([0])\n [2]\n sage: T = T1.disjoint_union(T2)\n sage: T([0])\n Traceback (most recent call last):\n ...\n ValueError: Found more than one accepting path.\n sage: T.process([0])\n [(True, (0, 0), [1]), (True, (1, 0), [2])]\n\n Handling of the input alphabet (see :trac:`18989`)::\n\n sage: A = Automaton([(0, 0, 0)])\n sage: B = Automaton([(0, 0, 1)], input_alphabet=[1, 2])\n sage: C = Automaton([(0, 0, 2)], determine_alphabets=False)\n sage: D = Automaton([(0, 0, [[0, 0]])], input_alphabet=[[0, 0]])\n sage: A.input_alphabet\n [0]\n sage: B.input_alphabet\n [1, 2]\n sage: C.input_alphabet is None\n True\n sage: D.input_alphabet\n [[0, 0]]\n sage: (A + B).input_alphabet\n [0, 1, 2]\n sage: (A + C).input_alphabet is None\n True\n sage: (A + D).input_alphabet is None\n True\n\n .. SEEALSO::\n\n :meth:`Automaton.intersection`,\n :meth:`Transducer.intersection`,\n :meth:`.determine_alphabets`.\n '
result = self.empty_copy()
for s in self.iter_states():
result.add_state(s.relabeled((0, s)))
for s in other.iter_states():
result.add_state(s.relabeled((1, s)))
for t in self.iter_transitions():
result.add_transition((0, t.from_state), (0, t.to_state), t.word_in, t.word_out)
for t in other.iter_transitions():
result.add_transition((1, t.from_state), (1, t.to_state), t.word_in, t.word_out)
try:
result.input_alphabet = list((set(self.input_alphabet) | set(other.input_alphabet)))
except TypeError:
result.input_alphabet = None
return result
def concatenation(self, other):
'\n Concatenate this finite state machine with another finite\n state machine.\n\n INPUT:\n\n - ``other`` -- a :class:`FiniteStateMachine`.\n\n OUTPUT:\n\n A :class:`FiniteStateMachine` of the same type as this finite\n state machine.\n\n Assume that both finite state machines are automata. If\n `\\mathcal{L}_1` is the language accepted by this automaton and\n `\\mathcal{L}_2` is the language accepted by the other automaton,\n then the language accepted by the concatenated automaton is\n `\\{ w_1w_2 \\mid w_1\\in\\mathcal{L}_1, w_2\\in\\mathcal{L}_2\\}` where\n `w_1w_2` denotes the concatenation of the words `w_1` and `w_2`.\n\n Assume that both finite state machines are transducers and that\n this transducer maps words `w_1\\in\\mathcal{L}_1` to words\n `f_1(w_1)` and that the other transducer maps words\n `w_2\\in\\mathcal{L}_2` to words `f_2(w_2)`. Then the concatenated\n transducer maps words `w_1w_2` with `w_1\\in\\mathcal{L}_1` and\n `w_2\\in\\mathcal{L}_2` to `f_1(w_1)f_2(w_2)`. Here, `w_1w_2` and\n `f_1(w_1)f_2(w_2)` again denote concatenation of words.\n\n The input alphabet is the union of the input alphabets (if\n possible) and ``None`` otherwise. In the latter case, try\n calling :meth:`.determine_alphabets`.\n\n Instead of ``A.concatenation(B)``, the notation ``A * B`` can be\n used.\n\n EXAMPLES:\n\n Concatenation of two automata::\n\n sage: A = automata.Word([0])\n sage: B = automata.Word([1])\n sage: C = A.concatenation(B)\n sage: C.transitions()\n [Transition from (0, 0) to (0, 1): 0|-,\n Transition from (0, 1) to (1, 0): -|-,\n Transition from (1, 0) to (1, 1): 1|-]\n sage: [w\n ....: for w in ([0, 0], [0, 1], [1, 0], [1, 1])\n ....: if C(w)]\n [[0, 1]]\n sage: from sage.combinat.finite_state_machine import (\n ....: is_Automaton, is_Transducer)\n sage: is_Automaton(C)\n True\n\n Concatenation of two transducers::\n\n sage: A = Transducer([(0, 1, 0, 1), (0, 1, 1, 2)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: B = Transducer([(0, 1, 0, 1), (0, 1, 1, 0)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: C = A.concatenation(B)\n sage: C.transitions()\n [Transition from (0, 0) to (0, 1): 0|1,\n Transition from (0, 0) to (0, 1): 1|2,\n Transition from (0, 1) to (1, 0): -|-,\n Transition from (1, 0) to (1, 1): 0|1,\n Transition from (1, 0) to (1, 1): 1|0]\n sage: [(w, C(w)) for w in ([0, 0], [0, 1], [1, 0], [1, 1])]\n [([0, 0], [1, 1]),\n ([0, 1], [1, 0]),\n ([1, 0], [2, 1]),\n ([1, 1], [2, 0])]\n sage: is_Transducer(C)\n True\n\n\n Alternative notation as multiplication::\n\n sage: C == A * B\n True\n\n Final output words are taken into account::\n\n sage: A = Transducer([(0, 1, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: A.state(1).final_word_out = 2\n sage: B = Transducer([(0, 1, 0, 3)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: B.state(1).final_word_out = 4\n sage: C = A * B\n sage: C([0, 0])\n [1, 2, 3, 4]\n\n Handling of the input alphabet::\n\n sage: A = Automaton([(0, 0, 0)])\n sage: B = Automaton([(0, 0, 1)], input_alphabet=[1, 2])\n sage: C = Automaton([(0, 0, 2)], determine_alphabets=False)\n sage: D = Automaton([(0, 0, [[0, 0]])], input_alphabet=[[0, 0]])\n sage: A.input_alphabet\n [0]\n sage: B.input_alphabet\n [1, 2]\n sage: C.input_alphabet is None\n True\n sage: D.input_alphabet\n [[0, 0]]\n sage: (A * B).input_alphabet\n [0, 1, 2]\n sage: (A * C).input_alphabet is None\n True\n sage: (A * D).input_alphabet is None\n True\n\n .. SEEALSO::\n\n :meth:`~.disjoint_union`,\n :meth:`.determine_alphabets`.\n\n TESTS::\n\n sage: A = Automaton()\n sage: F = FiniteStateMachine()\n sage: A * F\n Traceback (most recent call last):\n ...\n TypeError: Cannot concatenate finite state machines of\n different types.\n sage: F * A\n Traceback (most recent call last):\n ...\n TypeError: Cannot concatenate finite state machines of\n different types.\n sage: F * 5\n Traceback (most recent call last):\n ...\n TypeError: A finite state machine can only be concatenated\n with a another finite state machine.\n '
if (not is_FiniteStateMachine(other)):
raise TypeError('A finite state machine can only be concatenated with a another finite state machine.')
if (is_Automaton(other) != is_Automaton(self)):
raise TypeError('Cannot concatenate finite state machines of different types.')
result = self.empty_copy()
first_states = {}
second_states = {}
for s in self.iter_states():
new_state = s.relabeled((0, s.label()))
new_state.final_word_out = None
new_state.is_final = False
first_states[s] = new_state
result.add_state(new_state)
for s in other.iter_states():
new_state = s.relabeled((1, s.label()))
new_state.is_initial = False
second_states[s] = new_state
result.add_state(new_state)
for t in self.iter_transitions():
result.add_transition(first_states[t.from_state], first_states[t.to_state], t.word_in, t.word_out)
for t in other.iter_transitions():
result.add_transition(second_states[t.from_state], second_states[t.to_state], t.word_in, t.word_out)
for s in self.iter_final_states():
first_state = first_states[s]
for t in other.iter_initial_states():
second_state = second_states[t]
result.add_transition(first_state, second_state, [], s.final_word_out)
try:
result.input_alphabet = list((set(self.input_alphabet) | set(other.input_alphabet)))
except TypeError:
result.input_alphabet = None
return result
__mul__ = concatenation
def kleene_star(self):
'\n Compute the Kleene closure of this finite state machine.\n\n OUTPUT:\n\n A :class:`FiniteStateMachine` of the same type as this finite\n state machine.\n\n Assume that this finite state machine is an automaton\n recognizing the language `\\mathcal{L}`. Then the Kleene star\n recognizes the language `\\mathcal{L}^*=\\{ w_1\\ldots w_n \\mid\n n\\ge 0, w_j\\in\\mathcal{L} \\text{ for all } j\\}`.\n\n Assume that this finite state machine is a transducer realizing\n a function `f` on some alphabet `\\mathcal{L}`. Then the Kleene\n star realizes a function `g` on `\\mathcal{L}^*` with\n `g(w_1\\ldots w_n)=f(w_1)\\ldots f(w_n)`.\n\n EXAMPLES:\n\n Kleene star of an automaton::\n\n sage: A = automata.Word([0, 1])\n sage: B = A.kleene_star()\n sage: B.transitions()\n [Transition from 0 to 1: 0|-,\n Transition from 2 to 0: -|-,\n Transition from 1 to 2: 1|-]\n sage: from sage.combinat.finite_state_machine import (\n ....: is_Automaton, is_Transducer)\n sage: is_Automaton(B)\n True\n sage: [w for w in ([], [0, 1], [0, 1, 0], [0, 1, 0, 1], [0, 1, 1, 1])\n ....: if B(w)]\n [[],\n [0, 1],\n [0, 1, 0, 1]]\n\n Kleene star of a transducer::\n\n sage: T = Transducer([(0, 1, 0, 1), (0, 1, 1, 0)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: S = T.kleene_star()\n sage: S.transitions()\n [Transition from 0 to 1: 0|1,\n Transition from 0 to 1: 1|0,\n Transition from 1 to 0: -|-]\n sage: is_Transducer(S)\n True\n sage: for w in ([], [0], [1], [0, 0], [0, 1]):\n ....: print("{} {}".format(w, S.process(w)))\n [] (True, 0, [])\n [0] [(True, 0, [1]), (True, 1, [1])]\n [1] [(True, 0, [0]), (True, 1, [0])]\n [0, 0] [(True, 0, [1, 1]), (True, 1, [1, 1])]\n [0, 1] [(True, 0, [1, 0]), (True, 1, [1, 0])]\n\n Final output words are taken into account::\n\n sage: T = Transducer([(0, 1, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: T.state(1).final_word_out = 2\n sage: S = T.kleene_star()\n sage: sorted(S.process([0, 0]))\n [(True, 0, [1, 2, 1, 2]), (True, 1, [1, 2, 1, 2])]\n\n Final output words may lead to undesirable situations if initial\n states and final states coincide::\n\n sage: T = Transducer(initial_states=[0], final_states=[0])\n sage: T.state(0).final_word_out = 1\n sage: T([])\n [1]\n sage: S = T.kleene_star()\n sage: S([])\n Traceback (most recent call last):\n ...\n RuntimeError: State 0 is in an epsilon cycle (no input), but\n output is written.\n '
result = deepcopy(self)
for initial in result.iter_initial_states():
for final in result.iter_final_states():
result.add_transition(final, initial, [], final.final_word_out)
for initial in result.iter_initial_states():
initial.is_final = True
return result
def intersection(self, other):
'\n TESTS::\n\n sage: FiniteStateMachine().intersection(FiniteStateMachine())\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
raise NotImplementedError
def product_FiniteStateMachine(self, other, function, new_input_alphabet=None, only_accessible_components=True, final_function=None, new_class=None):
"\n Return a new finite state machine whose states are\n `d`-tuples of states of the original finite state machines.\n\n INPUT:\n\n - ``other`` -- a finite state machine (for `d=2`) or a list\n (or iterable) of `d-1` finite state machines.\n\n - ``function`` has to accept `d` transitions from `A_j` to `B_j`\n for `j\\in\\{1, \\ldots, d\\}` and returns a pair ``(word_in, word_out)``\n which is the label of the transition `A=(A_1, \\ldots, A_d)` to `B=(B_1,\n \\ldots, B_d)`. If there is no transition from `A` to `B`,\n then ``function`` should raise a ``LookupError``.\n\n - ``new_input_alphabet`` (optional) -- the new input alphabet\n as a list.\n\n - ``only_accessible_components`` -- If ``True`` (default), then\n the result is piped through :meth:`.accessible_components`. If no\n ``new_input_alphabet`` is given, it is determined by\n :meth:`.determine_alphabets`.\n\n - ``final_function`` -- A function mapping `d` final states of\n the original finite state machines to the final output of\n the corresponding state in the new finite state machine. By\n default, the final output is the empty word if both final\n outputs of the constituent states are empty; otherwise, a\n ``ValueError`` is raised.\n\n - ``new_class`` -- Class of the new finite state machine. By\n default (``None``), the class of ``self`` is used.\n\n OUTPUT:\n\n A finite state machine whose states are `d`-tuples of states of the\n original finite state machines. A state is initial or\n final if all constituent states are initial or final,\n respectively.\n\n The labels of the transitions are defined by ``function``.\n\n The final output of a final state is determined by calling\n ``final_function`` on the constituent states.\n\n The color of a new state is the tuple of colors of the\n constituent states of ``self`` and ``other``. However,\n if all constituent states have color ``None``, then\n the state has color ``None``, too.\n\n EXAMPLES::\n\n sage: F = Automaton([('A', 'B', 1), ('A', 'A', 0), ('B', 'A', 2)],\n ....: initial_states=['A'], final_states=['B'],\n ....: determine_alphabets=True)\n sage: G = Automaton([(1, 1, 1)], initial_states=[1], final_states=[1])\n sage: def addition(transition1, transition2):\n ....: return (transition1.word_in[0] + transition2.word_in[0],\n ....: None)\n sage: H = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False)\n sage: H.transitions()\n [Transition from ('A', 1) to ('B', 1): 2|-,\n Transition from ('A', 1) to ('A', 1): 1|-,\n Transition from ('B', 1) to ('A', 1): 3|-]\n sage: [s.color for s in H.iter_states()]\n [None, None]\n sage: H1 = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False)\n sage: H1.states()[0].label()[0] is F.states()[0]\n True\n sage: H1.states()[0].label()[1] is G.states()[0]\n True\n\n ::\n\n sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)],\n ....: initial_states=[0] )\n sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)],\n ....: initial_states=[0] )\n sage: H = F.product_FiniteStateMachine(\n ....: G, lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None))\n sage: H.states()\n [(0, 0), (1, 0)]\n\n ::\n\n sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)],\n ....: initial_states=[0] )\n sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)],\n ....: initial_states=[0] )\n sage: H = F.product_FiniteStateMachine(G,\n ....: lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None),\n ....: only_accessible_components=False)\n sage: H.states()\n [(0, 0), (1, 0), (0, 1), (1, 1)]\n\n Also final output words are considered according to the function\n ``final_function``::\n\n sage: F = Transducer([(0, 1, 0, 1), (1, 1, 1, 1), (1, 1, 0, 1)],\n ....: final_states=[1])\n sage: F.state(1).final_word_out = 1\n sage: G = Transducer([(0, 0, 0, 1), (0, 0, 1, 0)], final_states=[0])\n sage: G.state(0).final_word_out = 1\n sage: def minus(t1, t2):\n ....: return (t1.word_in[0] - t2.word_in[0],\n ....: t1.word_out[0] - t2.word_out[0])\n sage: H = F.product_FiniteStateMachine(G, minus)\n Traceback (most recent call last):\n ...\n ValueError: A final function must be given.\n sage: def plus(s1, s2):\n ....: return s1.final_word_out[0] + s2.final_word_out[0]\n sage: H = F.product_FiniteStateMachine(G, minus,\n ....: final_function=plus)\n sage: H.final_states()\n [(1, 0)]\n sage: H.final_states()[0].final_word_out\n [2]\n\n Products of more than two finite state machines are also possible::\n\n sage: def plus(s1, s2, s3):\n ....: if s1.word_in == s2.word_in == s3.word_in:\n ....: return (s1.word_in,\n ....: sum(s.word_out[0] for s in (s1, s2, s3)))\n ....: else:\n ....: raise LookupError\n sage: T0 = transducers.CountSubblockOccurrences([0, 0], [0, 1, 2])\n sage: T1 = transducers.CountSubblockOccurrences([1, 1], [0, 1, 2])\n sage: T2 = transducers.CountSubblockOccurrences([2, 2], [0, 1, 2])\n sage: T = T0.product_FiniteStateMachine([T1, T2], plus)\n sage: T.transitions()\n [Transition from ((), (), ()) to ((0,), (), ()): 0|0,\n Transition from ((), (), ()) to ((), (1,), ()): 1|0,\n Transition from ((), (), ()) to ((), (), (2,)): 2|0,\n Transition from ((0,), (), ()) to ((0,), (), ()): 0|1,\n Transition from ((0,), (), ()) to ((), (1,), ()): 1|0,\n Transition from ((0,), (), ()) to ((), (), (2,)): 2|0,\n Transition from ((), (1,), ()) to ((0,), (), ()): 0|0,\n Transition from ((), (1,), ()) to ((), (1,), ()): 1|1,\n Transition from ((), (1,), ()) to ((), (), (2,)): 2|0,\n Transition from ((), (), (2,)) to ((0,), (), ()): 0|0,\n Transition from ((), (), (2,)) to ((), (1,), ()): 1|0,\n Transition from ((), (), (2,)) to ((), (), (2,)): 2|1]\n sage: T([0, 0, 1, 1, 2, 2, 0, 1, 2, 2])\n [0, 1, 0, 1, 0, 1, 0, 0, 0, 1]\n\n ``other`` can also be an iterable::\n\n sage: T == T0.product_FiniteStateMachine(iter([T1, T2]), plus)\n True\n\n TESTS:\n\n Check that colors are correctly dealt with. In particular, the\n new colors have to be hashable such that\n :meth:`Automaton.determinisation` does not fail::\n\n sage: A = Automaton([[0, 0, 0]], initial_states=[0])\n sage: B = A.product_FiniteStateMachine(A,\n ....: lambda t1, t2: (0, None))\n sage: B.states()[0].color is None\n True\n sage: B.determinisation()\n Automaton with 1 state\n\n Check handling of the parameter ``other``::\n\n sage: A.product_FiniteStateMachine(None, plus)\n Traceback (most recent call last):\n ...\n ValueError: other must be a finite state machine or a list\n of finite state machines.\n sage: A.product_FiniteStateMachine([None], plus)\n Traceback (most recent call last):\n ...\n ValueError: other must be a finite state machine or a list\n of finite state machines.\n\n Test whether ``new_class`` works::\n\n sage: T = Transducer()\n sage: type(T.product_FiniteStateMachine(T, None))\n <class 'sage.combinat.finite_state_machine.Transducer'>\n sage: type(T.product_FiniteStateMachine(T, None,\n ....: new_class=Automaton))\n <class 'sage.combinat.finite_state_machine.Automaton'>\n\n Check that isolated vertices are kept (:trac:`16762`)::\n\n sage: F = Transducer(initial_states=[0])\n sage: F.add_state(1)\n 1\n sage: G = Transducer(initial_states=['A'])\n sage: F.product_FiniteStateMachine(G, None).states()\n [(0, 'A')]\n sage: F.product_FiniteStateMachine(\n ....: G, None, only_accessible_components=False).states()\n [(0, 'A'), (1, 'A')]\n "
def default_final_function(*args):
if any((s.final_word_out for s in args)):
raise ValueError('A final function must be given.')
return []
if (final_function is None):
final_function = default_final_function
result = self.empty_copy(new_class=new_class)
if (new_input_alphabet is not None):
result.input_alphabet = new_input_alphabet
else:
result.input_alphabet = None
if isinstance(other, Iterable):
machines = [self]
machines.extend(other)
if (not all((is_FiniteStateMachine(m) for m in machines))):
raise ValueError('other must be a finite state machine or a list of finite state machines.')
elif is_FiniteStateMachine(other):
machines = [self, other]
else:
raise ValueError('other must be a finite state machine or a list of finite state machines.')
for transitions in itertools.product(*(m.iter_transitions() for m in machines)):
try:
word = function(*transitions)
except LookupError:
continue
result.add_transition(tuple((t.from_state for t in transitions)), tuple((t.to_state for t in transitions)), word[0], word[1])
if only_accessible_components:
state_iterator = itertools.product(*(m.iter_initial_states() for m in machines))
else:
state_iterator = itertools.product(*(m.iter_states() for m in machines))
for state in state_iterator:
result.add_state(state)
for state in result.states():
if all((s.is_initial for s in state.label())):
state.is_initial = True
if all((s.is_final for s in state.label())):
state.is_final = True
state.final_word_out = final_function(*state.label())
if all(((s.color is None) for s in state.label())):
state.color = None
else:
state.color = tuple((s.color for s in state.label()))
if only_accessible_components:
if (result.input_alphabet is None):
result.determine_alphabets()
return result.accessible_components()
else:
return result
def composition(self, other, algorithm=None, only_accessible_components=True):
'\n Return a new transducer which is the composition of ``self``\n and ``other``.\n\n INPUT:\n\n - ``other`` -- a transducer\n\n - ``algorithm`` -- can be one of the following\n\n - ``direct`` -- The composition is calculated directly.\n\n There can be arbitrarily many initial and final states,\n but the input and output labels must have length `1`.\n\n .. WARNING::\n\n The output of ``other`` is fed into ``self``.\n\n - ``explorative`` -- An explorative algorithm is used.\n\n The input alphabet of self has to be specified.\n\n .. WARNING::\n\n The output of ``other`` is fed into ``self``.\n\n If algorithm is ``None``, then the algorithm is chosen\n automatically (at the moment always ``direct``, except when\n there are output words of ``other`` or input words of ``self``\n of length greater than `1`).\n\n OUTPUT:\n\n A new transducer.\n\n The labels of the new finite state machine are pairs of states\n of the original finite state machines. The color of a new\n state is the tuple of colors of the constituent states.\n\n\n EXAMPLES::\n\n sage: F = Transducer([(\'A\', \'B\', 1, 0), (\'B\', \'A\', 0, 1)],\n ....: initial_states=[\'A\', \'B\'], final_states=[\'B\'],\n ....: determine_alphabets=True)\n sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: initial_states=[1], final_states=[2],\n ....: determine_alphabets=True)\n sage: Hd = F.composition(G, algorithm=\'direct\')\n sage: Hd.initial_states()\n [(1, \'B\'), (1, \'A\')]\n sage: Hd.transitions()\n [Transition from (1, \'B\') to (1, \'A\'): 1|1,\n Transition from (1, \'A\') to (2, \'B\'): 0|0,\n Transition from (2, \'B\') to (2, \'A\'): 0|1,\n Transition from (2, \'A\') to (2, \'B\'): 1|0]\n sage: He = F.composition(G, algorithm=\'explorative\')\n sage: He.initial_states()\n [(1, \'A\'), (1, \'B\')]\n sage: He.transitions()\n [Transition from (1, \'A\') to (2, \'B\'): 0|0,\n Transition from (1, \'B\') to (1, \'A\'): 1|1,\n Transition from (2, \'B\') to (2, \'A\'): 0|1,\n Transition from (2, \'A\') to (2, \'B\'): 1|0]\n sage: Hd == He\n True\n\n The following example has output of length `> 1`, so the\n explorative algorithm has to be used (and is selected\n automatically).\n\n ::\n\n sage: F = Transducer([(\'A\', \'B\', 1, [1, 0]), (\'B\', \'B\', 1, 1),\n ....: (\'B\', \'B\', 0, 0)],\n ....: initial_states=[\'A\'], final_states=[\'B\'])\n sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),\n ....: (2, 2, 0, 1), (2, 1, 1, 1)],\n ....: initial_states=[1], final_states=[1])\n sage: He = G.composition(F, algorithm=\'explorative\')\n sage: He.transitions()\n [Transition from (\'A\', 1) to (\'B\', 2): 1|0,1,\n Transition from (\'B\', 2) to (\'B\', 2): 0|1,\n Transition from (\'B\', 2) to (\'B\', 1): 1|1,\n Transition from (\'B\', 1) to (\'B\', 1): 0|0,\n Transition from (\'B\', 1) to (\'B\', 2): 1|0]\n sage: Ha = G.composition(F)\n sage: Ha == He\n True\n\n Final output words are also considered::\n\n sage: F = Transducer([(\'A\', \'B\', 1, 0), (\'B\', \'A\', 0, 1)],\n ....: initial_states=[\'A\', \'B\'],\n ....: final_states=[\'A\', \'B\'])\n sage: F.state(\'A\').final_word_out = 0\n sage: F.state(\'B\').final_word_out = 1\n sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: initial_states=[1], final_states=[2])\n sage: G.state(2).final_word_out = 0\n sage: Hd = F.composition(G, algorithm=\'direct\')\n sage: Hd.final_states()\n [(2, \'B\')]\n sage: He = F.composition(G, algorithm=\'explorative\')\n sage: He.final_states()\n [(2, \'B\')]\n\n Note that ``(2, \'A\')`` is not final, as the final output `0`\n of state `2` of `G` cannot be processed in state ``\'A\'`` of\n `F`.\n\n ::\n\n sage: [s.final_word_out for s in Hd.final_states()]\n [[1, 0]]\n sage: [s.final_word_out for s in He.final_states()]\n [[1, 0]]\n sage: Hd == He\n True\n\n Here is a non-deterministic example with intermediate output\n length `>1`.\n\n ::\n\n sage: F = Transducer([(1, 1, 1, [\'a\', \'a\']), (1, 2, 1, \'b\'),\n ....: (2, 1, 2, \'a\'), (2, 2, 2, \'b\')],\n ....: initial_states=[1, 2])\n sage: G = Transducer([(\'A\', \'A\', \'a\', \'i\'),\n ....: (\'A\', \'B\', \'a\', \'l\'),\n ....: (\'B\', \'B\', \'b\', \'e\')],\n ....: initial_states=[\'A\', \'B\'])\n sage: G(F).transitions()\n [Transition from (1, \'A\') to (1, \'A\'): 1|\'i\',\'i\',\n Transition from (1, \'A\') to (1, \'B\'): 1|\'i\',\'l\',\n Transition from (1, \'B\') to (2, \'B\'): 1|\'e\',\n Transition from (2, \'A\') to (1, \'A\'): 2|\'i\',\n Transition from (2, \'A\') to (1, \'B\'): 2|\'l\',\n Transition from (2, \'B\') to (2, \'B\'): 2|\'e\']\n\n Be aware that after composition, different transitions may\n share the same output label (same python object)::\n\n sage: F = Transducer([ (\'A\',\'B\',0,0), (\'B\',\'A\',0,0)],\n ....: initial_states=[\'A\'],\n ....: final_states=[\'A\'])\n sage: F.transitions()[0].word_out is F.transitions()[1].word_out\n False\n sage: G = Transducer([(\'C\',\'C\',0,1)],\n ....: initial_states=[\'C\'],\n ....: final_states=[\'C\'])\n sage: H = G.composition(F)\n sage: H.transitions()[0].word_out is H.transitions()[1].word_out\n True\n\n TESTS:\n\n In the explorative algorithm, transducers with non-empty final\n output words are implemented in :trac:`16548`::\n\n sage: A = transducers.GrayCode()\n sage: B = transducers.abs([0, 1])\n sage: A.composition(B, algorithm=\'explorative\').transitions()\n [Transition from (0, 0) to (0, 1): 0|-,\n Transition from (0, 0) to (0, 2): 1|-,\n Transition from (0, 1) to (0, 1): 0|0,\n Transition from (0, 1) to (0, 2): 1|1,\n Transition from (0, 2) to (0, 1): 0|1,\n Transition from (0, 2) to (0, 2): 1|0]\n\n Similarly, the explorative algorithm can handle\n non-deterministic finite state machines as of :trac:`16548`::\n\n sage: A = Transducer([(0, 0, 0, 0), (0, 1, 0, 0)],\n ....: initial_states=[0])\n sage: B = transducers.Identity([0])\n sage: A.composition(B, algorithm=\'explorative\').transitions()\n [Transition from (0, 0) to (0, 0): 0|0,\n Transition from (0, 0) to (0, 1): 0|0]\n sage: B.composition(A, algorithm=\'explorative\').transitions()\n [Transition from (0, 0) to (0, 0): 0|0,\n Transition from (0, 0) to (1, 0): 0|0]\n\n In the following example, ``algorithm=\'direct\'`` is inappropriate\n as there are edges with output labels of length greater than 1::\n\n sage: F = Transducer([(\'A\', \'B\', 1, [1, 0]), (\'B\', \'B\', 1, 1),\n ....: (\'B\', \'B\', 0, 0)],\n ....: initial_states=[\'A\'], final_states=[\'B\'])\n sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),\n ....: (2, 2, 0, 1), (2, 1, 1, 1)],\n ....: initial_states=[1], final_states=[1])\n sage: Hd = G.composition(F, algorithm=\'direct\')\n\n In the following examples, we compose transducers and automata\n and check whether the types are correct.\n\n ::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: is_Automaton, is_Transducer)\n sage: T = Transducer([(0, 0, 0, 0)], initial_states=[0])\n sage: A = Automaton([(0, 0, 0)], initial_states=[0])\n sage: is_Transducer(T.composition(T, algorithm=\'direct\'))\n True\n sage: is_Transducer(T.composition(T, algorithm=\'explorative\'))\n True\n sage: T.composition(A, algorithm=\'direct\')\n Traceback (most recent call last):\n ...\n TypeError: Composition with automaton is not possible.\n sage: T.composition(A, algorithm=\'explorative\')\n Traceback (most recent call last):\n ...\n TypeError: Composition with automaton is not possible.\n sage: A.composition(A, algorithm=\'direct\')\n Traceback (most recent call last):\n ...\n TypeError: Composition with automaton is not possible.\n sage: A.composition(A, algorithm=\'explorative\')\n Traceback (most recent call last):\n ...\n TypeError: Composition with automaton is not possible.\n sage: is_Automaton(A.composition(T, algorithm=\'direct\'))\n True\n sage: is_Automaton(A.composition(T, algorithm=\'explorative\'))\n True\n\n Non-deterministic final output cannot be handled::\n\n sage: F = Transducer([(\'I\', \'A\', 0, 42), (\'I\', \'B\', 0, 42)],\n ....: initial_states=[\'I\'],\n ....: final_states=[\'A\', \'B\'])\n sage: G = Transducer(initial_states=[0],\n ....: final_states=[0],\n ....: input_alphabet=[0])\n sage: G.state(0).final_word_out = 0\n sage: H = F.composition(G, algorithm=\'explorative\')\n sage: for s in H.final_states():\n ....: print("{} {}".format(s, s.final_word_out))\n (0, \'I\') [42]\n sage: F.state(\'A\').final_word_out = \'a\'\n sage: F.state(\'B\').final_word_out = \'b\'\n sage: F.composition(G, algorithm=\'explorative\')\n Traceback (most recent call last):\n ...\n NotImplementedError: Stopping in state (0, \'I\') leads to\n non-deterministic final output.\n\n Check that the output and input alphabets are set correctly::\n\n sage: F = Transducer([(0, 0, 1, \'A\')],\n ....: initial_states=[0],\n ....: determine_alphabets=False)\n sage: G = Transducer([(2, 2, \'A\', \'a\')],\n ....: initial_states=[2],\n ....: determine_alphabets=False)\n sage: Hd = G(F, algorithm=\'direct\')\n sage: Hd.input_alphabet, Hd.output_alphabet\n ([1], [\'a\'])\n sage: He = G(F, algorithm=\'explorative\')\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given. Try calling\n determine_alphabets().\n sage: F.input_alphabet = [1]\n sage: Hd = G(F, algorithm=\'direct\')\n sage: Hd.input_alphabet, Hd.output_alphabet\n ([1], [\'a\'])\n sage: He = G(F, algorithm=\'explorative\')\n sage: He.input_alphabet, He.output_alphabet\n ([1], None)\n sage: G.output_alphabet = [\'a\']\n sage: Hd = G(F, algorithm=\'direct\')\n sage: Hd.input_alphabet, Hd.output_alphabet\n ([1], [\'a\'])\n sage: He = G(F, algorithm=\'explorative\')\n sage: He.input_alphabet, He.output_alphabet\n ([1], [\'a\'])\n sage: Hd == He\n True\n sage: F.input_alphabet = None\n sage: Hd = G(F, algorithm=\'direct\')\n sage: Hd.input_alphabet, Hd.output_alphabet\n ([1], [\'a\'])\n sage: He = G(F, algorithm=\'explorative\')\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given. Try calling\n determine_alphabets().\n '
if (not other._allow_composition_):
raise TypeError('Composition with automaton is not possible.')
if (algorithm is None):
if (any(((len(t.word_out) > 1) for t in other.iter_transitions())) or any(((len(t.word_in) != 1) for t in self.iter_transitions()))):
algorithm = 'explorative'
else:
algorithm = 'direct'
if (algorithm == 'direct'):
return self._composition_direct_(other, only_accessible_components)
elif (algorithm == 'explorative'):
return self._composition_explorative_(other)
else:
raise ValueError(('Unknown algorithm %s.' % (algorithm,)))
def _composition_direct_(self, other, only_accessible_components=True):
"\n See :meth:`.composition` for details.\n\n TESTS::\n\n sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)],\n ....: initial_states=['A', 'B'], final_states=['B'],\n ....: determine_alphabets=True)\n sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1),\n ....: (2, 2, 1, 1), (2, 2, 0, 0)],\n ....: initial_states=[1], final_states=[2],\n ....: determine_alphabets=True)\n sage: Hd = F._composition_direct_(G)\n sage: Hd.initial_states()\n [(1, 'B'), (1, 'A')]\n sage: Hd.transitions()\n [Transition from (1, 'B') to (1, 'A'): 1|1,\n Transition from (1, 'A') to (2, 'B'): 0|0,\n Transition from (2, 'B') to (2, 'A'): 0|1,\n Transition from (2, 'A') to (2, 'B'): 1|0]\n "
def function(transition1, transition2):
if (transition1.word_out == transition2.word_in):
return (transition1.word_in, transition2.word_out)
else:
raise LookupError
result = other.product_FiniteStateMachine(self, function, only_accessible_components=only_accessible_components, final_function=(lambda s1, s2: []), new_class=self.__class__)
for state_result in result.iter_states():
state = state_result.label()[0]
if state.is_final:
(accept, _, output) = self.process(state.final_word_out, initial_state=self.state(state_result.label()[1]))
if (not accept):
state_result.is_final = False
else:
state_result.is_final = True
state_result.final_word_out = output
return result
def _composition_explorative_(self, other):
"\n See :meth:`.composition` for details.\n\n TESTS::\n\n sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1),\n ....: ('B', 'B', 0, 0)],\n ....: initial_states=['A'], final_states=['B'])\n sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0),\n ....: (2, 2, 0, 1), (2, 1, 1, 1)],\n ....: initial_states=[1], final_states=[1])\n sage: He = G._composition_explorative_(F)\n sage: He.transitions()\n [Transition from ('A', 1) to ('B', 2): 1|0,1,\n Transition from ('B', 2) to ('B', 2): 0|1,\n Transition from ('B', 2) to ('B', 1): 1|1,\n Transition from ('B', 1) to ('B', 1): 0|0,\n Transition from ('B', 1) to ('B', 2): 1|0]\n\n Check that colors are correctly dealt with, cf. :trac:`19199`.\n In particular, the new colors have to be hashable such that\n :meth:`Automaton.determinisation` does not fail::\n\n sage: T = Transducer([[0, 0, 0, 0]], initial_states=[0])\n sage: A = T.input_projection()\n sage: B = A.composition(T, algorithm='explorative')\n sage: B.states()[0].color is None\n True\n sage: A.state(0).color = 0\n sage: B = A.composition(T, algorithm='explorative')\n sage: B.states()[0].color\n (None, 0)\n sage: B.determinisation()\n Automaton with 1 state\n "
def composition_transition(states, input):
(state1, state2) = states
return [((new_state1, new_state2), output_second) for (_, new_state1, output_first) in first.process([input], list_of_outputs=True, initial_state=state1, write_final_word_out=False) for (_, new_state2, output_second) in second.process(output_first, list_of_outputs=True, initial_state=state2, write_final_word_out=False, always_include_output=True)]
first = other
if any(((len(t.word_in) > 1) for t in first.iter_transitions())):
first = first.split_transitions()
second = self
if any(((len(t.word_in) > 1) for t in second.iter_transitions())):
second = second.split_transitions()
F = first.empty_copy(new_class=second.__class__)
new_initial_states = itertools.product(first.iter_initial_states(), second.iter_initial_states())
F.add_from_transition_function(composition_transition, initial_states=new_initial_states)
for state in F.iter_states():
(state1, state2) = state.label()
if state1.is_final:
final_output_second = second.process(state1.final_word_out, list_of_outputs=True, initial_state=state2, only_accepted=True, always_include_output=True)
if ((len(final_output_second) > 1) and (not equal((r[2] for r in final_output_second)))):
raise NotImplementedError(('Stopping in state %s leads to non-deterministic final output.' % state))
if final_output_second:
state.is_final = True
state.final_word_out = final_output_second[0][2]
if all(((s.color is None) for s in state.label())):
state.color = None
else:
state.color = tuple((s.color for s in state.label()))
F.output_alphabet = second.output_alphabet
return F
def input_projection(self):
"\n Return an automaton where the output of each transition of\n self is deleted.\n\n OUTPUT:\n\n An automaton.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),\n ....: ('B', 'B', 1, 0)])\n sage: G = F.input_projection()\n sage: G.transitions()\n [Transition from 'A' to 'B': 0|-,\n Transition from 'A' to 'A': 1|-,\n Transition from 'B' to 'B': 1|-]\n "
return self.projection(what='input')
def output_projection(self):
"\n Return a automaton where the input of each transition of self\n is deleted and the new input is the original output.\n\n OUTPUT:\n\n An automaton.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),\n ....: ('B', 'B', 1, 0)])\n sage: G = F.output_projection()\n sage: G.transitions()\n [Transition from 'A' to 'B': 1|-,\n Transition from 'A' to 'A': 1|-,\n Transition from 'B' to 'B': 0|-]\n\n Final output words are also considered correctly::\n\n sage: H = Transducer([('A', 'B', 0, 1), ('A', 'A', 1, 1),\n ....: ('B', 'B', 1, 0), ('A', ('final', 0), 0, 0)],\n ....: final_states=['A', 'B'])\n sage: H.state('B').final_word_out = 2\n sage: J = H.output_projection()\n sage: J.states()\n ['A', 'B', ('final', 0), ('final', 1)]\n sage: J.transitions()\n [Transition from 'A' to 'B': 1|-,\n Transition from 'A' to 'A': 1|-,\n Transition from 'A' to ('final', 0): 0|-,\n Transition from 'B' to 'B': 0|-,\n Transition from 'B' to ('final', 1): 2|-]\n sage: J.final_states()\n ['A', ('final', 1)]\n "
return self.projection(what='output')
def projection(self, what='input'):
"\n Return an Automaton which transition labels are the projection\n of the transition labels of the input.\n\n INPUT:\n\n - ``what`` -- (default: ``input``) either ``input`` or ``output``.\n\n OUTPUT:\n\n An automaton.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1),\n ....: ('B', 'B', 1, 0)])\n sage: G = F.projection(what='output')\n sage: G.transitions()\n [Transition from 'A' to 'B': 1|-,\n Transition from 'A' to 'A': 1|-,\n Transition from 'B' to 'B': 0|-]\n "
new = Automaton()
if (what == 'input'):
new.input_alphabet = copy(self.input_alphabet)
elif (what == 'output'):
new.input_alphabet = copy(self.output_alphabet)
else:
raise NotImplementedError
state_mapping = {}
for state in self.iter_states():
state_mapping[state] = new.add_state(deepcopy(state))
for transition in self.iter_transitions():
if (what == 'input'):
new_word_in = transition.word_in
elif (what == 'output'):
new_word_in = transition.word_out
else:
raise NotImplementedError
new.add_transition((state_mapping[transition.from_state], state_mapping[transition.to_state], new_word_in, None))
if (what == 'output'):
states = [s for s in self.iter_final_states() if s.final_word_out]
if (not states):
return new
number = 0
while new.has_state(('final', number)):
number += 1
final = new.add_state(('final', number))
final.is_final = True
for state in states:
output = state.final_word_out
new.state(state_mapping[state]).final_word_out = []
new.state(state_mapping[state]).is_final = False
new.add_transition((state_mapping[state], final, output, None))
return new
def transposition(self, reverse_output_labels=True):
"\n Return a new finite state machine, where all transitions of the\n input finite state machine are reversed.\n\n INPUT:\n\n - ``reverse_output_labels`` -- a boolean (default: ``True``): whether to reverse\n output labels.\n\n OUTPUT:\n\n A new finite state machine.\n\n EXAMPLES::\n\n sage: aut = Automaton([('A', 'A', 0), ('A', 'A', 1), ('A', 'B', 0)],\n ....: initial_states=['A'], final_states=['B'])\n sage: aut.transposition().transitions('B')\n [Transition from 'B' to 'A': 0|-]\n\n ::\n\n sage: aut = Automaton([('1', '1', 1), ('1', '2', 0), ('2', '2', 0)],\n ....: initial_states=['1'], final_states=['1', '2'])\n sage: aut.transposition().initial_states()\n ['1', '2']\n\n ::\n\n sage: A = Automaton([(0, 1, [1, 0])],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: A([1, 0])\n True\n sage: A.transposition()([0, 1])\n True\n\n ::\n\n sage: T = Transducer([(0, 1, [1, 0], [1, 0])],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: T([1, 0])\n [1, 0]\n sage: T.transposition()([0, 1])\n [0, 1]\n sage: T.transposition(reverse_output_labels=False)([0, 1])\n [1, 0]\n\n\n TESTS:\n\n If a final state of ``self`` has a non-empty final output word,\n transposition is not implemented::\n\n sage: T = Transducer([('1', '1', 1, 0), ('1', '2', 0, 1),\n ....: ('2', '2', 0, 2)],\n ....: initial_states=['1'],\n ....: final_states=['1', '2'])\n sage: T.state('1').final_word_out = [2, 5]\n sage: T.transposition()\n Traceback (most recent call last):\n ...\n NotImplementedError: Transposition for transducers with\n final output words is not implemented.\n "
if reverse_output_labels:
rewrite_output = (lambda word: list(reversed(word)))
else:
rewrite_output = (lambda word: word)
transposition = self.empty_copy()
for state in self.iter_states():
transposition.add_state(deepcopy(state))
for transition in self.iter_transitions():
transposition.add_transition(transition.to_state.label(), transition.from_state.label(), list(reversed(transition.word_in)), rewrite_output(transition.word_out))
for initial in self.iter_initial_states():
state = transposition.state(initial.label())
if (not initial.is_final):
state.is_final = True
state.is_initial = False
for final in self.iter_final_states():
state = transposition.state(final.label())
if final.final_word_out:
raise NotImplementedError('Transposition for transducers with final output words is not implemented.')
if (not final.is_initial):
state.is_final = False
state.is_initial = True
return transposition
def split_transitions(self):
"\n Return a new transducer, where all transitions in self with input\n labels consisting of more than one letter\n are replaced by a path of the corresponding length.\n\n OUTPUT:\n\n A new transducer.\n\n EXAMPLES::\n\n sage: A = Transducer([('A', 'B', [1, 2, 3], 0)],\n ....: initial_states=['A'], final_states=['B'])\n sage: A.split_transitions().states()\n [('A', ()), ('B', ()),\n ('A', (1,)), ('A', (1, 2))]\n "
new = self.empty_copy()
for state in self.states():
new.add_state(FSMState((state, ()), is_initial=state.is_initial, is_final=state.is_final))
for transition in self.transitions():
for j in range((len(transition.word_in) - 1)):
new.add_transition(((transition.from_state, tuple(transition.word_in[:j])), (transition.from_state, tuple(transition.word_in[:(j + 1)])), transition.word_in[j], []))
new.add_transition(((transition.from_state, tuple(transition.word_in[:(- 1)])), (transition.to_state, ()), transition.word_in[(- 1):], transition.word_out))
return new
def final_components(self):
"\n Return the final components of a finite state machine as finite\n state machines.\n\n OUTPUT:\n\n A list of finite state machines, each representing a final\n component of ``self``.\n\n A final component of a transducer ``T`` is a strongly connected\n component ``C`` such that there are no transitions of ``T``\n leaving ``C``.\n\n The final components are the only parts of a transducer which\n influence the main terms of the asymptotic behaviour of the sum\n of output labels of a transducer, see [HKP2015]_ and [HKW2015]_.\n\n EXAMPLES::\n\n sage: T = Transducer([['A', 'B', 0, 0], ['B', 'C', 0, 1],\n ....: ['C', 'B', 0, 1], ['A', 'D', 1, 0],\n ....: ['D', 'D', 0, 0], ['D', 'B', 1, 0],\n ....: ['A', 'E', 2, 0], ['E', 'E', 0, 0]])\n sage: FC = T.final_components()\n sage: sorted(FC[0].transitions())\n [Transition from 'B' to 'C': 0|1,\n Transition from 'C' to 'B': 0|1]\n sage: FC[1].transitions()\n [Transition from 'E' to 'E': 0|0]\n\n Another example (cycle of length 2)::\n\n sage: T = Automaton([[0, 1, 0], [1, 0, 0]])\n sage: len(T.final_components()) == 1\n True\n sage: T.final_components()[0].transitions()\n [Transition from 0 to 1: 0|-,\n Transition from 1 to 0: 0|-]\n "
DG = self.digraph()
condensation = DG.strongly_connected_components_digraph()
return [self.induced_sub_finite_state_machine([self.state(_) for _ in component]) for component in condensation.vertices(sort=True) if (condensation.out_degree(component) == 0)]
def completion(self, sink=None):
"\n Return a completion of this finite state machine.\n\n INPUT:\n\n - ``sink`` -- either an instance of :class:`FSMState` or a label\n for the sink (default: ``None``). If ``None``, the least\n available non-zero integer is used.\n\n OUTPUT:\n\n A :class:`FiniteStateMachine` of the same type as this finite\n state machine.\n\n The resulting finite state machine is a complete version of this\n finite state machine. A finite state machine is considered to\n be complete if each transition has an input label of length one\n and for each pair `(q, a)` where `q` is a state and `a` is an\n element of the input alphabet, there is exactly one transition\n from `q` with input label `a`.\n\n If this finite state machine is already complete, a deep copy is\n returned. Otherwise, a new non-final state (usually called a\n sink) is created and transitions to this sink are introduced as\n appropriate.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine([(0, 0, 0, 0),\n ....: (0, 1, 1, 1),\n ....: (1, 1, 0, 0)])\n sage: F.is_complete()\n False\n sage: G1 = F.completion()\n sage: G1.is_complete()\n True\n sage: G1.transitions()\n [Transition from 0 to 0: 0|0,\n Transition from 0 to 1: 1|1,\n Transition from 1 to 1: 0|0,\n Transition from 1 to 2: 1|-,\n Transition from 2 to 2: 0|-,\n Transition from 2 to 2: 1|-]\n sage: G2 = F.completion('Sink')\n sage: G2.is_complete()\n True\n sage: G2.transitions()\n [Transition from 0 to 0: 0|0,\n Transition from 0 to 1: 1|1,\n Transition from 1 to 1: 0|0,\n Transition from 1 to 'Sink': 1|-,\n Transition from 'Sink' to 'Sink': 0|-,\n Transition from 'Sink' to 'Sink': 1|-]\n sage: F.completion(1)\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine already contains a state\n '1'.\n\n An input alphabet must be given::\n\n sage: F = FiniteStateMachine([(0, 0, 0, 0),\n ....: (0, 1, 1, 1),\n ....: (1, 1, 0, 0)],\n ....: determine_alphabets=False)\n sage: F.is_complete()\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given. Try calling\n determine_alphabets().\n\n Non-deterministic machines are not allowed. ::\n\n sage: F = FiniteStateMachine([(0, 0, 0, 0), (0, 1, 0, 0)])\n sage: F.is_complete()\n False\n sage: F.completion()\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine must be deterministic.\n sage: F = FiniteStateMachine([(0, 0, [0, 0], 0)])\n sage: F.is_complete()\n False\n sage: F.completion()\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine must be deterministic.\n\n .. SEEALSO::\n\n :meth:`is_complete`,\n :meth:`split_transitions`,\n :meth:`determine_alphabets`,\n :meth:`is_deterministic`.\n\n TESTS:\n\n Test the use of an :class:`FSMState` as sink::\n\n sage: F = FiniteStateMachine([(0, 0, 0, 0),\n ....: (0, 1, 1, 1),\n ....: (1, 1, 0, 0)])\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: F.completion(FSMState(1))\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine already contains a state\n '1'.\n sage: s = FSMState(2)\n sage: G = F.completion(s)\n sage: G.state(2) is s\n True\n "
result = deepcopy(self)
if result.is_complete():
return result
if (not result.is_deterministic()):
raise ValueError('The finite state machine must be deterministic.')
if (sink is not None):
try:
s = result.state(sink)
raise ValueError(("The finite state machine already contains a state '%s'." % s.label()))
except LookupError:
pass
else:
sink = (1 + max(itertools.chain([(- 1)], (s.label() for s in result.iter_states() if (s.label() in ZZ)))))
sink_state = result.add_state(sink)
for state in result.iter_states():
for transition in state.transitions:
if (len(transition.word_in) != 1):
raise ValueError('Transitions with input labels of length greater than one are not allowed. Try calling split_transitions().')
existing = set((transition.word_in[0] for transition in state.transitions))
for missing in (set(result.input_alphabet) - existing):
result.add_transition(state, sink_state, missing)
return result
def prepone_output(self):
"\n For all paths, shift the output of the path from one\n transition to the earliest possible preceding transition of\n the path.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n Nothing.\n\n Apply the following to each state `s` (except initial states) of the\n finite state machine as often as possible:\n\n If the letter `a` is a prefix of the output label of all transitions from\n `s` (including the final output of `s`), then remove it from all these\n labels and append it to all output labels of all transitions leading\n to `s`.\n\n We assume that the states have no output labels, but final outputs are\n allowed.\n\n EXAMPLES::\n\n sage: A = Transducer([('A', 'B', 1, 1),\n ....: ('B', 'B', 0, 0),\n ....: ('B', 'C', 1, 0)],\n ....: initial_states=['A'],\n ....: final_states=['C'])\n sage: A.prepone_output()\n sage: A.transitions()\n [Transition from 'A' to 'B': 1|1,0,\n Transition from 'B' to 'B': 0|0,\n Transition from 'B' to 'C': 1|-]\n\n ::\n\n sage: B = Transducer([('A', 'B', 0, 1),\n ....: ('B', 'C', 1, [1, 1]),\n ....: ('B', 'C', 0, 1)],\n ....: initial_states=['A'],\n ....: final_states=['C'])\n sage: B.prepone_output()\n sage: B.transitions()\n [Transition from 'A' to 'B': 0|1,1,\n Transition from 'B' to 'C': 1|1,\n Transition from 'B' to 'C': 0|-]\n\n If initial states are not labeled as such, unexpected results may be\n obtained::\n\n sage: C = Transducer([(0,1,0,0)])\n sage: C.prepone_output()\n verbose 0 (...: finite_state_machine.py, prepone_output)\n All transitions leaving state 0 have an output label with\n prefix 0. However, there is no inbound transition and it\n is not an initial state. This routine (possibly called by\n simplification) therefore erased this prefix from all\n outbound transitions.\n sage: C.transitions()\n [Transition from 0 to 1: 0|-]\n\n Also the final output of final states can be changed::\n\n sage: T = Transducer([('A', 'B', 0, 1),\n ....: ('B', 'C', 1, [1, 1]),\n ....: ('B', 'C', 0, 1)],\n ....: initial_states=['A'],\n ....: final_states=['B'])\n sage: T.state('B').final_word_out = [1]\n sage: T.prepone_output()\n sage: T.transitions()\n [Transition from 'A' to 'B': 0|1,1,\n Transition from 'B' to 'C': 1|1,\n Transition from 'B' to 'C': 0|-]\n sage: T.state('B').final_word_out\n []\n\n ::\n\n sage: S = Transducer([('A', 'B', 0, 1),\n ....: ('B', 'C', 1, [1, 1]),\n ....: ('B', 'C', 0, 1)],\n ....: initial_states=['A'],\n ....: final_states=['B'])\n sage: S.state('B').final_word_out = [0]\n sage: S.prepone_output()\n sage: S.transitions()\n [Transition from 'A' to 'B': 0|1,\n Transition from 'B' to 'C': 1|1,1,\n Transition from 'B' to 'C': 0|1]\n sage: S.state('B').final_word_out\n [0]\n\n Output labels do not have to be hashable::\n\n sage: C = Transducer([(0, 1, 0, []),\n ....: (1, 0, 0, [vector([0, 0]), 0]),\n ....: (1, 1, 1, [vector([0, 0]), 1]),\n ....: (0, 0, 1, 0)],\n ....: determine_alphabets=False,\n ....: initial_states=[0])\n sage: C.prepone_output()\n sage: sorted(C.transitions())\n [Transition from 0 to 1: 0|(0, 0),\n Transition from 0 to 0: 1|0,\n Transition from 1 to 0: 0|0,\n Transition from 1 to 1: 1|1,(0, 0)]\n "
def find_common_output(state):
if (any((transition for transition in self.transitions(state) if (not transition.word_out))) or (state.is_final and (not state.final_word_out))):
return tuple()
first_letters = [transition.word_out[0] for transition in self.transitions(state)]
if state.is_final:
first_letters = (first_letters + [state.final_word_out[0]])
if (not first_letters):
return tuple()
first_item = first_letters.pop()
if all(((item == first_item) for item in first_letters)):
return (first_item,)
return tuple()
changed = 1
iteration = 0
while (changed > 0):
changed = 0
iteration += 1
for state in self.iter_states():
if state.is_initial:
continue
if state.word_out:
raise NotImplementedError(('prepone_output assumes that all states have empty output word, but state %s has output word %s' % (state, state.word_out)))
common_output = find_common_output(state)
if common_output:
changed += 1
if state.is_final:
assert (state.final_word_out[0] == common_output[0])
state.final_word_out = state.final_word_out[1:]
for transition in self.transitions(state):
assert (transition.word_out[0] == common_output[0])
transition.word_out = transition.word_out[1:]
found_inbound_transition = False
for transition in self.iter_transitions():
if (transition.to_state == state):
transition.word_out = (transition.word_out + [common_output[0]])
found_inbound_transition = True
if (not found_inbound_transition):
verbose(('All transitions leaving state %s have an output label with prefix %s. 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.' % (state, common_output[0])), level=0)
def equivalence_classes(self):
'\n Return a list of equivalence classes of states.\n\n OUTPUT:\n\n A list of equivalence classes of states.\n\n Two states `a` and `b` are equivalent if and only if there is\n a bijection `\\varphi` between paths starting at `a` and paths\n starting at `b` with the following properties: Let `p_a` be a\n path from `a` to `a\'` and `p_b` a path from `b` to `b\'` such\n that `\\varphi(p_a)=p_b`, then\n\n - `p_a.\\mathit{word}_\\mathit{in}=p_b.\\mathit{word}_\\mathit{in}`,\n - `p_a.\\mathit{word}_\\mathit{out}=p_b.\\mathit{word}_\\mathit{out}`,\n - `a\'` and `b\'` have the same output label, and\n - `a\'` and `b\'` are both final or both non-final and have the\n same final output word.\n\n The function :meth:`.equivalence_classes` returns a list of\n the equivalence classes to this equivalence relation.\n\n This is one step of Moore\'s minimization algorithm.\n\n .. SEEALSO::\n\n :meth:`.minimization`\n\n EXAMPLES::\n\n sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0),\n ....: ("B", "C", 0, 0), ("B", "C", 1, 1),\n ....: ("C", "D", 0, 1), ("C", "D", 1, 0),\n ....: ("D", "A", 0, 0), ("D", "A", 1, 1)])\n sage: sorted(fsm.equivalence_classes())\n [[\'A\', \'C\'], [\'B\', \'D\']]\n sage: fsm.state("A").is_final = True\n sage: sorted(fsm.equivalence_classes())\n [[\'A\'], [\'B\'], [\'C\'], [\'D\']]\n sage: fsm.state("C").is_final = True\n sage: sorted(fsm.equivalence_classes())\n [[\'A\', \'C\'], [\'B\', \'D\']]\n sage: fsm.state("A").final_word_out = 1\n sage: sorted(fsm.equivalence_classes())\n [[\'A\'], [\'B\'], [\'C\'], [\'D\']]\n sage: fsm.state("C").final_word_out = 1\n sage: sorted(fsm.equivalence_classes())\n [[\'A\', \'C\'], [\'B\', \'D\']]\n '
classes_previous = []
key_0 = (lambda state: (state.is_final, state.color, state.word_out, state.final_word_out))
states_grouped = full_group_by(self.states(), key=key_0)
classes_current = [equivalence_class for (key, equivalence_class) in states_grouped]
while (len(classes_current) != len(classes_previous)):
class_of = {}
classes_previous = classes_current
classes_current = []
for k in range(len(classes_previous)):
for state in classes_previous[k]:
class_of[state] = k
key_current = (lambda state: sorted([(transition.word_in, transition.word_out, class_of[transition.to_state]) for transition in state.transitions]))
for class_previous in classes_previous:
states_grouped = full_group_by(class_previous, key=key_current)
classes_current.extend([equivalence_class for (key, equivalence_class) in states_grouped])
return classes_current
def quotient(self, classes):
'\n Construct the quotient with respect to the equivalence classes.\n\n INPUT:\n\n - ``classes`` is a list of equivalence classes of states.\n\n OUTPUT:\n\n A finite state machine.\n\n The labels of the new states are tuples of states of the\n ``self``, corresponding to ``classes``.\n\n Assume that `c` is a class, and `a` and `b` are states in\n `c`. Then there is a bijection `\\varphi` between the\n transitions from `a` and the transitions from `b` with the\n following properties: if `\\varphi(t_a)=t_b`, then\n\n - `t_a.\\mathit{word}_\\mathit{in}=t_b.\\mathit{word}_\\mathit{in}`,\n - `t_a.\\mathit{word}_\\mathit{out}=t_b.\\mathit{word}_\\mathit{out}`, and\n - `t_a` and `t_b` lead to some equivalent states `a\'` and `b\'`.\n\n Non-initial states may be merged with initial states, the\n resulting state is an initial state.\n\n All states in a class must have the same ``is_final``,\n ``final_word_out`` and ``word_out`` values.\n\n EXAMPLES::\n\n sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0),\n ....: ("B", "C", 0, 0), ("B", "C", 1, 1),\n ....: ("C", "D", 0, 1), ("C", "D", 1, 0),\n ....: ("D", "A", 0, 0), ("D", "A", 1, 1)])\n sage: fsmq = fsm.quotient([[fsm.state("A"), fsm.state("C")],\n ....: [fsm.state("B"), fsm.state("D")]])\n sage: fsmq.transitions()\n [Transition from (\'A\', \'C\')\n to (\'B\', \'D\'): 0|1,\n Transition from (\'A\', \'C\')\n to (\'B\', \'D\'): 1|0,\n Transition from (\'B\', \'D\')\n to (\'A\', \'C\'): 0|0,\n Transition from (\'B\', \'D\')\n to (\'A\', \'C\'): 1|1]\n sage: fsmq.relabeled().transitions()\n [Transition from 0 to 1: 0|1,\n Transition from 0 to 1: 1|0,\n Transition from 1 to 0: 0|0,\n Transition from 1 to 0: 1|1]\n sage: fsmq1 = fsm.quotient(fsm.equivalence_classes())\n sage: fsmq1 == fsmq\n True\n sage: fsm.quotient([[fsm.state("A"), fsm.state("B"), fsm.state("C"), fsm.state("D")]])\n Traceback (most recent call last):\n ...\n AssertionError: Transitions of state \'A\' and \'B\' are incompatible.\n\n TESTS::\n\n sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0),\n ....: ("B", "C", 0, 0), ("B", "C", 1, 1),\n ....: ("C", "D", 0, 1), ("C", "D", 1, 0),\n ....: ("D", "A", 0, 0), ("D", "A", 1, 1)],\n ....: final_states=["A", "C"])\n sage: fsm.state("A").final_word_out = 1\n sage: fsm.state("C").final_word_out = 2\n sage: fsmq = fsm.quotient([[fsm.state("A"), fsm.state("C")],\n ....: [fsm.state("B"), fsm.state("D")]])\n Traceback (most recent call last):\n ...\n AssertionError: Class [\'A\', \'C\'] mixes\n final states with different final output words.\n '
new = self.empty_copy()
state_mapping = {}
for c in classes:
new_label = tuple(c)
new_state = c[0].relabeled(new_label)
new.add_state(new_state)
for state in c:
state_mapping[state] = new_state
for c in classes:
new_state = state_mapping[c[0]]
sorted_transitions = sorted([(state_mapping[t.to_state], t.word_in, t.word_out) for t in c[0].transitions])
for transition in self.iter_transitions(c[0]):
new.add_transition(from_state=new_state, to_state=state_mapping[transition.to_state], word_in=transition.word_in, word_out=transition.word_out)
for state in c:
new_state.is_initial = (new_state.is_initial or state.is_initial)
assert (new_state.is_final == state.is_final), ('Class %s mixes final and non-final states' % (c,))
assert (new_state.word_out == state.word_out), ('Class %s mixes different word_out' % (c,))
assert (new_state.color == state.color), ('Class %s mixes different colors' % (c,))
assert (sorted_transitions == sorted([(state_mapping[t.to_state], t.word_in, t.word_out) for t in state.transitions])), ('Transitions of state %s and %s are incompatible.' % (c[0], state))
assert (new_state.final_word_out == state.final_word_out), ('Class %s mixes final states with different final output words.' % (c,))
return new
def merged_transitions(self):
'\n Merges transitions which have the same ``from_state``,\n ``to_state`` and ``word_out`` while adding their ``word_in``.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A finite state machine with merged transitions. If no mergers occur,\n return ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: T = Transducer([[1, 2, 1/4, 1], [1, -2, 1/4, 1], [1, -2, 1/2, 1],\n ....: [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1],\n ....: [-2, 2, 1/4, 1], [2, 3, 1/2, 1], [-2, 3, 1/2, 1]],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: T1 = T.merged_transitions()\n sage: T1 is T\n False\n sage: sorted(T1.transitions())\n [Transition from -2 to -2: 1/4|1,\n Transition from -2 to 2: 1/4|1,\n Transition from -2 to 3: 1/2|1,\n Transition from 1 to 2: 1/4|1,\n Transition from 1 to -2: 3/4|1,\n Transition from 2 to -2: 1/4|1,\n Transition from 2 to 2: 1/4|1,\n Transition from 2 to 3: 1/2|1]\n\n Applying the function again does not change the result::\n\n sage: T2 = T1.merged_transitions()\n sage: T2 is T1\n True\n '
def key(transition):
return (transition.to_state, transition.word_out)
new = self.empty_copy()
changed = False
state_dict = {}
memo = {}
for state in self.states():
new_state = deepcopy(state, memo)
state_dict[state] = new_state
new.add_state(new_state)
for state in self.states():
grouped_transitions = itertools.groupby(sorted(state.transitions, key=key), key=key)
for ((to_state, word_out), transitions) in grouped_transitions:
transition_list = list(transitions)
changed = (changed or (len(transition_list) > 1))
word_in = 0
for transition in transition_list:
if (isinstance(transition.word_in, Iterable) and (len(transition.word_in) == 1)):
word_in += transition.word_in[0]
else:
raise TypeError(('%s does not have a list of length 1 as word_in' % transition))
new.add_transition((state, to_state, word_in, word_out))
if changed:
return new
else:
return self
def markov_chain_simplification(self):
'\n Consider ``self`` as Markov chain with probabilities as input labels\n and simplify it.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n Simplified version of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: T = Transducer([[1, 2, 1/4, 0], [1, -2, 1/4, 0], [1, -2, 1/2, 0],\n ....: [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1],\n ....: [-2, 2, 1/4, 1], [2, 3, 1/2, 2], [-2, 3, 1/2, 2]],\n ....: initial_states=[1],\n ....: final_states=[3],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: T1 = T.markov_chain_simplification()\n sage: sorted(T1.transitions())\n [Transition from ((1,),) to ((2, -2),): 1|0,\n Transition from ((2, -2),) to ((2, -2),): 1/2|1,\n Transition from ((2, -2),) to ((3,),): 1/2|2]\n '
current = self.merged_transitions()
number_states = len(current.states())
while True:
current = current.simplification()
new_number_states = len(current.states())
new = current.merged_transitions()
if ((new is current) and (number_states == new_number_states)):
return new
current = new
number_states = new_number_states
def with_final_word_out(self, letters, allow_non_final=True):
'\n Constructs a new finite state machine with final output words\n for all states by implicitly reading trailing letters until a\n final state is reached.\n\n INPUT:\n\n - ``letters`` -- either an element of the input alphabet or a\n list of such elements. This is repeated cyclically when\n needed.\n\n - ``allow_non_final`` -- a boolean (default: ``True``) which\n indicates whether we allow that some states may be non-final\n in the resulting finite state machine. I.e., if ``False`` then\n each state has to have a path to a final state with input\n label matching ``letters``.\n\n OUTPUT:\n\n A finite state machine.\n\n The inplace version of this function is\n :meth:`.construct_final_word_out`.\n\n Suppose for the moment a single element ``letter`` as input\n for ``letters``. This is equivalent to ``letters = [letter]``.\n We will discuss the general case below.\n\n Let ``word_in`` be a word over the input alphabet and assume\n that the original finite state machine transforms ``word_in`` to\n ``word_out`` reaching a possibly non-final state ``s``. Let\n further `k` be the minimum number of letters ``letter`` such\n that there is a path from ``s`` to some final state ``f`` whose\n input label consists of `k` copies of ``letter`` and whose\n output label is ``path_word_out``. Then the state ``s`` of the\n resulting finite state machine is a final state with final\n output ``path_word_out + f.final_word_out``. Therefore, the new\n finite state machine transforms ``word_in`` to ``word_out +\n path_word_out + f.final_word_out``.\n\n This is e.g. useful for finite state machines operating on digit\n expansions: there, it is sometimes required to read a sufficient\n number of trailing zeros (at the most significant positions) in\n order to reach a final state and to flush all carries. In this\n case, this method constructs an essentially equivalent finite\n state machine in the sense that it not longer requires adding\n sufficiently many trailing zeros. However, it is the\n responsibility of the user to make sure that if adding trailing\n zeros to the input anyway, the output is equivalent.\n\n If ``letters`` consists of more than one letter, then it is\n assumed that (not necessarily complete) cycles of ``letters``\n are appended as trailing input.\n\n .. SEEALSO::\n\n :ref:`example on Gray code <finite_state_machine_gray_code_example>`\n\n EXAMPLES:\n\n #. A simple transducer transforming `00` blocks to `01`\n blocks::\n\n sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T.process([0, 0, 0])\n (False, 1, [0, 1, 0])\n sage: T.process([0, 0, 0, 0])\n (True, 0, [0, 1, 0, 1])\n sage: F = T.with_final_word_out(0)\n sage: for f in F.iter_final_states():\n ....: print("{} {}".format(f, f.final_word_out))\n 0 []\n 1 [1]\n sage: F.process([0, 0, 0])\n (True, 1, [0, 1, 0, 1])\n sage: F.process([0, 0, 0, 0])\n (True, 0, [0, 1, 0, 1])\n\n #. A more realistic example: Addition of `1` in binary. We\n construct a transition function transforming the input\n to its binary expansion::\n\n sage: def binary_transition(carry, input):\n ....: value = carry + input\n ....: if value.mod(2) == 0:\n ....: return (value/2, 0)\n ....: else:\n ....: return ((value-1)/2, 1)\n\n Now, we only have to start with a carry of `1` to\n get the required transducer::\n\n sage: T = Transducer(binary_transition,\n ....: input_alphabet=[0, 1],\n ....: initial_states=[1],\n ....: final_states=[0])\n\n We test this for the binary expansion of `7`::\n\n sage: T.process([1, 1, 1])\n (False, 1, [0, 0, 0])\n\n The final carry `1` has not be flushed yet, we have to add a\n trailing zero::\n\n sage: T.process([1, 1, 1, 0])\n (True, 0, [0, 0, 0, 1])\n\n We check that with this trailing zero, the transducer\n performs as advertised::\n\n sage: all(ZZ(T(k.bits()+[0]), base=2) == k + 1\n ....: for k in srange(16))\n True\n\n However, most of the time, we produce superfluous trailing\n zeros::\n\n sage: T(11.bits()+[0])\n [0, 0, 1, 1, 0]\n\n We now use this method::\n\n sage: F = T.with_final_word_out(0)\n sage: for f in F.iter_final_states():\n ....: print("{} {}".format(f, f.final_word_out))\n 1 [1]\n 0 []\n\n The same tests as above, but we do not have to pad with\n trailing zeros anymore::\n\n sage: F.process([1, 1, 1])\n (True, 1, [0, 0, 0, 1])\n sage: all(ZZ(F(k.bits()), base=2) == k + 1\n ....: for k in srange(16))\n True\n\n No more trailing zero in the output::\n\n sage: F(11.bits())\n [0, 0, 1, 1]\n sage: all(F(k.bits())[-1] == 1\n ....: for k in srange(16))\n True\n\n #. Here is an example, where we allow trailing repeated `10`::\n\n sage: T = Transducer([(0, 1, 0, \'a\'),\n ....: (1, 2, 1, \'b\'),\n ....: (2, 0, 0, \'c\')],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: F = T.with_final_word_out([1, 0])\n sage: for f in F.iter_final_states():\n ....: print(str(f) + \' \' + \'\'.join(f.final_word_out))\n 0\n 1 bc\n\n Trying this with trailing repeated `01` does not produce\n a ``final_word_out`` for state ``1``, but for state ``2``::\n\n sage: F = T.with_final_word_out([0, 1])\n sage: for f in F.iter_final_states():\n ....: print(str(f) + \' \' + \'\'.join(f.final_word_out))\n 0\n 2 c\n\n #. Here another example with a more-letter trailing input::\n\n sage: T = Transducer([(0, 1, 0, \'a\'),\n ....: (1, 2, 0, \'b\'), (1, 2, 1, \'b\'),\n ....: (2, 3, 0, \'c\'), (2, 0, 1, \'e\'),\n ....: (3, 1, 0, \'d\'), (3, 1, 1, \'d\')],\n ....: initial_states=[0],\n ....: final_states=[0],\n ....: with_final_word_out=[0, 0, 1, 1])\n sage: for f in T.iter_final_states():\n ....: print(str(f) + \' \' + \'\'.join(f.final_word_out))\n 0\n 1 bcdbcdbe\n 2 cdbe\n 3 dbe\n\n TESTS:\n\n #. Reading copies of ``letter`` may result in a cycle. In\n this simple example, we have no final state at all::\n\n sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)],\n ....: initial_states=[0])\n sage: T.with_final_word_out(0)\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine contains\n a cycle starting at state 0 with input label 0\n and no final state.\n\n #. A unique transition with input word ``letter`` is\n required::\n\n sage: T = Transducer([(0, 1, 0, 0), (0, 2, 0, 0)])\n sage: T.with_final_word_out(0)\n Traceback (most recent call last):\n ...\n ValueError: No unique transition leaving state 0\n with input label 0.\n\n It is not a problem if there is no transition starting\n at state ``1`` with input word ``letter``::\n\n sage: T = Transducer([(0, 1, 0, 0)])\n sage: F = T.with_final_word_out(0)\n sage: for f in F.iter_final_states():\n ....: print(f, f.final_word_out)\n\n Anyhow, you can override this by::\n\n sage: T = Transducer([(0, 1, 0, 0)])\n sage: T.with_final_word_out(0, allow_non_final=False)\n Traceback (most recent call last):\n ...\n ValueError: No unique transition leaving state 1\n with input label 0.\n\n #. All transitions must have input labels of length `1`::\n\n sage: T = Transducer([(0, 0, [], 0)])\n sage: T.with_final_word_out(0)\n Traceback (most recent call last):\n ...\n NotImplementedError: All transitions must have input\n labels of length 1. Consider calling split_transitions().\n sage: T = Transducer([(0, 0, [0, 1], 0)])\n sage: T.with_final_word_out(0)\n Traceback (most recent call last):\n ...\n NotImplementedError: All transitions must have input\n labels of length 1. Consider calling split_transitions().\n\n #. An empty list as input is not allowed::\n\n sage: T = Transducer([(0, 0, [], 0)])\n sage: T.with_final_word_out([])\n Traceback (most recent call last):\n ...\n ValueError: letters is not allowed to be an empty list.\n '
new = deepcopy(self)
new.construct_final_word_out(letters, allow_non_final)
return new
def construct_final_word_out(self, letters, allow_non_final=True):
'\n This is an inplace version of :meth:`.with_final_word_out`. See\n :meth:`.with_final_word_out` for documentation and examples.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: F = T.with_final_word_out(0)\n sage: T.construct_final_word_out(0)\n sage: T == F # indirect doctest\n True\n sage: T = Transducer([(0, 1, 0, None)],\n ....: final_states=[1])\n sage: F = T.with_final_word_out(0)\n sage: F.state(0).final_word_out\n []\n '
if (not isinstance(letters, list)):
letters = [letters]
elif (not letters):
raise ValueError('letters is not allowed to be an empty list.')
in_progress = set()
cache = {}
def find_final_word_out(state):
(position, letter) = next(trailing_letters)
if state.is_final:
return state.final_word_out
if ((state, position) in cache):
return cache[(state, position)]
if ((state, position) in in_progress):
raise ValueError(('The finite state machine contains a cycle starting at state %s with input label %s and no final state.' % (state, letter)))
if any(((len(t.word_in) != 1) for t in state.transitions)):
raise NotImplementedError('All transitions must have input labels of length 1. Consider calling split_transitions().')
transitions = [t for t in state.transitions if (t.word_in == [letter])]
if (allow_non_final and (not transitions)):
final_word_out = None
elif (len(transitions) != 1):
raise ValueError(('No unique transition leaving state %s with input label %s.' % (state, letter)))
else:
in_progress.add((state, position))
next_word = find_final_word_out(transitions[0].to_state)
if (next_word is not None):
final_word_out = (transitions[0].word_out + next_word)
else:
final_word_out = None
in_progress.remove((state, position))
cache[(state, position)] = final_word_out
return final_word_out
for state in self.iter_states():
assert (not in_progress)
trailing_letters = itertools.cycle(enumerate(letters))
find_final_word_out(state)
for ((state, position), final_word_out) in cache.items():
if ((position == 0) and (final_word_out is not None)):
state.is_final = True
state.final_word_out = final_word_out
def graph(self, edge_labels='words_in_out'):
"\n Return the graph of the finite state machine with labeled\n vertices and labeled edges.\n\n INPUT:\n\n - ``edge_label``: (default: ``'words_in_out'``) can be\n - ``'words_in_out'`` (labels will be strings ``'i|o'``)\n - a function with which takes as input a transition\n and outputs (returns) the label\n\n OUTPUT:\n\n A :class:`directed graph <DiGraph>`.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: T = Transducer()\n sage: T.graph()\n Looped multi-digraph on 0 vertices\n sage: T.add_state(A)\n 'A'\n sage: T.graph()\n Looped multi-digraph on 1 vertex\n sage: T.add_transition(('A', 'A', 0, 1))\n Transition from 'A' to 'A': 0|1\n sage: T.graph()\n Looped multi-digraph on 1 vertex\n\n .. SEEALSO::\n\n :class:`DiGraph`\n "
if (edge_labels == 'words_in_out'):
label_fct = (lambda t: t._in_out_label_())
elif callable(edge_labels):
label_fct = edge_labels
else:
raise TypeError('Wrong argument for edge_labels.')
graph_data = []
isolated_vertices = []
for state in self.iter_states():
transitions = state.transitions
if (not transitions):
isolated_vertices.append(state.label())
for t in transitions:
graph_data.append((t.from_state.label(), t.to_state.label(), label_fct(t)))
G = DiGraph(graph_data, multiedges=True, loops=True)
G.add_vertices(isolated_vertices)
return G
digraph = graph
def plot(self):
"\n Plots a graph of the finite state machine with labeled\n vertices and labeled edges.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A plot of the graph of the finite state machine.\n\n TESTS::\n\n sage: FiniteStateMachine([('A', 'A', 0)]).plot() # needs sage.plot\n Graphics object consisting of 3 graphics primitives\n "
return self.graph(edge_labels='words_in_out').plot()
def predecessors(self, state, valid_input=None):
"\n Lists all predecessors of a state.\n\n INPUT:\n\n - ``state`` -- the state from which the predecessors should be\n listed.\n\n - ``valid_input`` -- If ``valid_input`` is a list, then we\n only consider transitions whose input labels are contained\n in ``valid_input``. ``state`` has to be a :class:`FSMState`\n (not a label of a state). If input labels of length larger\n than `1` are used, then ``valid_input`` has to be a list of\n lists.\n\n OUTPUT:\n\n A list of states.\n\n EXAMPLES::\n\n sage: A = Transducer([('I', 'A', 'a', 'b'), ('I', 'B', 'b', 'c'),\n ....: ('I', 'C', 'c', 'a'), ('A', 'F', 'b', 'a'),\n ....: ('B', 'F', ['c', 'b'], 'b'), ('C', 'F', 'a', 'c')],\n ....: initial_states=['I'], final_states=['F'])\n sage: A.predecessors(A.state('A'))\n ['A', 'I']\n sage: A.predecessors(A.state('F'), valid_input=['b', 'a'])\n ['F', 'C', 'A', 'I']\n sage: A.predecessors(A.state('F'), valid_input=[['c', 'b'], 'a'])\n ['F', 'C', 'B']\n "
if (valid_input is not None):
valid_list = list()
for input in valid_input:
input_list = input
if (not isinstance(input_list, list)):
input_list = [input]
valid_list.append(input_list)
valid_input = valid_list
unhandeled_direct_predecessors = {s: [] for s in self.states()}
for t in self.transitions():
if ((valid_input is None) or (t.word_in in valid_input)):
unhandeled_direct_predecessors[t.to_state].append(t.from_state)
done = []
open = [state]
while open:
s = open.pop()
candidates = unhandeled_direct_predecessors[s]
if (candidates is not None):
open.extend(candidates)
unhandeled_direct_predecessors[s] = None
done.append(s)
return done
def number_of_words(self, variable=None, base_ring=None):
'\n Return the number of successful input words of given length.\n\n INPUT:\n\n - ``variable`` -- a symbol denoting the length of the words,\n by default `n`.\n\n - ``base_ring`` -- Ring (default: ``QQbar``) in which to\n compute the eigenvalues.\n\n OUTPUT:\n\n A symbolic expression.\n\n EXAMPLES::\n\n sage: NAFpm = Automaton([(0, 0, 0), (0, 1, 1),\n ....: (0, 1, -1), (1, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0, 1])\n sage: N = NAFpm.number_of_words(); N # needs sage.symbolic\n 4/3*2^n - 1/3*(-1)^n\n sage: all(len(list(NAFpm.language(s))) # needs sage.symbolic\n ....: - len(list(NAFpm.language(s-1))) == N.subs(n=s)\n ....: for s in srange(1, 6))\n True\n\n An example with non-rational eigenvalues. By default,\n eigenvalues are elements of the\n :mod:`field of algebraic numbers <sage.rings.qqbar>`. ::\n\n sage: NAFp = Automaton([(0, 0, 0), (0, 1, 1), (1, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0, 1])\n sage: N = NAFp.number_of_words(); N # needs sage.rings.number_field sage.symbolic\n 1.170820393249937?*1.618033988749895?^n\n - 0.1708203932499369?*(-0.618033988749895?)^n\n sage: all(len(list(NAFp.language(s))) # needs sage.rings.number_field sage.symbolic\n ....: - len(list(NAFp.language(s-1))) == N.subs(n=s)\n ....: for s in srange(1, 6))\n True\n\n We specify a suitable ``base_ring`` to obtain a radical\n expression. To do so, we first compute the characteristic\n polynomial and then construct a number field generated by its\n roots. ::\n\n sage: # needs sage.rings.number_field sage.symbolic\n sage: M = NAFp.adjacency_matrix(entry=lambda t: 1)\n sage: M.characteristic_polynomial()\n x^2 - x - 1\n sage: R.<phi> = NumberField(x^2 - x - 1, embedding=1.6)\n sage: N = NAFp.number_of_words(base_ring=R); N\n 1/2*(1/2*sqrt(5) + 1/2)^n*(3*sqrt(1/5) + 1)\n - 1/2*(-1/2*sqrt(5) + 1/2)^n*(3*sqrt(1/5) - 1)\n sage: all(len(list(NAFp.language(s)))\n ....: - len(list(NAFp.language(s-1))) == N.subs(n=s)\n ....: for s in srange(1, 6))\n True\n\n In this special case, we might also use the constant\n :class:`golden_ratio <sage.symbolic.constants.GoldenRatio>`::\n\n sage: # needs sage.rings.number_field sage.symbolic\n sage: R.<phi> = NumberField(x^2-x-1, embedding=golden_ratio)\n sage: N = NAFp.number_of_words(base_ring=R); N\n 1/5*(3*golden_ratio + 1)*golden_ratio^n\n - 1/5*(3*golden_ratio - 4)*(-golden_ratio + 1)^n\n sage: all(len(list(NAFp.language(s)))\n ....: - len(list(NAFp.language(s-1))) == N.subs(n=s)\n ....: for s in srange(1, 6))\n True\n\n The adjacency matrix of the following example is a Jordan\n matrix of size 3 to the eigenvalue 4::\n\n sage: J3 = Automaton([(0, 1, -1), (1, 2, -1)],\n ....: initial_states=[0],\n ....: final_states=[0, 1, 2])\n sage: for i in range(3):\n ....: for j in range(4):\n ....: new_transition = J3.add_transition(i, i, j)\n sage: J3.adjacency_matrix(entry=lambda t: 1)\n [4 1 0]\n [0 4 1]\n [0 0 4]\n sage: N = J3.number_of_words(); N # needs sage.symbolic\n 1/2*4^(n - 2)*(n - 1)*n + 4^(n - 1)*n + 4^n\n sage: all(len(list(J3.language(s))) # needs sage.symbolic\n ....: - len(list(J3.language(s-1))) == N.subs(n=s)\n ....: for s in range(1, 6))\n True\n\n Here is an automaton without cycles, so with eigenvalue `0`. ::\n\n sage: A = Automaton([(j, j+1, 0) for j in range(3)],\n ....: initial_states=[0],\n ....: final_states=list(range(3)))\n sage: A.number_of_words() # needs sage.symbolic\n 1/2*0^(n - 2)*(n - 1)*n + 0^(n - 1)*n + 0^n\n\n TESTS::\n\n sage: A = Automaton([(0, 0, 0), (0, 1, 0)],\n ....: initial_states=[0])\n sage: A.number_of_words() # needs sage.symbolic\n Traceback (most recent call last):\n ...\n NotImplementedError: Finite State Machine must be deterministic.\n '
from sage.modules.free_module_element import vector
from sage.arith.misc import binomial
from sage.symbolic.ring import SR
if (base_ring is None):
from sage.rings.qqbar import QQbar as base_ring
if (variable is None):
variable = SR.symbol('n')
def jordan_block_power(block, exponent):
eigenvalue = SR(block[(0, 0)])
return matrix(block.nrows(), block.nrows(), (lambda i, j: (((eigenvalue ** (exponent - (j - i))) * binomial(exponent, (j - i))) if (j >= i) else 0)))
if (not self.is_deterministic()):
raise NotImplementedError('Finite State Machine must be deterministic.')
left = vector((ZZ(s.is_initial) for s in self.iter_states()))
right = vector((ZZ(s.is_final) for s in self.iter_states()))
A = self.adjacency_matrix(entry=(lambda t: 1))
(J, T) = A.jordan_form(base_ring, transformation=True)
Jpower = matrix.block_diagonal([jordan_block_power(J.subdivision(j, j), variable) for j in range((len(J.subdivisions()[0]) + 1))])
T_inv_right = T.solve_right(right).change_ring(SR)
left_T = (left * T).change_ring(SR)
return ((left_T * Jpower) * T_inv_right)
def asymptotic_moments(self, variable=None):
'\n Return the main terms of expectation and variance of the sum\n of output labels and its covariance with the sum of input\n labels.\n\n INPUT:\n\n - ``variable`` -- a symbol denoting the length of the input,\n by default `n`.\n\n OUTPUT:\n\n A dictionary consisting of\n\n - ``expectation`` -- `e n + \\operatorname{Order}(1)`,\n - ``variance`` -- `v n + \\operatorname{Order}(1)`,\n - ``covariance`` -- `c n + \\operatorname{Order}(1)`\n\n for suitable constants `e`, `v` and `c`.\n\n Assume that all input and output labels are numbers and that\n ``self`` is complete and has only one final component. Assume\n further that this final component is aperiodic. Furthermore,\n assume that there is exactly one initial state and that all\n states are final.\n\n Denote by `X_n` the sum of output labels written by the\n finite state machine when reading a random input word of\n length `n` over the input alphabet (assuming\n equidistribution).\n\n Then the expectation of `X_n` is `en+O(1)`, the variance\n of `X_n` is `vn+O(1)` and the covariance of `X_n` and\n the sum of input labels is `cn+O(1)`, cf. [HKW2015]_,\n Theorem 3.9.\n\n In the case of non-integer input or output labels, performance\n degrades significantly. For rational input and output labels,\n consider rescaling to integers. This limitation comes from the\n fact that determinants over polynomial rings can be computed\n much more efficiently than over the symbolic ring. In fact, we\n compute (parts) of a trivariate generating function where the\n input and output labels are exponents of some indeterminates,\n see [HKW2015]_, Theorem 3.9 for details. If those exponents are\n integers, we can use a polynomial ring.\n\n EXAMPLES:\n\n #. A trivial example: write the negative of the input::\n\n sage: T = Transducer([(0, 0, 0, 0), (0, 0, 1, -1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T([0, 1, 1])\n [0, -1, -1]\n\n sage: # needs sage.symbolic\n sage: moments = T.asymptotic_moments()\n sage: moments[\'expectation\']\n -1/2*n + Order(1)\n sage: moments[\'variance\']\n 1/4*n + Order(1)\n sage: moments[\'covariance\']\n -1/4*n + Order(1)\n\n #. For the case of the Hamming weight of the non-adjacent-form\n (NAF) of integers, cf. the :wikipedia:`Non-adjacent_form`\n and the :ref:`example on recognizing NAFs\n <finite_state_machine_recognizing_NAFs_example>`, the\n following agrees with the results in [HP2007]_.\n\n We first use the transducer to convert the standard binary\n expansion to the NAF given in [HP2007]_. We use the parameter\n ``with_final_word_out`` such that we do not have to add\n sufficiently many trailing zeros::\n\n sage: NAF = Transducer([(0, 0, 0, 0),\n ....: (0, \'.1\', 1, None),\n ....: (\'.1\', 0, 0, [1, 0]),\n ....: (\'.1\', 1, 1, [-1, 0]),\n ....: (1, 1, 1, 0),\n ....: (1, \'.1\', 0, None)],\n ....: initial_states=[0],\n ....: final_states=[0],\n ....: with_final_word_out=[0])\n\n As an example, we compute the NAF of `27` by this\n transducer.\n\n ::\n\n sage: binary_27 = 27.bits()\n sage: binary_27\n [1, 1, 0, 1, 1]\n sage: NAF_27 = NAF(binary_27)\n sage: NAF_27\n [-1, 0, -1, 0, 0, 1, 0]\n sage: ZZ(NAF_27, base=2)\n 27\n\n Next, we are only interested in the Hamming weight::\n\n sage: def weight(state, input):\n ....: if input is None:\n ....: result = 0\n ....: else:\n ....: result = ZZ(input != 0)\n ....: return (0, result)\n sage: weight_transducer = Transducer(weight,\n ....: input_alphabet=[-1, 0, 1],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: NAFweight = weight_transducer.composition(NAF)\n sage: NAFweight.transitions()\n [Transition from (0, 0) to (0, 0): 0|0,\n Transition from (0, 0) to (\'.1\', 0): 1|-,\n Transition from (\'.1\', 0) to (0, 0): 0|1,0,\n Transition from (\'.1\', 0) to (1, 0): 1|1,0,\n Transition from (1, 0) to (\'.1\', 0): 0|-,\n Transition from (1, 0) to (1, 0): 1|0]\n sage: NAFweight(binary_27)\n [1, 0, 1, 0, 0, 1, 0]\n\n Now, we actually compute the asymptotic moments::\n\n sage: # needs sage.symbolic\n sage: moments = NAFweight.asymptotic_moments()\n sage: moments[\'expectation\']\n 1/3*n + Order(1)\n sage: moments[\'variance\']\n 2/27*n + Order(1)\n sage: moments[\'covariance\']\n Order(1)\n\n #. This is Example 3.16 in [HKW2015]_, where a transducer with\n variable output labels is given. There, the aim was to\n choose the output labels of this very simple transducer such\n that the input and output sum are asymptotically\n independent, i.e., the constant `c` vanishes.\n\n ::\n\n sage: # needs sage.symbolic\n sage: var(\'a_1, a_2, a_3, a_4\')\n (a_1, a_2, a_3, a_4)\n sage: T = Transducer([[0, 0, 0, a_1], [0, 1, 1, a_3],\n ....: [1, 0, 0, a_4], [1, 1, 1, a_2]],\n ....: initial_states=[0], final_states=[0, 1])\n sage: moments = T.asymptotic_moments()\n verbose 0 (...) Non-integer output weights lead to\n significant performance degradation.\n sage: moments[\'expectation\']\n 1/4*(a_1 + a_2 + a_3 + a_4)*n + Order(1)\n sage: moments[\'covariance\']\n -1/4*(a_1 - a_2)*n + Order(1)\n\n Therefore, the asymptotic covariance vanishes if and only if\n `a_2=a_1`.\n\n #. This is Example 4.3 in [HKW2015]_, dealing with the\n transducer converting the binary expansion of an integer\n into Gray code (cf. the :wikipedia:`Gray_code` and the\n :ref:`example on Gray code\n <finite_state_machine_gray_code_example>`)::\n\n sage: # needs sage.symbolic\n sage: moments = transducers.GrayCode().asymptotic_moments()\n sage: moments[\'expectation\']\n 1/2*n + Order(1)\n sage: moments[\'variance\']\n 1/4*n + Order(1)\n sage: moments[\'covariance\']\n Order(1)\n\n #. This is the first part of Example 4.4 in [HKW2015]_,\n counting the number of 10 blocks in the standard binary\n expansion. The least significant digit is at the left-most\n position::\n\n sage: block10 = transducers.CountSubblockOccurrences(\n ....: [1, 0],\n ....: input_alphabet=[0, 1])\n sage: sorted(block10.transitions())\n [Transition from () to (): 0|0,\n Transition from () to (1,): 1|0,\n Transition from (1,) to (): 0|1,\n Transition from (1,) to (1,): 1|0]\n\n sage: # needs sage.symbolic\n sage: moments = block10.asymptotic_moments()\n sage: moments[\'expectation\']\n 1/4*n + Order(1)\n sage: moments[\'variance\']\n 1/16*n + Order(1)\n sage: moments[\'covariance\']\n Order(1)\n\n #. This is the second part of Example 4.4 in [HKW2015]_,\n counting the number of 11 blocks in the standard binary\n expansion. The least significant digit is at the left-most\n position::\n\n sage: block11 = transducers.CountSubblockOccurrences(\n ....: [1, 1],\n ....: input_alphabet=[0, 1])\n sage: sorted(block11.transitions())\n [Transition from () to (): 0|0,\n Transition from () to (1,): 1|0,\n Transition from (1,) to (): 0|0,\n Transition from (1,) to (1,): 1|1]\n\n sage: # needs sage.symbolic\n sage: var(\'N\')\n N\n sage: moments = block11.asymptotic_moments(N)\n sage: moments[\'expectation\']\n 1/4*N + Order(1)\n sage: moments[\'variance\']\n 5/16*N + Order(1)\n sage: correlation = (moments[\'covariance\'].coefficient(N) /\n ....: (1/2 * sqrt(moments[\'variance\'].coefficient(N))))\n sage: correlation\n 2/5*sqrt(5)\n\n #. This is Example 4.5 in [HKW2015]_, counting the number of\n 01 blocks minus the number of 10 blocks in the standard binary\n expansion. The least significant digit is at the left-most\n position::\n\n sage: block01 = transducers.CountSubblockOccurrences(\n ....: [0, 1],\n ....: input_alphabet=[0, 1])\n sage: product_01x10 = block01.cartesian_product(block10)\n sage: block_difference = transducers.sub([0, 1])(product_01x10)\n sage: T = block_difference.simplification().relabeled()\n sage: T.transitions()\n [Transition from 0 to 2: 0|-1,\n Transition from 0 to 0: 1|0,\n Transition from 1 to 2: 0|0,\n Transition from 1 to 0: 1|0,\n Transition from 2 to 2: 0|0,\n Transition from 2 to 0: 1|1]\n\n sage: # needs sage.symbolic\n sage: moments = T.asymptotic_moments()\n sage: moments[\'expectation\']\n Order(1)\n sage: moments[\'variance\']\n Order(1)\n sage: moments[\'covariance\']\n Order(1)\n\n #. The finite state machine must have a unique final component::\n\n sage: T = Transducer([(0, -1, -1, -1), (0, 1, 1, 1),\n ....: (-1, -1, -1, -1), (-1, -1, 1, -1),\n ....: (1, 1, -1, 1), (1, 1, 1, 1)],\n ....: initial_states=[0],\n ....: final_states=[0, 1, -1])\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n NotImplementedError: asymptotic_moments is only\n implemented for finite state machines with one final\n component.\n\n In this particular example, the first letter of the input\n decides whether we reach the loop at `-1` or the loop at\n `1`. In the first case, we have `X_n = -n`, while we have\n `X_n = n` in the second case. Therefore, the expectation\n `E(X_n)` of `X_n` is `E(X_n) = 0`. We get `(X_n-E(X_n))^2 =\n n^2` in all cases, which results in a variance of `n^2`.\n\n So this example shows that the variance may be non-linear if\n there is more than one final component.\n\n TESTS:\n\n #. An input alphabet must be given::\n\n sage: T = Transducer([[0, 0, 0, 0]],\n ....: initial_states=[0], final_states=[0],\n ....: determine_alphabets=False)\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n ValueError: No input alphabet is given.\n Try calling determine_alphabets().\n\n #. The finite state machine must have a unique initial state::\n\n sage: T = Transducer([(0, 0, 0, 0)])\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n ValueError: A unique initial state is required.\n\n #. The finite state machine must be complete::\n\n sage: T = Transducer([[0, 0, 0, 0]],\n ....: initial_states=[0], final_states=[0],\n ....: input_alphabet=[0, 1])\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n NotImplementedError: This finite state machine is\n not complete.\n\n #. The final component of the finite state machine must be\n aperiodic::\n\n sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)],\n ....: initial_states=[0], final_states=[0, 1])\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n NotImplementedError: asymptotic_moments is only\n implemented for finite state machines whose unique final\n component is aperiodic.\n\n #. Non-integer input or output labels lead to a warning::\n\n sage: # needs sage.symbolic\n sage: T = Transducer([[0, 0, 0, 0], [0, 0, 1, -1/2]],\n ....: initial_states=[0], final_states=[0])\n sage: moments = T.asymptotic_moments()\n verbose 0 (...) Non-integer output weights lead to\n significant performance degradation.\n sage: moments[\'expectation\']\n -1/4*n + Order(1)\n sage: moments[\'variance\']\n 1/16*n + Order(1)\n sage: moments[\'covariance\']\n -1/8*n + Order(1)\n\n This warning can be silenced by :func:`~sage.misc.verbose.set_verbose`::\n\n sage: # needs sage.symbolic\n sage: from sage.misc.verbose import set_verbose\n sage: set_verbose(-1, "finite_state_machine.py")\n sage: moments = T.asymptotic_moments()\n sage: moments[\'expectation\']\n -1/4*n + Order(1)\n sage: moments[\'variance\']\n 1/16*n + Order(1)\n sage: moments[\'covariance\']\n -1/8*n + Order(1)\n sage: set_verbose(0, "finite_state_machine.py")\n\n #. Check whether ``word_out`` of ``FSMState`` are correctly\n dealt with::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: s = FSMState(0, word_out=2,\n ....: is_initial=True,\n ....: is_final=True)\n sage: T = Transducer([(s, s, 0, 1)],\n ....: initial_states=[s], final_states=[s])\n sage: T([0, 0])\n [2, 1, 2, 1, 2]\n sage: T.asymptotic_moments()[\'expectation\'] # needs sage.symbolic\n 3*n + Order(1)\n\n The same test for non-integer output::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: s = FSMState(0, word_out=2/3)\n sage: T = Transducer([(s, s, 0, 1/2)],\n ....: initial_states=[s], final_states=[s])\n sage: T.asymptotic_moments()[\'expectation\'] # needs sage.symbolic\n verbose 0 (...) Non-integer output weights lead to\n significant performance degradation.\n 7/6*n + Order(1)\n\n #. All states of ``self`` have to be final::\n\n sage: T = Transducer([(0, 1, 1, 4)], initial_states=[0])\n sage: T.asymptotic_moments()\n Traceback (most recent call last):\n ...\n ValueError: Not all states are final.\n\n ALGORITHM:\n\n See [HKW2015]_, Theorem 3.9.\n\n REFERENCES:\n\n .. [HP2007] Clemens Heuberger and Helmut Prodinger, *The Hamming\n Weight of the Non-Adjacent-Form under Various Input Statistics*,\n Periodica Mathematica Hungarica Vol. 55 (1), 2007, pp. 81--96,\n :doi:`10.1007/s10998-007-3081-z`.\n '
if (self.input_alphabet is None):
raise ValueError('No input alphabet is given. Try calling determine_alphabets().')
if (len(self.initial_states()) != 1):
raise ValueError('A unique initial state is required.')
if (not all((state.is_final for state in self.iter_states()))):
raise ValueError('Not all states are final.')
if (not self.is_complete()):
raise NotImplementedError('This finite state machine is not complete.')
final_components = self.final_components()
if (len(final_components) != 1):
raise NotImplementedError('asymptotic_moments is only implemented for finite state machines with one final component.')
final_component = final_components[0]
if (not final_component.digraph().is_aperiodic()):
raise NotImplementedError('asymptotic_moments is only implemented for finite state machines whose unique final component is aperiodic.')
from sage.calculus.functional import derivative
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ
from sage.symbolic.ring import SR
if (variable is None):
variable = SR.symbol('n')
def get_matrix(fsm, x, y):
return fsm.adjacency_matrix(entry=(lambda transition: ((x ** sum(transition.word_in)) * (y ** (sum(transition.word_out) + sum(transition.from_state.word_out))))))
K = len(self.input_alphabet)
R = PolynomialRing(QQ, ('x', 'y', 'z'))
(x, y, z) = R.gens()
try:
M = get_matrix(self, x, y)
except (TypeError, ValueError):
verbose('Non-integer output weights lead to significant performance degradation.', level=0)
R = SR
x = R.symbol()
y = R.symbol()
z = R.symbol()
M = get_matrix(self, x, y)
def substitute_one(g):
return g.subs({x: 1, y: 1, z: 1})
else:
def substitute_one(g):
return g(1, 1, 1)
f = (M.parent().identity_matrix() - ((z / K) * M)).det()
f_x = substitute_one(derivative(f, x))
f_y = substitute_one(derivative(f, y))
f_z = substitute_one(derivative(f, z))
f_xy = substitute_one(derivative(f, x, y))
f_xz = substitute_one(derivative(f, x, z))
f_yz = substitute_one(derivative(f, y, z))
f_yy = substitute_one(derivative(f, y, y))
f_zz = substitute_one(derivative(f, z, z))
e_2 = (f_y / f_z)
v_2 = (((((f_y ** 2) * (f_zz + f_z)) + ((f_z ** 2) * (f_yy + f_y))) - (((2 * f_y) * f_z) * f_yz)) / (f_z ** 3))
c = ((((((f_x * f_y) * (f_zz + f_z)) + ((f_z ** 2) * f_xy)) - ((f_y * f_z) * f_xz)) - ((f_x * f_z) * f_yz)) / (f_z ** 3))
return {'expectation': ((e_2 * variable) + SR(1).Order()), 'variance': ((v_2 * variable) + SR(1).Order()), 'covariance': ((c * variable) + SR(1).Order())}
def moments_waiting_time(self, test=bool, is_zero=None, expectation_only=False):
"\n If this finite state machine acts as a Markov chain, return\n the expectation and variance of the number of steps until\n first writing ``True``.\n\n INPUT:\n\n - ``test`` -- (default: ``bool``) a callable deciding whether\n an output label is to be considered ``True``. By default, the\n standard conversion to boolean is used.\n\n - ``is_zero`` -- (default: ``None``) a callable deciding\n whether an expression for a probability is zero. By default,\n checking for zero is simply done by\n :meth:`~sage.structure.element.Element.is_zero`. This\n parameter can be used to provide a more sophisticated check\n for zero, e.g. in the case of symbolic probabilities, see\n the examples below. This parameter is passed on to\n :meth:`is_Markov_chain`. This parameter only affects the\n input of the Markov chain.\n\n - ``expectation_only`` -- (default: ``False``) if set, the\n variance is not computed (in order to save time). By default,\n the variance is computed.\n\n OUTPUT:\n\n A dictionary (if ``expectation_only=False``) consisting of\n\n - ``expectation``,\n - ``variance``.\n\n Otherwise, just the expectation is returned (no dictionary for\n ``expectation_only=True``).\n\n Expectation and variance of the number of steps until first\n writing ``True`` (as determined by the parameter ``test``).\n\n ALGORITHM:\n\n Relies on a (classical and easy) probabilistic argument,\n cf. [FGT1992]_, Eqns. (6) and (7).\n\n For the variance, see [FHP2015]_, Section 2.\n\n EXAMPLES:\n\n #. The simplest example is to wait for the first `1` in a\n `0`-`1`-string where both digits appear with probability\n `1/2`. In fact, the waiting time equals `k` if and only if\n the string starts with `0^{k-1}1`. This event occurs with\n probability `2^{-k}`. Therefore, the expected waiting time\n and the variance are `\\sum_{k\\ge 1} k2^{-k}=2` and\n `\\sum_{k\\ge 1} (k-2)^2 2^{-k}=2`::\n\n sage: var('k') # needs sage.symbolic\n k\n sage: sum(k * 2^(-k), k, 1, infinity) # needs sage.symbolic\n 2\n sage: sum((k-2)^2 * 2^(-k), k, 1, infinity) # needs sage.symbolic\n 2\n\n We now compute the same expectation and variance by using a\n Markov chain::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: duplicate_transition_add_input)\n sage: T = Transducer(\n ....: [(0, 0, 1/2, 0), (0, 0, 1/2, 1)],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input,\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T.moments_waiting_time()\n {'expectation': 2, 'variance': 2}\n sage: T.moments_waiting_time(expectation_only=True)\n 2\n\n In the following, we replace the output ``0`` by ``-1`` and\n demonstrate the use of the parameter ``test``::\n\n sage: T.delete_transition((0, 0, 1/2, 0))\n sage: T.add_transition((0, 0, 1/2, -1))\n Transition from 0 to 0: 1/2|-1\n sage: T.moments_waiting_time(test=lambda x: x<0)\n {'expectation': 2, 'variance': 2}\n\n #. Make sure that the transducer is actually a Markov\n chain. Although this is checked by the code, unexpected\n behaviour may still occur if the transducer looks like a\n Markov chain. In the following example, we 'forget' to\n assign probabilities, but due to a coincidence, all\n 'probabilities' add up to one. Nevertheless, `0` is never\n written, so the expectation is `1`.\n\n ::\n\n sage: T = Transducer([(0, 0, 0, 0), (0, 0, 1, 1)],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input,\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T.moments_waiting_time()\n {'expectation': 1, 'variance': 0}\n\n #. If ``True`` is never written, the moments are\n ``+Infinity``::\n\n sage: T = Transducer([(0, 0, 1, 0)],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input,\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: T.moments_waiting_time()\n {'expectation': +Infinity, 'variance': +Infinity}\n\n #. Let `h` and `r` be positive integers. We consider random\n strings of letters `1`, `\\ldots`, `r` where the letter `j`\n occurs with probability `p_j`. Let `B` be the random\n variable giving the first position of a block of `h`\n consecutive identical letters. Then\n\n .. MATH::\n\n \\begin{aligned}\n \\mathbb{E}(B)&=\\frac1{\\displaystyle\\sum_{i=1}^r\n \\frac1{p_i^{-1}+\\cdots+p_i^{-h}}},\\\\\n \\mathbb{V}(B)&=\\frac{\\displaystyle\\sum_{i=1}^r\\biggl(\n \\frac{p_i +p_i^h}{1-p_i^h}\n - 2h\\frac{ p_i^h(1-p_i)}{(1-p_i^h)^2}\\biggr)}\n {\\displaystyle\\biggl(\\sum_{i=1}^r\n \\frac1{p_i^{-1}+\\cdots+p_i^{-h}}\\biggr)^2}\n \\end{aligned}\n\n cf. [S1986]_, p. 62, or [FHP2015]_, Theorem 1. We now\n verify this with a transducer approach.\n\n ::\n\n sage: # needs sage.libs.singular\n sage: def test(h, r):\n ....: R = PolynomialRing(\n ....: QQ,\n ....: names=['p_%d' % j for j in range(r)])\n ....: p = R.gens()\n ....: def is_zero(polynomial):\n ....: return polynomial in (sum(p) - 1) * R\n ....: theory_expectation = 1/(sum(1/sum(p[j]^(-i)\n ....: for i in range(1, h+1))\n ....: for j in range(r)))\n ....: theory_variance = sum(\n ....: (p[i] + p[i]^h)/(1 - p[i]^h)\n ....: - 2*h*p[i]^h * (1 - p[i])/(1 - p[i]^h)^2\n ....: for i in range(r)\n ....: ) * theory_expectation^2\n ....: alphabet = list(range(r))\n ....: counters = [\n ....: transducers.CountSubblockOccurrences([j]*h,\n ....: alphabet)\n ....: for j in alphabet]\n ....: all_counter = counters[0].cartesian_product(\n ....: counters[1:])\n ....: adder = transducers.add(input_alphabet=[0, 1],\n ....: number_of_operands=r)\n ....: probabilities = Transducer(\n ....: [(0, 0, p[j], j) for j in alphabet],\n ....: initial_states=[0],\n ....: final_states=[0],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input)\n ....: chain = adder(all_counter(probabilities))\n ....: result = chain.moments_waiting_time(\n ....: is_zero=is_zero)\n ....: return is_zero((result['expectation'] -\n ....: theory_expectation).numerator()) \\\n ....: and \\\n ....: is_zero((result['variance'] -\n ....: theory_variance).numerator())\n sage: test(2, 2)\n True\n sage: test(2, 3)\n True\n sage: test(3, 3)\n True\n\n #. Consider the alphabet `\\{0, \\ldots, r-1\\}`, some `1\\le j\\le\n r` and some `h\\ge 1`. For some probabilities `p_0`,\n `\\ldots`, `p_{r-1}`, we consider infinite words where the\n letters occur independently with the given probabilities.\n The random variable `B_j` is the first position `n` such\n that there exist `j` of the `r` letters having an `h`-run.\n The expectation of `B_j` is given in [FHP2015]_, Theorem 2.\n Here, we verify this result by using transducers::\n\n sage: # needs sage.libs.singular\n sage: def test(h, r, j):\n ....: R = PolynomialRing(\n ....: QQ,\n ....: names=['p_%d' % i for i in range(r)])\n ....: p = R.gens()\n ....: def is_zero(polynomial):\n ....: return polynomial in (sum(p) - 1) * R\n ....: alphabet = list(range(r))\n ....: counters = [\n ....: transducers.Wait([0, 1])(\n ....: transducers.CountSubblockOccurrences(\n ....: [i]*h,\n ....: alphabet))\n ....: for i in alphabet]\n ....: all_counter = counters[0].cartesian_product(\n ....: counters[1:])\n ....: adder = transducers.add(input_alphabet=[0, 1],\n ....: number_of_operands=r)\n ....: threshold = transducers.map(\n ....: f=lambda x: x >= j,\n ....: input_alphabet=srange(r+1))\n ....: probabilities = Transducer(\n ....: [(0, 0, p[i], i) for i in alphabet],\n ....: initial_states=[0],\n ....: final_states=[0],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input)\n ....: chain = threshold(adder(all_counter(\n ....: probabilities)))\n ....: result = chain.moments_waiting_time(\n ....: is_zero=is_zero,\n ....: expectation_only=True)\n ....: R_v = PolynomialRing(\n ....: QQ,\n ....: names=['p_%d' % i for i in range(r)])\n ....: v = R_v.gens()\n ....: S = 1/(1 - sum(v[i]/(1+v[i])\n ....: for i in range(r)))\n ....: alpha = [(p[i] - p[i]^h)/(1 - p[i])\n ....: for i in range(r)]\n ....: gamma = [p[i]/(1 - p[i]) for i in range(r)]\n ....: alphabet_set = set(alphabet)\n ....: expectation = 0\n ....: for q in range(j):\n ....: for M in Subsets(alphabet_set, q):\n ....: summand = S\n ....: for i in M:\n ....: summand = summand.subs(\n ....: {v[i]: gamma[i]}) -\\\n ....: summand.subs({v[i]: alpha[i]})\n ....: for i in alphabet_set - set(M):\n ....: summand = summand.subs(\n ....: {v[i]: alpha[i]})\n ....: expectation += summand\n ....: return is_zero((result - expectation).\\\n ....: numerator())\n sage: test(2, 3, 2)\n True\n\n REFERENCES:\n\n .. [FGT1992] Philippe Flajolet, Danièle Gardy, Loÿs Thimonier,\n *Birthday paradox, coupon collectors, caching algorithms and\n self-organizing search*, Discrete Appl. Math. 39 (1992),\n 207--229, :doi:`10.1016/0166-218X(92)90177-C`.\n\n .. [FHP2015] Uta Freiberg, Clemens Heuberger, Helmut Prodinger,\n *Application of Smirnov Words to Waiting Time Distributions\n of Runs*, :arxiv:`1503.08096`.\n\n .. [S1986] Gábor J. Székely, *Paradoxes in Probability Theory\n and Mathematical Statistics*, D. Reidel Publishing Company.\n\n TESTS:\n\n Only Markov chains are acceptable::\n\n sage: T = transducers.Identity([0, 1, 2])\n sage: T.moments_waiting_time()\n Traceback (most recent call last):\n ...\n ValueError: Only Markov chains can compute\n moments_waiting_time.\n\n There must be a unique initial state::\n\n sage: T = Transducer([(0, 1, 1, 1), (1, 0, 1, 0)],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input)\n sage: T.moments_waiting_time()\n Traceback (most recent call last):\n ...\n ValueError: Unique initial state is required.\n\n Using `0` as initial state in this example, a `1` is written in\n the first step with probability `1`, so the waiting time is\n always `1`::\n\n sage: T.state(0).is_initial = True\n sage: T.moments_waiting_time()\n {'expectation': 1, 'variance': 0}\n\n Using both `0` and `1` as initial states again yields an error\n message::\n\n sage: T.state(1).is_initial = True\n sage: T.moments_waiting_time()\n Traceback (most recent call last):\n ...\n ValueError: Unique initial state is required.\n\n Detection of infinite waiting time for symbolic probabilities::\n\n sage: R.<p, q> = PolynomialRing(QQ)\n sage: T = Transducer([(0, 0, p, 0), (0, 0, q, 0)],\n ....: initial_states=[0],\n ....: on_duplicate_transition=\\\n ....: duplicate_transition_add_input)\n sage: T.moments_waiting_time(\n ....: is_zero=lambda e: e in (p + q - 1)*R)\n {'expectation': +Infinity, 'variance': +Infinity}\n "
from sage.modules.free_module_element import vector
from sage.matrix.constructor import identity_matrix
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
def default_is_zero(expression):
return expression.is_zero()
is_zero_function = default_is_zero
if (is_zero is not None):
is_zero_function = is_zero
if (not self.is_Markov_chain(is_zero)):
raise ValueError('Only Markov chains can compute moments_waiting_time.')
if (len(self.initial_states()) != 1):
raise ValueError('Unique initial state is required.')
def entry(transition):
word_out = transition.word_out
if ((not word_out) or ((len(word_out) == 1) and (not test(word_out[0])))):
return transition.word_in[0]
else:
return 0
relabeled = self.relabeled()
n = len(relabeled.states())
assert ([s.label() for s in relabeled.states()] == list(range(n)))
entry_vector = vector((ZZ(s.is_initial) for s in relabeled.states()))
exit_vector = vector(([1] * n))
transition_matrix = relabeled.adjacency_matrix(entry=entry)
if all(map(is_zero_function, ((transition_matrix * exit_vector) - exit_vector))):
import sage.rings.infinity
expectation = sage.rings.infinity.PlusInfinity()
variance = sage.rings.infinity.PlusInfinity()
elif expectation_only:
system_matrix = (identity_matrix(n) - transition_matrix)
expectation = (entry_vector * system_matrix.solve_right(exit_vector))
else:
base_ring = transition_matrix.parent().base_ring()
from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing
if is_MPolynomialRing(base_ring):
R = PolynomialRing(base_ring.base_ring(), (base_ring.variable_names() + ('Z_waiting_time',)))
else:
R = PolynomialRing(base_ring, 'Z_waiting_time')
Z = R.gens()[(- 1)]
system_matrix = (identity_matrix(n) - (Z * transition_matrix))
G = (entry_vector * system_matrix.solve_right(exit_vector))
expectation = G.subs({Z: 1})
variance = (((2 * G.derivative(Z).subs({Z: 1})) + expectation) - (expectation ** 2))
if expectation_only:
return expectation
else:
return {'expectation': expectation, 'variance': variance}
def is_monochromatic(self):
"\n Check whether the colors of all states are equal.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: G = transducers.GrayCode()\n sage: [s.color for s in G.iter_states()]\n [None, None, None]\n sage: G.is_monochromatic()\n True\n sage: G.state(1).color = 'blue'\n sage: G.is_monochromatic()\n False\n "
return equal((s.color for s in self.iter_states()))
def language(self, max_length=None, **kwargs):
'\n Return all words that can be written by this transducer.\n\n INPUT:\n\n - ``max_length`` -- an integer or ``None`` (default). Only\n output words which come from inputs of length at most\n ``max_length`` will be considered. If ``None``, then this\n iterates over all possible words without length restrictions.\n\n - ``kwargs`` -- will be passed on to the :class:`process\n iterator <FSMProcessIterator>`. See :meth:`process` for a\n description.\n\n OUTPUT:\n\n An iterator.\n\n EXAMPLES::\n\n sage: NAF = Transducer([(\'I\', 0, 0, None), (\'I\', 1, 1, None),\n ....: (0, 0, 0, 0), (0, 1, 1, 0),\n ....: (1, 0, 0, 1), (1, 2, 1, -1),\n ....: (2, 1, 0, 0), (2, 2, 1, 0)],\n ....: initial_states=[\'I\'], final_states=[0],\n ....: input_alphabet=[0, 1])\n sage: sorted(NAF.language(4),\n ....: key=lambda o: (ZZ(o, base=2), len(o)))\n [[], [0], [0, 0], [0, 0, 0],\n [1], [1, 0], [1, 0, 0],\n [0, 1], [0, 1, 0],\n [-1, 0, 1],\n [0, 0, 1],\n [1, 0, 1]]\n\n ::\n\n sage: iterator = NAF.language()\n sage: next(iterator)\n []\n sage: next(iterator)\n [0]\n sage: next(iterator)\n [1]\n sage: next(iterator)\n [0, 0]\n sage: next(iterator)\n [0, 1]\n\n .. SEEALSO::\n\n :meth:`Automaton.language`,\n :meth:`process`.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, 0, \'a\'), (1, 2, 1, \'b\')],\n ....: initial_states=[0], final_states=[0, 1, 2])\n sage: T.determine_alphabets()\n sage: list(T.language(2))\n [[], [\'a\'], [\'a\', \'b\']]\n sage: list(T.language(3))\n [[], [\'a\'], [\'a\', \'b\']]\n sage: from sage.combinat.finite_state_machine import _FSMProcessIteratorAll_\n sage: it = T.iter_process(\n ....: process_iterator_class=_FSMProcessIteratorAll_,\n ....: max_length=3,\n ....: process_all_prefixes_of_input=True)\n sage: for current in it:\n ....: print(current)\n ....: print("finished: {}".format([branch.output for branch in it._finished_]))\n process (1 branch)\n + at state 1\n +-- tape at 1, [[\'a\']]\n finished: [[]]\n process (1 branch)\n + at state 2\n +-- tape at 2, [[\'a\', \'b\']]\n finished: [[], [\'a\']]\n process (0 branches)\n finished: [[], [\'a\'], [\'a\', \'b\']]\n '
kwargs['process_iterator_class'] = _FSMProcessIteratorAll_
kwargs['max_length'] = max_length
kwargs['process_all_prefixes_of_input'] = True
it = self.iter_process(**kwargs)
for _ in it:
for branch in it._finished_:
if branch.accept:
(yield branch.output)
it._finished_ = []
|
def is_Automaton(FSM):
'\n Tests whether or not ``FSM`` inherits from :class:`Automaton`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Automaton\n sage: is_Automaton(FiniteStateMachine())\n False\n sage: is_Automaton(Automaton())\n True\n sage: is_FiniteStateMachine(Automaton())\n True\n '
return isinstance(FSM, Automaton)
|
class Automaton(FiniteStateMachine):
"\n This creates an automaton, which is a finite state machine, whose\n transitions have input labels.\n\n An automaton has additional features like creating a deterministic\n and a minimized automaton.\n\n See class :class:`FiniteStateMachine` for more information.\n\n EXAMPLES:\n\n We can create an automaton recognizing even numbers (given in\n binary and read from left to right) in the following way::\n\n sage: A = Automaton([('P', 'Q', 0), ('P', 'P', 1),\n ....: ('Q', 'P', 1), ('Q', 'Q', 0)],\n ....: initial_states=['P'], final_states=['Q'])\n sage: A\n Automaton with 2 states\n sage: A([0])\n True\n sage: A([1, 1, 0])\n True\n sage: A([1, 0, 1])\n False\n\n Note that the full output of the commands can be obtained by\n calling :meth:`.process` and looks like this::\n\n sage: A.process([1, 0, 1])\n (False, 'P')\n\n TESTS::\n\n sage: Automaton()\n Empty automaton\n "
def __init__(self, *args, **kwargs):
'\n Initialize an automaton. See :class:`Automaton` and its parent\n :class:`FiniteStateMachine` for more information.\n\n TESTS::\n\n sage: Transducer()._allow_composition_\n True\n sage: Automaton()._allow_composition_\n False\n '
super().__init__(*args, **kwargs)
self._allow_composition_ = False
def _repr_(self):
'\n Represents the finite state machine as "Automaton with n\n states" where n is the number of states.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: Automaton()._repr_()\n \'Empty automaton\'\n\n\n TESTS::\n\n sage: A = Automaton()\n sage: A\n Empty automaton\n sage: A.add_state(42)\n 42\n sage: A\n Automaton with 1 state\n sage: A.add_state(43)\n 43\n sage: A\n Automaton with 2 states\n\n '
if (not self._states_):
return 'Empty automaton'
if (len(self._states_) == 1):
return 'Automaton with 1 state'
else:
return ('Automaton with %s states' % len(self._states_))
def _latex_transition_label_(self, transition, format_function=None):
"\n Return the proper transition label.\n\n INPUT:\n\n - ``transition`` -- a transition\n\n - ``format_function`` -- a function formatting the labels\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: F = Automaton([('A', 'B', 1)])\n sage: print(latex(F)) # indirect doctest\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$\\text{\\texttt{A}}$};\n \\node[state] (v1) at (-3.000000, 0.000000) {$\\text{\\texttt{B}}$};\n \\path[->] (v0) edge node[rotate=360.00, anchor=south] {$1$} (v1);\n \\end{tikzpicture}\n\n TESTS::\n\n sage: F = Automaton([('A', 'B', 0, 1)])\n sage: t = F.transitions()[0]\n sage: F._latex_transition_label_(t)\n \\left[0\\right]\n "
if (format_function is None):
format_function = latex
return format_function(transition.word_in)
def intersection(self, other, only_accessible_components=True):
"\n Return a new automaton which accepts an input if it is\n accepted by both given automata.\n\n INPUT:\n\n - ``other`` -- an automaton\n\n - ``only_accessible_components`` -- If ``True`` (default), then\n the result is piped through :meth:`.accessible_components`. If no\n ``new_input_alphabet`` is given, it is determined by\n :meth:`.determine_alphabets`.\n\n OUTPUT:\n\n A new automaton which computes the intersection\n (see below) of the languages of ``self`` and ``other``.\n\n The set of states of the new automaton is the Cartesian product of the\n set of states of both given automata. There is a transition `((A, B),\n (C, D), a)` in the new automaton if there are transitions `(A, C, a)`\n and `(B, D, a)` in the old automata.\n\n The methods :meth:`.intersection` and\n :meth:`.cartesian_product` are the same (for automata).\n\n EXAMPLES::\n\n sage: aut1 = Automaton([('1', '2', 1),\n ....: ('2', '2', 1),\n ....: ('2', '2', 0)],\n ....: initial_states=['1'],\n ....: final_states=['2'],\n ....: determine_alphabets=True)\n sage: aut2 = Automaton([('A', 'A', 1),\n ....: ('A', 'B', 0),\n ....: ('B', 'B', 0),\n ....: ('B', 'A', 1)],\n ....: initial_states=['A'],\n ....: final_states=['B'],\n ....: determine_alphabets=True)\n sage: res = aut1.intersection(aut2)\n sage: (aut1([1, 1]), aut2([1, 1]), res([1, 1]))\n (True, False, False)\n sage: (aut1([1, 0]), aut2([1, 0]), res([1, 0]))\n (True, True, True)\n sage: res.transitions()\n [Transition from ('1', 'A') to ('2', 'A'): 1|-,\n Transition from ('2', 'A') to ('2', 'B'): 0|-,\n Transition from ('2', 'A') to ('2', 'A'): 1|-,\n Transition from ('2', 'B') to ('2', 'B'): 0|-,\n Transition from ('2', 'B') to ('2', 'A'): 1|-]\n\n For automata with epsilon-transitions, intersection is not well\n defined. But for any finite state machine, epsilon-transitions can be\n removed by :meth:`.remove_epsilon_transitions`.\n\n ::\n\n sage: a1 = Automaton([(0, 0, 0),\n ....: (0, 1, None),\n ....: (1, 1, 1),\n ....: (1, 2, 1)],\n ....: initial_states=[0],\n ....: final_states=[1],\n ....: determine_alphabets=True)\n sage: a2 = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 1)],\n ....: initial_states=[0],\n ....: final_states=[1],\n ....: determine_alphabets=True)\n sage: a1.intersection(a2)\n Traceback (most recent call last):\n ...\n ValueError: An epsilon-transition (with empty input)\n was found.\n sage: a1.remove_epsilon_transitions() # not tested (since not implemented yet)\n sage: a1.intersection(a2) # not tested\n "
if (not is_Automaton(other)):
raise TypeError('Only an automaton can be intersected with an automaton.')
def function(transition1, transition2):
if ((not transition1.word_in) or (not transition2.word_in)):
raise ValueError('An epsilon-transition (with empty input) was found.')
if (transition1.word_in == transition2.word_in):
return (transition1.word_in, None)
else:
raise LookupError
return self.product_FiniteStateMachine(other, function, only_accessible_components=only_accessible_components)
cartesian_product = intersection
def determinisation(self):
"\n Return a deterministic automaton which accepts the same input\n words as the original one.\n\n OUTPUT:\n\n A new automaton, which is deterministic.\n\n The labels of the states of the new automaton are frozensets\n of states of ``self``. The color of a new state is the\n frozenset of colors of the constituent states of ``self``.\n Therefore, the colors of the constituent states have to be\n hashable. However, if all constituent states have color\n ``None``, then the resulting color is ``None``, too.\n\n The input alphabet must be specified.\n\n EXAMPLES::\n\n sage: aut = Automaton([('A', 'A', 0), ('A', 'B', 1), ('B', 'B', 1)],\n ....: initial_states=['A'], final_states=['B'])\n sage: aut.determinisation().transitions()\n [Transition from frozenset({'A'}) to frozenset({'A'}): 0|-,\n Transition from frozenset({'A'}) to frozenset({'B'}): 1|-,\n Transition from frozenset({'B'}) to frozenset(): 0|-,\n Transition from frozenset({'B'}) to frozenset({'B'}): 1|-,\n Transition from frozenset() to frozenset(): 0|-,\n Transition from frozenset() to frozenset(): 1|-]\n\n ::\n\n sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1),\n ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)],\n ....: initial_states=['A'], final_states=['C'])\n sage: A.determinisation().states()\n [frozenset({'A'}),\n frozenset({'A', 'B'}),\n frozenset({'A', 'C'}),\n frozenset({'A', 'B', 'C'})]\n\n ::\n\n sage: A = Automaton([(0, 1, 1), (0, 2, [1, 1]), (0, 3, [1, 1, 1]),\n ....: (1, 0, -1), (2, 0, -2), (3, 0, -3)],\n ....: initial_states=[0], final_states=[0, 1, 2, 3])\n sage: B = A.determinisation().relabeled().coaccessible_components()\n sage: sorted(B.transitions())\n [Transition from 0 to 1: 1|-,\n Transition from 1 to 0: -1|-,\n Transition from 1 to 3: 1|-,\n Transition from 3 to 0: -2|-,\n Transition from 3 to 4: 1|-,\n Transition from 4 to 0: -3|-]\n\n Note that colors of states have to be hashable::\n\n sage: A = Automaton([[0, 0, 0]], initial_states=[0])\n sage: A.state(0).color = []\n sage: A.determinisation()\n Traceback (most recent call last):\n ...\n TypeError: unhashable type: 'list'\n sage: A.state(0).color = ()\n sage: A.determinisation()\n Automaton with 1 state\n\n If the colors of all constituent states are ``None``,\n the resulting color is ``None``, too (:trac:`19199`)::\n\n sage: A = Automaton([(0, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: [s.color for s in A.determinisation().iter_states()]\n [None]\n\n TESTS:\n\n This is from :trac:`15078`, comment 13.\n\n ::\n\n sage: D = {'A': [('A', 'a'), ('B', 'a'), ('A', 'b')],\n ....: 'C': [], 'B': [('C', 'b')]}\n sage: auto = Automaton(D, initial_states=['A'], final_states=['C'])\n sage: auto.is_deterministic()\n False\n sage: auto.process(list('aaab'))\n [(False, 'A'), (True, 'C')]\n sage: auto.states()\n ['A', 'C', 'B']\n sage: Ddet = auto.determinisation()\n sage: Ddet\n Automaton with 3 states\n sage: Ddet.is_deterministic()\n True\n sage: sorted(Ddet.transitions())\n [Transition from frozenset({'A'}) to frozenset({'A', 'B'}): 'a'|-,\n Transition from frozenset({'A'}) to frozenset({'A'}): 'b'|-,\n Transition from frozenset({'A', 'B'}) to frozenset({'A', 'B'}): 'a'|-,\n Transition from frozenset({'A', 'B'}) to frozenset({'A', 'C'}): 'b'|-,\n Transition from frozenset({'A', 'C'}) to frozenset({'A', 'B'}): 'a'|-,\n Transition from frozenset({'A', 'C'}) to frozenset({'A'}): 'b'|-]\n sage: Ddet.initial_states()\n [frozenset({'A'})]\n sage: Ddet.final_states()\n [frozenset({'A', 'C'})]\n sage: Ddet.process(list('aaab'))\n (True, frozenset({'A', 'C'}))\n\n Test that :trac:`18992` is fixed::\n\n sage: A = Automaton([(0, 1, []), (1, 1, 0)],\n ....: initial_states=[0], final_states=[1])\n sage: B = A.determinisation()\n sage: B.initial_states()\n [frozenset({0, 1})]\n sage: B.final_states()\n [frozenset({0, 1}), frozenset({1})]\n sage: B.transitions()\n [Transition from frozenset({0, 1}) to frozenset({1}): 0|-,\n Transition from frozenset({1}) to frozenset({1}): 0|-]\n sage: C = B.minimization().relabeled()\n sage: C.initial_states()\n [0]\n sage: C.final_states()\n [0]\n sage: C.transitions()\n [Transition from 0 to 0: 0|-]\n "
if any(((len(t.word_in) > 1) for t in self.iter_transitions())):
return self.split_transitions().determinisation()
epsilon_successors = {}
direct_epsilon_successors = {}
for state in self.iter_states():
direct_epsilon_successors[state] = set((t.to_state for t in self.iter_transitions(state) if (not t.word_in)))
epsilon_successors[state] = set([state])
old_count_epsilon_successors = 0
count_epsilon_successors = len(epsilon_successors)
while (old_count_epsilon_successors < count_epsilon_successors):
old_count_epsilon_successors = count_epsilon_successors
count_epsilon_successors = 0
for state in self.iter_states():
for direct_successor in direct_epsilon_successors[state]:
epsilon_successors[state] = epsilon_successors[state].union(epsilon_successors[direct_successor])
count_epsilon_successors += len(epsilon_successors[state])
def set_transition(states, letter):
result = set()
for state in states:
for transition in self.iter_transitions(state):
if (transition.word_in == [letter]):
result.add(transition.to_state)
result = result.union(*(epsilon_successors[s] for s in result))
return (frozenset(result), [])
result = self.empty_copy()
new_initial_states = [frozenset(set().union(*(epsilon_successors[s] for s in self.iter_initial_states())))]
result.add_from_transition_function(set_transition, initial_states=new_initial_states)
for state in result.iter_states():
state.is_final = any((s.is_final for s in state.label()))
if all(((s.color is None) for s in state.label())):
state.color = None
else:
state.color = frozenset((s.color for s in state.label()))
return result
def minimization(self, algorithm=None):
"\n Return the minimization of the input automaton as a new automaton.\n\n INPUT:\n\n - ``algorithm`` -- Either Moore's algorithm (by\n ``algorithm='Moore'`` or as default for deterministic\n automata) or Brzozowski's algorithm (when\n ``algorithm='Brzozowski'`` or when the automaton is not\n deterministic) is used.\n\n OUTPUT:\n\n A new automaton.\n\n The resulting automaton is deterministic and has a minimal\n number of states.\n\n EXAMPLES::\n\n sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1),\n ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)],\n ....: initial_states=['A'], final_states=['C'])\n sage: B = A.minimization(algorithm='Brzozowski')\n sage: B_trans = B.transitions(B.states()[1])\n sage: B_trans # random\n [Transition from frozenset({frozenset({'B', 'C'}),\n frozenset({'A', 'C'}),\n frozenset({'A', 'B', 'C'})})\n to frozenset({frozenset({'C'}),\n frozenset({'B', 'C'}),\n frozenset({'A', 'C'}),\n frozenset({'A', 'B', 'C'})}):\n 0|-,\n Transition from frozenset({frozenset({'B', 'C'}),\n frozenset({'A', 'C'}),\n frozenset({'A', 'B', 'C'})})\n to frozenset({frozenset({'B', 'C'}),\n frozenset({'A', 'C'}),\n frozenset({'A', 'B', 'C'})}):\n 1|-]\n sage: len(B.states())\n 3\n sage: C = A.minimization(algorithm='Brzozowski')\n sage: C_trans = C.transitions(C.states()[1])\n sage: B_trans == C_trans\n True\n sage: len(C.states())\n 3\n\n ::\n\n sage: aut = Automaton([('1', '2', 'a'), ('2', '3', 'b'),\n ....: ('3', '2', 'a'), ('2', '1', 'b'),\n ....: ('3', '4', 'a'), ('4', '3', 'b')],\n ....: initial_states=['1'], final_states=['1'])\n sage: min = aut.minimization(algorithm='Brzozowski')\n sage: [len(min.states()), len(aut.states())]\n [3, 4]\n sage: min = aut.minimization(algorithm='Moore')\n Traceback (most recent call last):\n ...\n NotImplementedError: Minimization via Moore's Algorithm is only\n implemented for deterministic finite state machines\n "
deterministic = self.is_deterministic()
if ((algorithm == 'Moore') or ((algorithm is None) and deterministic)):
return self._minimization_Moore_()
elif ((algorithm == 'Brzozowski') or ((algorithm is None) and (not deterministic))):
return self._minimization_Brzozowski_()
else:
raise NotImplementedError(("Algorithm '%s' is not implemented. Choose 'Moore' or 'Brzozowski'" % algorithm))
def _minimization_Brzozowski_(self):
"\n Return a minimized automaton by using Brzozowski's algorithm.\n\n See also :meth:`.minimization`.\n\n TESTS::\n\n sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1),\n ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)],\n ....: initial_states=['A'], final_states=['C'])\n sage: B = A._minimization_Brzozowski_()\n sage: len(B.states())\n 3\n "
return self.transposition().determinisation().transposition().determinisation()
def _minimization_Moore_(self):
"\n Return a minimized automaton by using Moore's algorithm.\n\n See also :meth:`.minimization`.\n\n TESTS::\n\n sage: aut = Automaton([('1', '2', 'a'), ('2', '3', 'b'),\n ....: ('3', '2', 'a'), ('2', '1', 'b'),\n ....: ('3', '4', 'a'), ('4', '3', 'b')],\n ....: initial_states=['1'], final_states=['1'])\n sage: min = aut._minimization_Moore_()\n Traceback (most recent call last):\n ...\n NotImplementedError: Minimization via Moore's Algorithm is only\n implemented for deterministic finite state machines\n "
if self.is_deterministic():
return self.quotient(self.equivalence_classes())
else:
raise NotImplementedError("Minimization via Moore's Algorithm is only implemented for deterministic finite state machines")
def complement(self):
'\n Return the complement of this automaton.\n\n OUTPUT:\n\n An :class:`Automaton`.\n\n If this automaton recognizes language `\\mathcal{L}` over an\n input alphabet `\\mathcal{A}`, then the complement recognizes\n `\\mathcal{A}\\setminus\\mathcal{L}`.\n\n EXAMPLES::\n\n sage: A = automata.Word([0, 1])\n sage: [w for w in ([], [0], [1], [0, 0], [0, 1], [1, 0], [1, 1])\n ....: if A(w)]\n [[0, 1]]\n sage: Ac = A.complement()\n sage: Ac.transitions()\n [Transition from 0 to 1: 0|-,\n Transition from 0 to 3: 1|-,\n Transition from 2 to 3: 0|-,\n Transition from 2 to 3: 1|-,\n Transition from 1 to 2: 1|-,\n Transition from 1 to 3: 0|-,\n Transition from 3 to 3: 0|-,\n Transition from 3 to 3: 1|-]\n sage: [w for w in ([], [0], [1], [0, 0], [0, 1], [1, 0], [1, 1])\n ....: if Ac(w)]\n [[], [0], [1], [0, 0], [1, 0], [1, 1]]\n\n The automaton must be deterministic::\n\n sage: A = automata.Word([0]) * automata.Word([1])\n sage: A.complement()\n Traceback (most recent call last):\n ...\n ValueError: The finite state machine must be deterministic.\n sage: Ac = A.determinisation().complement()\n sage: [w for w in ([], [0], [1], [0, 0], [0, 1], [1, 0], [1, 1])\n ....: if Ac(w)]\n [[], [0], [1], [0, 0], [1, 0], [1, 1]]\n '
result = self.completion()
for state in result.iter_states():
state.is_final = (not state.is_final)
return result
def is_equivalent(self, other):
"\n Test whether two automata are equivalent, i.e., accept the same\n language.\n\n INPUT:\n\n - ``other`` -- an :class:`Automaton`.\n\n EXAMPLES::\n\n sage: A = Automaton([(0, 0, 0), (0, 1, 1), (1, 0, 1)],\n ....: initial_states=[0],\n ....: final_states=[0])\n sage: B = Automaton([('a', 'a', 0), ('a', 'b', 1), ('b', 'a', 1)],\n ....: initial_states=['a'],\n ....: final_states=['a'])\n sage: A.is_equivalent(B)\n True\n sage: B.add_transition('b', 'a', 0)\n Transition from 'b' to 'a': 0|-\n sage: A.is_equivalent(B)\n False\n "
A = self.minimization().relabeled()
[initial] = A.initial_states()
address = {initial: ()}
for v in A.digraph().breadth_first_search(initial.label()):
state = A.state(v)
state_address = address[state]
for t in A.iter_transitions(state):
if (t.to_state not in address):
address[t.to_state] = (state_address + tuple(t.word_in))
B = other.minimization().relabeled()
labels = {B.process(path)[1].label(): state.label() for (state, path) in address.items()}
try:
return (A == B.relabeled(labels=labels))
except KeyError:
return False
def process(self, *args, **kwargs):
"\n Return whether the automaton accepts the input and the state\n where the computation stops.\n\n INPUT:\n\n - ``input_tape`` -- the input tape can be a list or an\n iterable with entries from the input alphabet. If we are\n working with a multi-tape machine (see parameter\n ``use_multitape_input`` and notes below), then the tape is a\n list or tuple of tracks, each of which can be a list or an\n iterable with entries from the input alphabet.\n\n - ``initial_state`` or ``initial_states`` -- the initial\n state(s) in which the machine starts. Either specify a\n single one with ``initial_state`` or a list of them with\n ``initial_states``. If both are given, ``initial_state``\n will be appended to ``initial_states``. If neither is\n specified, the initial states of the finite state machine\n are taken.\n\n - ``list_of_outputs`` -- (default: ``None``) a boolean or\n ``None``. If ``True``, then the outputs are given in list form\n (even if we have no or only one single output). If\n ``False``, then the result is never a list (an exception is\n raised if the result cannot be returned). If\n ``list_of_outputs=None`` the method determines automatically\n what to do (e.g. if a non-deterministic machine returns more\n than one path, then the output is returned in list form).\n\n - ``only_accepted`` -- (default: ``False``) a boolean. If set,\n then the first argument in the output is guaranteed to be\n ``True`` (if the output is a list, then the first argument\n of each element will be ``True``).\n\n - ``full_output`` -- (default: ``True``) a boolean. If set,\n then the full output is given, otherwise only whether the\n sequence is accepted or not (the first entry below only).\n\n - ``always_include_output`` -- if set (not by default), always\n return a triple containing the (non-existing) output. This\n is in order to obtain output compatible with that of\n :meth:`FiniteStateMachine.process`. If this parameter is set,\n ``full_output`` has no effect.\n\n - ``format_output`` -- a function that translates the written\n output (which is in form of a list) to something more\n readable. By default (``None``) identity is used here.\n\n - ``check_epsilon_transitions`` -- (default: ``True``) a\n boolean. If ``False``, then epsilon transitions are not\n taken into consideration during process.\n\n - ``write_final_word_out`` -- (default: ``True``) a boolean\n specifying whether the final output words should be written\n or not.\n\n - ``use_multitape_input`` -- (default: ``False``) a\n boolean. If ``True``, then the multi-tape mode of the\n process iterator is activated. See also the notes below for\n multi-tape machines.\n\n - ``process_all_prefixes_of_input`` -- (default: ``False``) a\n boolean. If ``True``, then each prefix of the input word is\n processed (instead of processing the whole input word at\n once). Consequently, there is an output generated for each\n of these prefixes.\n\n - ``process_iterator_class`` -- (default: ``None``) a class\n inherited from :class:`FSMProcessIterator`. If ``None``,\n then :class:`FSMProcessIterator` is taken. An instance of this\n class is created and is used during the processing.\n\n OUTPUT:\n\n The full output is a pair (or a list of pairs,\n cf. parameter ``list_of_outputs``), where\n\n - the first entry is ``True`` if the input string is accepted and\n\n - the second gives the state reached after processing the\n input tape (This is a state with label ``None`` if the input\n could not be processed, i.e., if at one point no\n transition to go on could be found.).\n\n If ``full_output`` is ``False``, then only the first entry\n is returned.\n\n If ``always_include_output`` is set, an additional third entry\n ``[]`` is included.\n\n Note that in the case the automaton is not\n deterministic, all possible paths are taken into account.\n You can use :meth:`.determinisation` to get a deterministic\n automaton machine.\n\n This function uses an iterator which, in its simplest form, goes\n from one state to another in each step. To decide which way to\n go, it uses the input words of the outgoing transitions and\n compares them to the input tape. More precisely, in each step,\n the iterator takes an outgoing transition of the current state,\n whose input label equals the input letter of the tape.\n\n If the choice of the outgoing transition is not unique (i.e.,\n we have a non-deterministic finite state machine), all\n possibilities are followed. This is done by splitting the\n process into several branches, one for each of the possible\n outgoing transitions.\n\n The process (iteration) stops if all branches are finished,\n i.e., for no branch, there is any transition whose input word\n coincides with the processed input tape. This can simply\n happen when the entire tape was read.\n\n Also see :meth:`~FiniteStateMachine.__call__` for a\n version of :meth:`.process` with shortened output.\n\n Internally this function creates and works with an instance of\n :class:`FSMProcessIterator`. This iterator can also be obtained\n with :meth:`~FiniteStateMachine.iter_process`.\n\n If working with multi-tape finite state machines, all input\n words of transitions are words of `k`-tuples of letters.\n Moreover, the input tape has to consist of `k` tracks, i.e.,\n be a list or tuple of `k` iterators, one for each track.\n\n .. WARNING::\n\n Working with multi-tape finite state machines is still\n experimental and can lead to wrong outputs.\n\n EXAMPLES:\n\n In the following examples, we construct an automaton which\n accepts non-adjacent forms (see also the example on\n :ref:`non-adjacent forms <finite_state_machine_recognizing_NAFs_example>`\n in the documentation of the module\n :doc:`finite_state_machine`)\n and then test it by feeding it with several binary digit\n expansions.\n\n ::\n\n sage: NAF = Automaton(\n ....: {'_': [('_', 0), ('1', 1)], '1': [('_', 0)]},\n ....: initial_states=['_'], final_states=['_', '1'])\n sage: [NAF.process(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],\n ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]\n [(True, '_'), (True, '1'), (False, None),\n (True, '1'), (False, None), (False, None)]\n\n If we just want a condensed output, we use::\n\n sage: [NAF.process(w, full_output=False)\n ....: for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],\n ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]\n [True, True, False, True, False, False]\n\n It is equivalent to::\n\n sage: [NAF(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1],\n ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]]\n [True, True, False, True, False, False]\n\n The following example illustrates the difference between\n non-existing paths and reaching a non-final state::\n\n sage: NAF.process([2])\n (False, None)\n sage: NAF.add_transition(('_', 's', 2))\n Transition from '_' to 's': 2|-\n sage: NAF.process([2])\n (False, 's')\n\n A simple example of a (non-deterministic) multi-tape automaton is the\n following: It checks whether the two input tapes have the same number\n of ones::\n\n sage: M = Automaton([('=', '=', (1, 1)),\n ....: ('=', '=', (None, 0)),\n ....: ('=', '=', (0, None)),\n ....: ('=', '<', (None, 1)),\n ....: ('<', '<', (None, 1)),\n ....: ('<', '<', (None, 0)),\n ....: ('=', '>', (1, None)),\n ....: ('>', '>', (1, None)),\n ....: ('>', '>', (0, None))],\n ....: initial_states=['='],\n ....: final_states=['='])\n sage: M.process(([1, 0, 1], [1, 0]), use_multitape_input=True)\n (False, '>')\n sage: M.process(([0, 1, 0], [0, 1, 1]), use_multitape_input=True)\n (False, '<')\n sage: M.process(([1, 1, 0, 1], [0, 0, 1, 0, 1, 1]),\n ....: use_multitape_input=True)\n (True, '=')\n\n Alternatively, we can use the following (non-deterministic)\n multi-tape automaton for the same check::\n\n sage: N = Automaton([('=', '=', (0, 0)),\n ....: ('=', '<', (None, 1)),\n ....: ('<', '<', (0, None)),\n ....: ('<', '=', (1, None)),\n ....: ('=', '>', (1, None)),\n ....: ('>', '>', (None, 0)),\n ....: ('>', '=', (None, 1))],\n ....: initial_states=['='],\n ....: final_states=['='])\n sage: N.process(([1, 0, 1], [1, 0]), use_multitape_input=True)\n (False, '>')\n sage: N.process(([0, 1, 0], [0, 1, 1]), use_multitape_input=True)\n (False, '<')\n sage: N.process(([1, 1, 0, 1], [0, 0, 1, 0, 1, 1]),\n ....: use_multitape_input=True)\n (True, '=')\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.process`,\n :meth:`Transducer.process`,\n :meth:`~FiniteStateMachine.iter_process`,\n :meth:`~FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n "
options = copy(self._process_default_options_)
options.update(kwargs)
condensed_output = ((options['list_of_outputs'] is False) and (not options['full_output']))
if condensed_output:
options['list_of_outputs'] = True
options['only_accepted'] = True
result = super().process(*args, **options)
if condensed_output:
return any(result)
return result
def _process_convert_output_(self, output_data, **kwargs):
"\n Helper function which converts the output of\n :meth:`FiniteStateMachine.process` to one suitable for\n automata.\n\n INPUT:\n\n - ``output_data`` -- a triple.\n\n - ``full_output`` -- a boolean.\n\n - ``always_include_output`` -- if set (not by default), always\n return a triple containing the (non-existing) output. This\n is for compatibility with transducers.\n\n OUTPUT:\n\n The converted output.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = Automaton()\n sage: A._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=False,\n ....: always_include_output=False)\n True\n sage: A._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=True,\n ....: always_include_output=False)\n (True, 'a')\n sage: A._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=False,\n ....: always_include_output=True)\n (True, 'a', [1, 0, 1])\n "
if kwargs['always_include_output']:
return super()._process_convert_output_(output_data, **kwargs)
(accept_input, current_state, _) = output_data
if kwargs['full_output']:
return (accept_input, current_state)
else:
return accept_input
def shannon_parry_markov_chain(self):
'\n Compute a time homogeneous Markov chain such that all words of a\n given length recognized by the original automaton occur as the\n output with the same weight; the transition probabilities\n correspond to the Parry measure.\n\n OUTPUT:\n\n A Markov chain. Its input labels are the transition probabilities, the\n output labels the labels of the original automaton. In order to obtain\n equal weight for all words of the same length, an "exit weight" is\n needed. It is stored in the attribute ``color`` of the states of the\n Markov chain. The weights of the words of the same length sum up to one\n up to an exponentially small error.\n\n The stationary distribution of this Markov chain is\n saved as the initial probabilities of the states.\n\n The transition probabilities correspond to the Parry measure\n (see [S1948]_ and [P1964]_).\n\n The automaton is assumed to be deterministic, irreducible and\n aperiodic. All states must be final.\n\n EXAMPLES::\n\n sage: NAF = Automaton([(0, 0, 0), (0, 1, 1), (0, 1, -1),\n ....: (1, 0, 0)], initial_states=[0],\n ....: final_states=[0, 1])\n sage: P_NAF = NAF.shannon_parry_markov_chain() # needs sage.symbolic\n sage: P_NAF.transitions() # needs sage.symbolic\n [Transition from 0 to 0: 1/2|0,\n Transition from 0 to 1: 1/4|1,\n Transition from 0 to 1: 1/4|-1,\n Transition from 1 to 0: 1|0]\n sage: for s in P_NAF.iter_states(): # needs sage.symbolic\n ....: print(s.color)\n 3/4\n 3/2\n\n The stationary distribution is also computed and saved as the\n initial probabilities of the returned Markov chain::\n\n sage: for s in P_NAF.states(): # needs sage.symbolic\n ....: print("{} {}".format(s, s.initial_probability))\n 0 2/3\n 1 1/3\n\n The automaton is assumed to be deterministic, irreducible and aperiodic::\n\n sage: A = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)],\n ....: initial_states=[0])\n sage: A.shannon_parry_markov_chain()\n Traceback (most recent call last):\n ...\n NotImplementedError: Automaton must be strongly connected.\n sage: A = Automaton([(0, 0, 0), (0, 1, 0)],\n ....: initial_states=[0])\n sage: A.shannon_parry_markov_chain()\n Traceback (most recent call last):\n ...\n NotImplementedError: Automaton must be deterministic.\n sage: A = Automaton([(0, 1, 0), (1, 0, 0)],\n ....: initial_states=[0])\n sage: A.shannon_parry_markov_chain()\n Traceback (most recent call last):\n ...\n NotImplementedError: Automaton must be aperiodic.\n\n All states must be final::\n\n sage: A = Automaton([(0, 1, 0), (0, 0, 1), (1, 0, 0)],\n ....: initial_states=[0])\n sage: A.shannon_parry_markov_chain()\n Traceback (most recent call last):\n ...\n NotImplementedError: All states must be final.\n\n ALGORITHM:\n\n See [HKP2015a]_, Lemma 4.1.\n\n REFERENCES:\n\n .. [HKP2015a] Clemens Heuberger, Sara Kropf, and Helmut\n Prodinger, *Analysis of Carries in Signed Digit Expansions*,\n :arxiv:`1503.08816`.\n .. [P1964] William Parry, *Intrinsic Markov chains*, Transactions\n of the American Mathematical Society 112, 1964, pp. 55-66.\n :doi:`10.1090/S0002-9947-1964-0161372-1`.\n .. [S1948] Claude E. Shannon, *A mathematical theory of communication*,\n The Bell System Technical Journal 27, 1948, 379-423,\n :doi:`10.1002/j.1538-7305.1948.tb01338.x`.\n '
from sage.modules.free_module_element import vector
if (not self.is_deterministic()):
raise NotImplementedError('Automaton must be deterministic.')
if (not self.digraph().is_aperiodic()):
raise NotImplementedError('Automaton must be aperiodic.')
if (not self.digraph().is_strongly_connected()):
raise NotImplementedError('Automaton must be strongly connected.')
if (not all((s.is_final for s in self.iter_states()))):
raise NotImplementedError('All states must be final.')
M = self.adjacency_matrix().change_ring(ZZ)
states = {state: i for (i, state) in enumerate(self.iter_states())}
w_all = sorted(M.eigenvectors_right(), key=(lambda x: abs(x[0])), reverse=True)
w = w_all[0][1][0]
mu = w_all[0][0]
u_all = sorted(M.eigenvectors_left(), key=(lambda x: abs(x[0])), reverse=True)
u = u_all[0][1][0]
u = ((1 / (u * w)) * u)
final = vector((int(s.is_final) for s in self.iter_states()))
ff = (u * final)
assert ((u * w) == 1)
P = Transducer(initial_states=[s.label() for s in self.iter_initial_states()], final_states=[s.label() for s in self.iter_final_states()], on_duplicate_transition=duplicate_transition_add_input)
for t in self.iter_transitions():
P.add_transition(t.from_state.label(), t.to_state.label(), ((w[states[t.to_state]] / w[states[t.from_state]]) / mu), t.word_in)
for s in self.iter_states():
P.state(s.label()).color = (1 / (w[states[s]] * ff))
P.state(s.label()).initial_probability = (w[states[s]] * u[states[s]])
return P
def with_output(self, word_out_function=None):
"\n Construct a transducer out of this automaton.\n\n INPUT:\n\n - ``word_out_function`` -- (default: ``None``) a function. It\n transforms a :class:`transition <FSMTransition>` to the\n output word for this transition.\n\n If this is ``None``, then the output word will be equal to\n the input word of each transition.\n\n OUTPUT:\n\n A transducer.\n\n EXAMPLES::\n\n sage: A = Automaton([(0, 0, 'A'), (0, 1, 'B'), (1, 2, 'C')])\n sage: T = A.with_output(); T\n Transducer with 3 states\n sage: T.transitions()\n [Transition from 0 to 0: 'A'|'A',\n Transition from 0 to 1: 'B'|'B',\n Transition from 1 to 2: 'C'|'C']\n\n This result is in contrast to::\n\n sage: Transducer(A).transitions()\n [Transition from 0 to 0: 'A'|-,\n Transition from 0 to 1: 'B'|-,\n Transition from 1 to 2: 'C'|-]\n\n where no output labels are created.\n\n Here is another example::\n\n sage: T2 = A.with_output(lambda t: [c.lower() for c in t.word_in])\n sage: T2.transitions()\n [Transition from 0 to 0: 'A'|'a',\n Transition from 0 to 1: 'B'|'b',\n Transition from 1 to 2: 'C'|'c']\n\n We can obtain the same result by composing two transducers. As inner\n transducer of the composition, we use :meth:`.with_output`\n without the optional argument\n ``word_out_function`` (which makes the output of each\n transition equal to its input); as outer transducer we use a\n :meth:`map-transducer\n <sage.combinat.finite_state_machine_generators.TransducerGenerators.map>`\n (for converting to lower case).\n This gives\n\n ::\n\n sage: L = transducers.map(lambda x: x.lower(), ['A', 'B', 'C'])\n sage: L.composition(A.with_output()).relabeled().transitions()\n [Transition from 0 to 0: 'A'|'a',\n Transition from 0 to 1: 'B'|'b',\n Transition from 1 to 2: 'C'|'c']\n\n .. SEEALSO::\n\n :meth:`.input_projection`,\n :meth:`.output_projection`,\n :class:`Transducer`,\n :meth:`transducers.map()\n <sage.combinat.finite_state_machine_generators.TransducerGenerators.map>`.\n\n TESTS::\n\n sage: A.with_output().input_projection() == A\n True\n sage: NAF = Automaton(\n ....: {'A': [('A', 0), ('B', 1), ('B', -1)], 'B': [('A', 0)]})\n sage: NAF.with_output().input_projection() == NAF\n True\n sage: B = Automaton(\n ....: {0: [(0, 'a'), (1, ['b', 'c']), (2, ['d', 'e'])],\n ....: 1: [(0, ['f', 'g']), (1, 'h'), (2, None)],\n ....: 2: [(0, None), (1, None), (2, ['i', 'j'])]},\n ....: initial_states=[1, 2], final_states=[0])\n sage: B.with_output(lambda t: [c.upper() for c in t.word_in]).input_projection() == B\n True\n "
if (word_out_function is None):
word_out_function = (lambda transition: copy(transition.word_in))
new = Transducer()
memo = dict()
new._copy_from_other_(self, memo=memo)
for t in new.iter_transitions():
t.word_out = word_out_function(t)
return new
def language(self, max_length=None, **kwargs):
"\n Return all words accepted by this automaton.\n\n INPUT:\n\n - ``max_length`` -- an integer or ``None`` (default). Only\n inputs of length at most ``max_length`` will be\n considered. If ``None``, then this iterates over all\n possible words without length restrictions.\n\n - ``kwargs`` -- will be passed on to the :class:`process\n iterator <FSMProcessIterator>`. See :meth:`process` for a\n description.\n\n OUTPUT:\n\n An iterator.\n\n EXAMPLES::\n\n sage: NAF = Automaton(\n ....: {'A': [('A', 0), ('B', 1), ('B', -1)],\n ....: 'B': [('A', 0)]},\n ....: initial_states=['A'], final_states=['A', 'B'])\n sage: list(NAF.language(3))\n [[],\n [0], [-1], [1],\n [-1, 0], [0, 0], [1, 0], [0, -1], [0, 1],\n [-1, 0, 0], [0, -1, 0], [0, 0, 0], [0, 1, 0], [1, 0, 0],\n [-1, 0, -1], [-1, 0, 1], [0, 0, -1],\n [0, 0, 1], [1, 0, -1], [1, 0, 1]]\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.language`,\n :meth:`process`.\n\n TESTS::\n\n sage: def R(ell):\n ....: return (2^(ell+2)-(-1)^ell)/3\n sage: import itertools\n sage: all(len(list(NAFs)) == R(ell) for ell, NAFs in\n ....: itertools.groupby(NAF.language(5), key=len))\n True\n "
T = self.with_output()
return T.language(max_length)
|
def is_Transducer(FSM):
'\n Tests whether or not ``FSM`` inherits from :class:`Transducer`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Transducer\n sage: is_Transducer(FiniteStateMachine())\n False\n sage: is_Transducer(Transducer())\n True\n sage: is_FiniteStateMachine(Transducer())\n True\n '
return isinstance(FSM, Transducer)
|
class Transducer(FiniteStateMachine):
"\n This creates a transducer, which is a finite state machine, whose\n transitions have input and output labels.\n\n A transducer has additional features like creating a simplified\n transducer.\n\n See class :class:`FiniteStateMachine` for more information.\n\n EXAMPLES:\n\n We can create a transducer performing the addition of 1 (for\n numbers given in binary and read from right to left) in the\n following way::\n\n sage: T = Transducer([('C', 'C', 1, 0), ('C', 'N', 0, 1),\n ....: ('N', 'N', 0, 0), ('N', 'N', 1, 1)],\n ....: initial_states=['C'], final_states=['N'])\n sage: T\n Transducer with 2 states\n sage: T([0])\n [1]\n sage: T([1,1,0])\n [0, 0, 1]\n sage: ZZ(T(15.digits(base=2)+[0]), base=2)\n 16\n\n Note that we have padded the binary input sequence by a `0` so\n that the transducer can reach its final state.\n\n TESTS::\n\n sage: Transducer()\n Empty transducer\n "
def _repr_(self):
'\n Represents the transducer as "Transducer with n states" where\n n is the number of states.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: Transducer()._repr_()\n \'Empty transducer\'\n\n TESTS::\n\n sage: T = Transducer()\n sage: T\n Empty transducer\n sage: T.add_state(42)\n 42\n sage: T\n Transducer with 1 state\n sage: T.add_state(43)\n 43\n sage: T\n Transducer with 2 states\n\n '
if (not self._states_):
return 'Empty transducer'
if (len(self._states_) == 1):
return 'Transducer with 1 state'
else:
return ('Transducer with %s states' % len(self._states_))
def _latex_transition_label_(self, transition, format_function=None):
"\n Return the proper transition label.\n\n INPUT:\n\n - ``transition`` -- a transition\n\n - ``format_function`` -- a function formatting the labels\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: F = Transducer([('A', 'B', 1, 2)])\n sage: print(latex(F)) # indirect doctest\n \\begin{tikzpicture}[auto, initial text=, >=latex]\n \\node[state] (v0) at (3.000000, 0.000000) {$\\text{\\texttt{A}}$};\n \\node[state] (v1) at (-3.000000, 0.000000) {$\\text{\\texttt{B}}$};\n \\path[->] (v0) edge node[rotate=360.00, anchor=south] {$1\\mid 2$} (v1);\n \\end{tikzpicture}\n\n TESTS::\n\n sage: F = Transducer([('A', 'B', 0, 1)])\n sage: t = F.transitions()[0]\n sage: F._latex_transition_label_(t)\n \\left[0\\right] \\mid \\left[1\\right]\n "
if (format_function is None):
format_function = latex
return ((format_function(transition.word_in) + '\\mid ') + format_function(transition.word_out))
def intersection(self, other, only_accessible_components=True):
"\n Return a new transducer which accepts an input if it is accepted by\n both given finite state machines producing the same output.\n\n INPUT:\n\n - ``other`` -- a transducer\n\n - ``only_accessible_components`` -- If ``True`` (default), then\n the result is piped through :meth:`.accessible_components`. If no\n ``new_input_alphabet`` is given, it is determined by\n :meth:`.determine_alphabets`.\n\n OUTPUT:\n\n A new transducer which computes the intersection\n (see below) of the languages of ``self`` and ``other``.\n\n The set of states of the transducer is the Cartesian product of the\n set of states of both given transducer. There is a transition `((A,\n B), (C, D), a, b)` in the new transducer if there are\n transitions `(A, C, a, b)` and `(B, D, a, b)` in the old transducers.\n\n EXAMPLES::\n\n sage: transducer1 = Transducer([('1', '2', 1, 0),\n ....: ('2', '2', 1, 0),\n ....: ('2', '2', 0, 1)],\n ....: initial_states=['1'],\n ....: final_states=['2'])\n sage: transducer2 = Transducer([('A', 'A', 1, 0),\n ....: ('A', 'B', 0, 0),\n ....: ('B', 'B', 0, 1),\n ....: ('B', 'A', 1, 1)],\n ....: initial_states=['A'],\n ....: final_states=['B'])\n sage: res = transducer1.intersection(transducer2)\n sage: res.transitions()\n [Transition from ('1', 'A') to ('2', 'A'): 1|0,\n Transition from ('2', 'A') to ('2', 'A'): 1|0]\n\n In general, transducers are not closed under intersection. But\n for transducer which do not have epsilon-transitions, the\n intersection is well defined (cf. [BaWo2012]_). However, in\n the next example the intersection of the two transducers is\n not well defined. The intersection of the languages consists\n of `(a^n, b^n c^n)`. This set is not recognizable by a\n *finite* transducer.\n\n ::\n\n sage: t1 = Transducer([(0, 0, 'a', 'b'),\n ....: (0, 1, None, 'c'),\n ....: (1, 1, None, 'c')],\n ....: initial_states=[0],\n ....: final_states=[0, 1])\n sage: t2 = Transducer([('A', 'A', None, 'b'),\n ....: ('A', 'B', 'a', 'c'),\n ....: ('B', 'B', 'a', 'c')],\n ....: initial_states=['A'],\n ....: final_states=['A', 'B'])\n sage: t2.intersection(t1)\n Traceback (most recent call last):\n ...\n ValueError: An epsilon-transition (with empty input or output)\n was found.\n\n TESTS::\n\n sage: transducer1 = Transducer([('1', '2', 1, 0)],\n ....: initial_states=['1'],\n ....: final_states=['2'])\n sage: transducer2 = Transducer([('A', 'B', 1, 0)],\n ....: initial_states=['A'],\n ....: final_states=['B'])\n sage: res = transducer1.intersection(transducer2)\n sage: res.final_states()\n [('2', 'B')]\n sage: transducer1.state('2').final_word_out = 1\n sage: transducer2.state('B').final_word_out = 2\n sage: res = transducer1.intersection(transducer2)\n sage: res.final_states()\n []\n\n REFERENCES:\n\n .. [BaWo2012] Javier Baliosian and Dina Wonsever, *Finite State\n Transducers*, chapter in *Handbook of Finite State Based Models and\n Applications*, edited by Jiacun Wang, Chapman and Hall/CRC, 2012.\n "
if (not is_Transducer(other)):
raise TypeError('Only a transducer can be intersected with a transducer.')
def function(transition1, transition2):
if ((not transition1.word_in) or (not transition2.word_in) or (not transition1.word_out) or (not transition2.word_out)):
raise ValueError('An epsilon-transition (with empty input or output) was found.')
if ((transition1.word_in == transition2.word_in) and (transition1.word_out == transition2.word_out)):
return (transition1.word_in, transition1.word_out)
else:
raise LookupError
new = self.product_FiniteStateMachine(other, function, only_accessible_components=only_accessible_components, final_function=(lambda s1, s2: s1.final_word_out))
for state in new.iter_final_states():
state0 = self.state(state.label()[0])
state1 = other.state(state.label()[1])
if (state0.final_word_out != state1.final_word_out):
state.final_word_out = None
state.is_final = False
return new
def cartesian_product(self, other, only_accessible_components=True):
"\n Return a new transducer which can simultaneously process an\n input with the machines ``self`` and ``other`` where the\n output labels are `d`-tuples of the original output labels.\n\n INPUT:\n\n - ``other`` - a finite state machine (if `d=2`) or a list (or\n other iterable) of `d-1` finite state machines\n\n - ``only_accessible_components`` -- If ``True`` (default), then\n the result is piped through :meth:`.accessible_components`. If no\n ``new_input_alphabet`` is given, it is determined by\n :meth:`.determine_alphabets`.\n\n OUTPUT:\n\n A transducer which can simultaneously process an input with ``self``\n and the machine(s) in ``other``.\n\n The set of states of the new transducer is the Cartesian product of\n the set of states of ``self`` and ``other``.\n\n Let `(A_j, B_j, a_j, b_j)` for `j\\in\\{1, \\ldots, d\\}` be\n transitions in the machines ``self`` and in ``other``. Then\n there is a transition `((A_1, \\ldots, A_d), (B_1, \\ldots,\n B_d), a, (b_1, \\ldots, b_d))` in the new transducer if `a_1 =\n \\cdots = a_d =: a`.\n\n EXAMPLES::\n\n sage: transducer1 = Transducer([('A', 'A', 0, 0),\n ....: ('A', 'A', 1, 1)],\n ....: initial_states=['A'],\n ....: final_states=['A'],\n ....: determine_alphabets=True)\n sage: transducer2 = Transducer([(0, 1, 0, ['b', 'c']),\n ....: (0, 0, 1, 'b'),\n ....: (1, 1, 0, 'a')],\n ....: initial_states=[0],\n ....: final_states=[1],\n ....: determine_alphabets=True)\n sage: result = transducer1.cartesian_product(transducer2)\n sage: result\n Transducer with 2 states\n sage: result.transitions()\n [Transition from ('A', 0) to ('A', 1): 0|(0, 'b'),(None, 'c'),\n Transition from ('A', 0) to ('A', 0): 1|(1, 'b'),\n Transition from ('A', 1) to ('A', 1): 0|(0, 'a')]\n sage: result([1, 0, 0])\n [(1, 'b'), (0, 'b'), (None, 'c'), (0, 'a')]\n sage: (transducer1([1, 0, 0]), transducer2([1, 0, 0]))\n ([1, 0, 0], ['b', 'b', 'c', 'a'])\n\n Also final output words are correctly processed::\n\n sage: transducer1.state('A').final_word_out = 2\n sage: result = transducer1.cartesian_product(transducer2)\n sage: result.final_states()[0].final_word_out\n [(2, None)]\n\n The following transducer counts the number of 11 blocks minus\n the number of 10 blocks over the alphabet ``[0, 1]``.\n\n ::\n\n sage: count_11 = transducers.CountSubblockOccurrences(\n ....: [1, 1],\n ....: input_alphabet=[0, 1])\n sage: count_10 = transducers.CountSubblockOccurrences(\n ....: [1, 0],\n ....: input_alphabet=[0, 1])\n sage: count_11x10 = count_11.cartesian_product(count_10)\n sage: difference = transducers.sub([0, 1])(count_11x10)\n sage: T = difference.simplification().relabeled()\n sage: T.initial_states()\n [1]\n sage: sorted(T.transitions())\n [Transition from 0 to 1: 0|-1,\n Transition from 0 to 0: 1|1,\n Transition from 1 to 1: 0|0,\n Transition from 1 to 0: 1|0]\n sage: input = [0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0]\n sage: output = [0, 0, 1, -1, 0, -1, 0, 0, 0, 1, 1, -1]\n sage: T(input) == output\n True\n\n If ``other`` is an automaton, then :meth:`.cartesian_product` returns\n ``self`` where the input is restricted to the input accepted by\n ``other``.\n\n For example, if the transducer transforms the standard\n binary expansion into the non-adjacent form and the automaton\n recognizes the binary expansion without adjacent ones, then the\n Cartesian product of these two is a transducer which does not change\n the input (except for changing ``a`` to ``(a, None)`` and ignoring a\n leading `0`).\n\n ::\n\n sage: NAF = Transducer([(0, 1, 0, None),\n ....: (0, 2, 1, None),\n ....: (1, 1, 0, 0),\n ....: (1, 2, 1, 0),\n ....: (2, 1, 0, 1),\n ....: (2, 3, 1, -1),\n ....: (3, 2, 0, 0),\n ....: (3, 3, 1, 0)],\n ....: initial_states=[0],\n ....: final_states=[1],\n ....: determine_alphabets=True)\n sage: aut11 = Automaton([(0, 0, 0), (0, 1, 1), (1, 0, 0)],\n ....: initial_states=[0],\n ....: final_states=[0, 1],\n ....: determine_alphabets=True)\n sage: res = NAF.cartesian_product(aut11)\n sage: res([1, 0, 0, 1, 0, 1, 0])\n [(1, None), (0, None), (0, None), (1, None), (0, None), (1, None)]\n\n This is obvious because if the standard binary expansion does not have\n adjacent ones, then it is the same as the non-adjacent form.\n\n Be aware that :meth:`.cartesian_product` is not commutative.\n\n ::\n\n sage: aut11.cartesian_product(NAF)\n Traceback (most recent call last):\n ...\n TypeError: Only an automaton can be intersected with an automaton.\n\n The Cartesian product of more than two finite state machines can also\n be computed::\n\n sage: T0 = transducers.CountSubblockOccurrences([0, 0], [0, 1, 2])\n sage: T1 = transducers.CountSubblockOccurrences([1, 1], [0, 1, 2])\n sage: T2 = transducers.CountSubblockOccurrences([2, 2], [0, 1, 2])\n sage: T = T0.cartesian_product([T1, T2])\n sage: T.transitions()\n [Transition from ((), (), ()) to ((0,), (), ()): 0|(0, 0, 0),\n Transition from ((), (), ()) to ((), (1,), ()): 1|(0, 0, 0),\n Transition from ((), (), ()) to ((), (), (2,)): 2|(0, 0, 0),\n Transition from ((0,), (), ()) to ((0,), (), ()): 0|(1, 0, 0),\n Transition from ((0,), (), ()) to ((), (1,), ()): 1|(0, 0, 0),\n Transition from ((0,), (), ()) to ((), (), (2,)): 2|(0, 0, 0),\n Transition from ((), (1,), ()) to ((0,), (), ()): 0|(0, 0, 0),\n Transition from ((), (1,), ()) to ((), (1,), ()): 1|(0, 1, 0),\n Transition from ((), (1,), ()) to ((), (), (2,)): 2|(0, 0, 0),\n Transition from ((), (), (2,)) to ((0,), (), ()): 0|(0, 0, 0),\n Transition from ((), (), (2,)) to ((), (1,), ()): 1|(0, 0, 0),\n Transition from ((), (), (2,)) to ((), (), (2,)): 2|(0, 0, 1)]\n sage: T([0, 0, 1, 1, 2, 2, 0, 1, 2, 2])\n [(0, 0, 0),\n (1, 0, 0),\n (0, 0, 0),\n (0, 1, 0),\n (0, 0, 0),\n (0, 0, 1),\n (0, 0, 0),\n (0, 0, 0),\n (0, 0, 0),\n (0, 0, 1)]\n "
def function(*transitions):
if equal((t.word_in for t in transitions)):
return (transitions[0].word_in, list(itertools.zip_longest(*(t.word_out for t in transitions))))
else:
raise LookupError
def final_function(*states):
return list(itertools.zip_longest(*(s.final_word_out for s in states)))
return self.product_FiniteStateMachine(other, function, final_function=final_function, only_accessible_components=only_accessible_components)
def simplification(self):
'\n Return a simplified transducer.\n\n OUTPUT:\n\n A new transducer.\n\n This function simplifies a transducer by Moore\'s algorithm,\n first moving common output labels of transitions leaving a\n state to output labels of transitions entering the state\n (cf. :meth:`.prepone_output`).\n\n The resulting transducer implements the same function as the\n original transducer.\n\n EXAMPLES::\n\n sage: fsm = Transducer([("A", "B", 0, 1), ("A", "B", 1, 0),\n ....: ("B", "C", 0, 0), ("B", "C", 1, 1),\n ....: ("C", "D", 0, 1), ("C", "D", 1, 0),\n ....: ("D", "A", 0, 0), ("D", "A", 1, 1)])\n sage: fsms = fsm.simplification()\n sage: fsms\n Transducer with 2 states\n sage: fsms.transitions()\n [Transition from (\'B\', \'D\') to (\'A\', \'C\'): 0|0,\n Transition from (\'B\', \'D\') to (\'A\', \'C\'): 1|1,\n Transition from (\'A\', \'C\') to (\'B\', \'D\'): 0|1,\n Transition from (\'A\', \'C\') to (\'B\', \'D\'): 1|0]\n sage: fsms.relabeled().transitions()\n [Transition from 0 to 1: 0|0,\n Transition from 0 to 1: 1|1,\n Transition from 1 to 0: 0|1,\n Transition from 1 to 0: 1|0]\n\n ::\n\n sage: fsm = Transducer([("A", "A", 0, 0),\n ....: ("A", "B", 1, 1),\n ....: ("A", "C", 1, -1),\n ....: ("B", "A", 2, 0),\n ....: ("C", "A", 2, 0)])\n sage: fsm_simplified = fsm.simplification()\n sage: fsm_simplified\n Transducer with 2 states\n sage: fsm_simplified.transitions()\n [Transition from (\'A\',) to (\'A\',): 0|0,\n Transition from (\'A\',) to (\'B\', \'C\'): 1|1,0,\n Transition from (\'A\',) to (\'B\', \'C\'): 1|-1,0,\n Transition from (\'B\', \'C\') to (\'A\',): 2|-]\n\n ::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input\n sage: T = Transducer([(\'A\', \'A\', 1/2, 0),\n ....: (\'A\', \'B\', 1/4, 1),\n ....: (\'A\', \'C\', 1/4, 1),\n ....: (\'B\', \'A\', 1, 0),\n ....: (\'C\', \'A\', 1, 0)],\n ....: initial_states=[0],\n ....: final_states=[\'A\', \'B\', \'C\'],\n ....: on_duplicate_transition=duplicate_transition_add_input)\n sage: sorted(T.simplification().transitions())\n [Transition from (\'A\',) to (\'A\',): 1/2|0,\n Transition from (\'A\',) to (\'B\', \'C\'): 1/2|1,\n Transition from (\'B\', \'C\') to (\'A\',): 1|0]\n\n Illustrating the use of colors in order to avoid identification of states::\n\n sage: T = Transducer( [[0,0,0,0], [0,1,1,1],\n ....: [1,0,0,0], [1,1,1,1]],\n ....: initial_states=[0],\n ....: final_states=[0,1])\n sage: sorted(T.simplification().transitions())\n [Transition from (0, 1) to (0, 1): 0|0,\n Transition from (0, 1) to (0, 1): 1|1]\n sage: T.state(0).color = 0\n sage: T.state(0).color = 1\n sage: sorted(T.simplification().transitions())\n [Transition from (0,) to (0,): 0|0,\n Transition from (0,) to (1,): 1|1,\n Transition from (1,) to (0,): 0|0,\n Transition from (1,) to (1,): 1|1]\n '
fsm = deepcopy(self)
fsm.prepone_output()
return fsm.quotient(fsm.equivalence_classes())
def process(self, *args, **kwargs):
"\n Return whether the transducer accepts the input, the state\n where the computation stops and which output is generated.\n\n INPUT:\n\n - ``input_tape`` -- the input tape can be a list or an\n iterable with entries from the input alphabet. If we are\n working with a multi-tape machine (see parameter\n ``use_multitape_input`` and notes below), then the tape is a\n list or tuple of tracks, each of which can be a list or an\n iterable with entries from the input alphabet.\n\n - ``initial_state`` or ``initial_states`` -- the initial\n state(s) in which the machine starts. Either specify a\n single one with ``initial_state`` or a list of them with\n ``initial_states``. If both are given, ``initial_state``\n will be appended to ``initial_states``. If neither is\n specified, the initial states of the finite state machine\n are taken.\n\n - ``list_of_outputs`` -- (default: ``None``) a boolean or\n ``None``. If ``True``, then the outputs are given in list form\n (even if we have no or only one single output). If\n ``False``, then the result is never a list (an exception is\n raised if the result cannot be returned). If\n ``list_of_outputs=None`` the method determines automatically\n what to do (e.g. if a non-deterministic machine returns more\n than one path, then the output is returned in list form).\n\n - ``only_accepted`` -- (default: ``False``) a boolean. If set,\n then the first argument in the output is guaranteed to be\n ``True`` (if the output is a list, then the first argument\n of each element will be ``True``).\n\n - ``full_output`` -- (default: ``True``) a boolean. If set,\n then the full output is given, otherwise only the generated\n output (the third entry below only). If the input is not\n accepted, a ``ValueError`` is raised.\n\n - ``always_include_output`` -- if set (not by default), always\n include the output. This is inconsequential for a\n :class:`Transducer`, but can be used in other classes\n derived from :class:`FiniteStateMachine` where the output is\n suppressed by default, cf. :meth:`Automaton.process`.\n\n - ``format_output`` -- a function that translates the written\n output (which is in form of a list) to something more\n readable. By default (``None``) identity is used here.\n\n - ``check_epsilon_transitions`` -- (default: ``True``) a\n boolean. If ``False``, then epsilon transitions are not\n taken into consideration during process.\n\n - ``write_final_word_out`` -- (default: ``True``) a boolean\n specifying whether the final output words should be written\n or not.\n\n - ``use_multitape_input`` -- (default: ``False``) a\n boolean. If ``True``, then the multi-tape mode of the\n process iterator is activated. See also the notes below for\n multi-tape machines.\n\n - ``process_all_prefixes_of_input`` -- (default: ``False``) a\n boolean. If ``True``, then each prefix of the input word is\n processed (instead of processing the whole input word at\n once). Consequently, there is an output generated for each\n of these prefixes.\n\n - ``process_iterator_class`` -- (default: ``None``) a class\n inherited from :class:`FSMProcessIterator`. If ``None``,\n then :class:`FSMProcessIterator` is taken. An instance of this\n class is created and is used during the processing.\n\n - ``automatic_output_type`` -- (default: ``False``) a boolean\n If set and the input has a parent, then the\n output will have the same parent. If the input does not have\n a parent, then the output will be of the same type as the\n input.\n\n OUTPUT:\n\n The full output is a triple (or a list of triples,\n cf. parameter ``list_of_outputs``), where\n\n - the first entry is ``True`` if the input string is accepted,\n\n - the second gives the reached state after processing the\n input tape (This is a state with label ``None`` if the input\n could not be processed, i.e., if at one point no\n transition to go on could be found.), and\n\n - the third gives a list of the output labels written during\n processing.\n\n If ``full_output`` is ``False``, then only the third entry\n is returned.\n\n Note that in the case the transducer is not\n deterministic, all possible paths are taken into account.\n\n This function uses an iterator which, in its simplest form, goes\n from one state to another in each step. To decide which way to\n go, it uses the input words of the outgoing transitions and\n compares them to the input tape. More precisely, in each step,\n the iterator takes an outgoing transition of the current state,\n whose input label equals the input letter of the tape. The\n output label of the transition, if present, is written on the\n output tape.\n\n If the choice of the outgoing transition is not unique (i.e.,\n we have a non-deterministic finite state machine), all\n possibilities are followed. This is done by splitting the\n process into several branches, one for each of the possible\n outgoing transitions.\n\n The process (iteration) stops if all branches are finished,\n i.e., for no branch, there is any transition whose input word\n coincides with the processed input tape. This can simply\n happen when the entire tape was read.\n\n Also see :meth:`~FiniteStateMachine.__call__` for a version of\n :meth:`.process` with shortened output.\n\n Internally this function creates and works with an instance of\n :class:`FSMProcessIterator`. This iterator can also be obtained\n with :meth:`~FiniteStateMachine.iter_process`.\n\n If working with multi-tape finite state machines, all input\n words of transitions are words of `k`-tuples of letters.\n Moreover, the input tape has to consist of `k` tracks, i.e.,\n be a list or tuple of `k` iterators, one for each track.\n\n .. WARNING::\n\n Working with multi-tape finite state machines is still\n experimental and can lead to wrong outputs.\n\n EXAMPLES::\n\n sage: binary_inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: binary_inverter.process([0, 1, 0, 0, 1, 1])\n (True, 'A', [1, 0, 1, 1, 0, 0])\n\n If we are only interested in the output, we can also use::\n\n sage: binary_inverter([0, 1, 0, 0, 1, 1])\n [1, 0, 1, 1, 0, 0]\n\n This can also be used with words as input::\n\n sage: # needs sage.combinat\n sage: W = Words([0, 1]); W\n Finite and infinite words over {0, 1}\n sage: w = W([0, 1, 0, 0, 1, 1]); w\n word: 010011\n sage: binary_inverter(w)\n word: 101100\n\n In this case it is automatically determined that the output is\n a word. The call above is equivalent to::\n\n sage: binary_inverter.process(w, # needs sage.combinat\n ....: full_output=False,\n ....: list_of_outputs=False,\n ....: automatic_output_type=True)\n word: 101100\n\n The following transducer transforms `0^n 1` to `1^n 2`::\n\n sage: T = Transducer([(0, 0, 0, 1), (0, 1, 1, 2)])\n sage: T.state(0).is_initial = True\n sage: T.state(1).is_final = True\n\n We can see the different possibilities of the output by::\n\n sage: [T.process(w) for w in [[1], [0, 1], [0, 0, 1], [0, 1, 1],\n ....: [0], [0, 0], [2, 0], [0, 1, 2]]]\n [(True, 1, [2]), (True, 1, [1, 2]),\n (True, 1, [1, 1, 2]), (False, None, None),\n (False, 0, [1]), (False, 0, [1, 1]),\n (False, None, None), (False, None, None)]\n\n If we just want a condensed output, we use::\n\n sage: [T.process(w, full_output=False)\n ....: for w in [[1], [0, 1], [0, 0, 1]]]\n [[2], [1, 2], [1, 1, 2]]\n sage: T.process([0], full_output=False)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T.process([0, 1, 2], full_output=False)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n\n It is equivalent to::\n\n sage: [T(w) for w in [[1], [0, 1], [0, 0, 1]]]\n [[2], [1, 2], [1, 1, 2]]\n sage: T([0])\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T([0, 1, 2])\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n\n A cycle with empty input and empty output is correctly processed::\n\n sage: T = Transducer([(0, 1, None, None), (1, 0, None, None)],\n ....: initial_states=[0], final_states=[1])\n sage: T.process([])\n [(False, 0, []), (True, 1, [])]\n sage: _ = T.add_transition(-1, 0, 0, 'r')\n sage: T.state(-1).is_initial = True\n sage: T.state(0).is_initial = False\n sage: T.process([0])\n [(False, 0, ['r']), (True, 1, ['r'])]\n\n If there is a cycle with empty input but non-empty output, the\n possible outputs would be an infinite set::\n\n sage: T = Transducer([(0, 1, None, 'z'), (1, 0, None, None)],\n ....: initial_states=[0], final_states=[1])\n sage: T.process([])\n Traceback (most recent call last):\n ...\n RuntimeError: State 0 is in an epsilon cycle (no input),\n but output is written.\n\n But if this cycle with empty input and non-empty output is not\n reached, the correct output is produced::\n\n sage: _ = T.add_transition(-1, 0, 0, 'r')\n sage: T.state(-1).is_initial = True\n sage: T.state(0).is_initial = False\n sage: T.process([])\n (False, -1, [])\n sage: T.process([0])\n Traceback (most recent call last):\n ...\n RuntimeError: State 0 is in an epsilon cycle (no input),\n but output is written.\n\n If we set ``check_epsilon_transitions=False``, then no\n transitions with empty input are considered\n anymore. Thus cycles with empty input are no problem anymore::\n\n sage: T.process([0], check_epsilon_transitions=False)\n (False, 0, ['r'])\n\n A simple example of a multi-tape transducer is the\n following: It writes the length of the first tape many letters ``a``\n and then the length of the second tape many letters ``b``::\n\n sage: M = Transducer([(0, 0, (1, None), 'a'),\n ....: (0, 1, [], []),\n ....: (1, 1, (None, 1), 'b')],\n ....: initial_states=[0],\n ....: final_states=[1])\n sage: M.process(([1, 1], [1]), use_multitape_input=True)\n (True, 1, ['a', 'a', 'b'])\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.process`,\n :meth:`Automaton.process`,\n :meth:`~FiniteStateMachine.iter_process`,\n :meth:`~FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, 1, 'a'), (1, 0, 1, 'b')],\n ....: initial_states=[0, 1], final_states=[1])\n sage: T.process([1, 1])\n [(False, 0, ['a', 'b']), (True, 1, ['b', 'a'])]\n sage: T.process([1, 1], T.state(0))\n (False, 0, ['a', 'b'])\n sage: T.state(1).final_word_out = 'c'\n sage: T.process([1, 1], T.state(1))\n (True, 1, ['b', 'a', 'c'])\n sage: T.process([1, 1], T.state(1), write_final_word_out=False)\n (True, 1, ['b', 'a'])\n\n The parameter ``input_tape`` is required::\n\n sage: T.process()\n Traceback (most recent call last):\n ...\n TypeError: No input tape given.\n "
options = copy(self._process_default_options_)
options.update(kwargs)
condensed_output = ((options['list_of_outputs'] is False) and (not options['full_output']))
if condensed_output:
options['list_of_outputs'] = True
options['only_accepted'] = True
result = super().process(*args, **options)
if ((condensed_output and (not result)) or ((not options['full_output']) and (result is None))):
raise ValueError('Invalid input sequence.')
if (condensed_output and (len(result) >= 2)):
raise ValueError('Found more than one accepting path.')
if condensed_output:
return result[0]
return result
def _process_convert_output_(self, output_data, **kwargs):
"\n Helper function which converts the output of\n :meth:`FiniteStateMachine.process` to one suitable for\n transducers.\n\n INPUT:\n\n - ``output_data`` -- a triple.\n\n - ``full_output`` -- a boolean.\n\n OUTPUT:\n\n The converted output.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: T = Transducer()\n sage: T._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=False)\n [1, 0, 1]\n sage: T._process_convert_output_((True, FSMState('a'), [1, 0, 1]),\n ....: full_output=True)\n (True, 'a', [1, 0, 1])\n "
(accept_input, current_state, output) = output_data
if kwargs['full_output']:
if (current_state.label() is None):
return (accept_input, current_state, None)
else:
return (accept_input, current_state, output)
else:
if (not accept_input):
return None
return output
|
class _FSMTapeCache_(SageObject):
'\n This is a class for caching an input tape. It is used in\n :class:`FSMProcessIterator`.\n\n INPUT:\n\n - ``tape_cache_manager`` -- a list of the existing instances of\n :class:`_FSMTapeCache_`. ``self`` will be appended to this list.\n\n - ``tape`` -- a tuple or list of the input tracks (iterables).\n\n - ``tape_ended`` -- a list of booleans (one for each track of the\n tape), which indicate whether the track iterator has already raised\n a ``StopIteration`` exception.\n\n - ``position`` -- a tuple of pairs `(p, t)` marking the current\n positions of each of the input tracks. There `p` is the number\n of letter read from track `t`. The pairs of ``position`` are\n sorted first by `p` (smallest first) and then by `t`, i.e.,\n lexicographically.\n\n - ``is_multitape`` -- If ``True`` each entry of the\n input-word-tuple of a transition is interpreted as word for the\n corresponding input track. If ``False`` input-words are\n interpreted as an iterable of letters.\n\n OUTPUT:\n\n A tape-cache.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC1 = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), False)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC1\n tape at 0\n sage: TC1.tape_cache_manager\n [tape at 0]\n sage: TC2\n multi-tape at (0, 0)\n sage: TC2.tape_cache_manager\n [multi-tape at (0, 0)]\n '
def __init__(self, tape_cache_manager, tape, tape_ended, position, is_multitape):
'\n See :class:`_FSMTapeCache_` for more details.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC1 = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), False)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC1m = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), True)\n sage: TC3 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False], ((0, 0),), False)\n Traceback (most recent call last):\n ...\n TypeError: The lengths of the inputs do not match\n sage: TC4 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0),), False)\n Traceback (most recent call last):\n ...\n TypeError: The lengths of the inputs do not match\n sage: TC5 = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False, False], ((0, 0), (0, 1)), True)\n Traceback (most recent call last):\n ...\n TypeError: The lengths of the inputs do not match\n sage: _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 2), (0, 1)), True)\n Traceback (most recent call last):\n ...\n TypeError: Tape position ((0, 2), (0, 1)) wrong.\n '
if (not (len(tape) == len(position) == len(tape_ended))):
raise TypeError('The lengths of the inputs do not match')
if (sorted((p[1] for p in position)) != list(range(len(tape)))):
raise TypeError(('Tape position %s wrong.' % (position,)))
self.position = position
self.tape = tape
self.tape_ended = tape_ended
self.is_multitape = is_multitape
self.tape_cache_manager = tape_cache_manager
self.tape_cache_manager.append(self)
self.cache = tuple((deque() for _ in self.tape))
def _repr_(self):
"\n Return a string representation of ``self``.\n\n OUTPUT:\n\n A string.\n\n Note that this representation depends on the parameter\n ``is_multitape`` of ``self``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC1 = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), False)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC1m = _FSMTapeCache_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), True)\n sage: repr(TC1) # indirect doctest\n 'tape at 0'\n sage: repr(TC1m) # indirect doctest\n 'multi-tape at (0,)'\n sage: repr(TC2) # indirect doctest\n 'multi-tape at (0, 0)'\n "
if self.is_multitape:
pos = tuple((p for (p, t) in sorted(self.position, key=(lambda x: x[1]))))
return ('multi-tape at %s' % (pos,))
else:
return ('tape at %s' % (self.position[0][0],))
def __deepcopy__(self, memo):
'\n See :meth:`.deepcopy` for details.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC3 = deepcopy(TC2) # indirect doctest\n sage: TC3\n multi-tape at (0, 0)\n sage: TC2.tape_cache_manager\n [multi-tape at (0, 0), multi-tape at (0, 0)]\n sage: TC2.tape_cache_manager is TC3.tape_cache_manager\n True\n '
new = type(self)(self.tape_cache_manager, self.tape, self.tape_ended, self.position, self.is_multitape)
new.cache = deepcopy(self.cache, memo)
return new
def deepcopy(self, memo=None):
'\n Return a deepcopy of ``self``.\n\n INPUT:\n\n - ``memo`` -- a dictionary.\n\n OUTPUT:\n\n An instance of ``_FSMCacheTape_``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC3 = deepcopy(TC2) # indirect doctest\n sage: TC2\n multi-tape at (0, 0)\n sage: TC3\n multi-tape at (0, 0)\n sage: TC2.read(0), TC2.read(1), TC2.read(1)\n ((True, 37), (True, 11), (True, 12))\n sage: TC2.preview_word()\n (37, 11)\n sage: TC2.cache is TC3.cache\n False\n '
return deepcopy(self, memo)
def read(self, track_number):
'\n Reads one letter from the given track of the input tape into\n the cache.\n\n INPUT:\n\n - ``track_number`` -- an integer.\n\n OUTPUT:\n\n ``(True, letter)`` if reading was successful (``letter`` was\n read), otherwise ``(False, None)``.\n\n Note that this updates the cache of all tapes in\n ``self.tape_cache_manager``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2.read(0), TC2.read(1), TC2.read(1)\n ((True, 37), (True, 11), (True, 12))\n sage: TC2.preview_word()\n (37, 11)\n sage: TC3 = deepcopy(TC2)\n sage: TC2.cache, TC3.cache\n ((deque([37]), deque([11, 12])), (deque([37]), deque([11, 12])))\n sage: TC3.read(1)\n (True, 13)\n sage: TC2.cache, TC3.cache\n ((deque([37]), deque([11, 12, 13])),\n (deque([37]), deque([11, 12, 13])))\n sage: TC2.read(1), TC2.read(1)\n ((True, 14), (False, None))\n sage: TC2.cache\n (deque([37]), deque([11, 12, 13, 14]))\n sage: TC2.tape_ended\n [False, True]\n sage: TC2.read(1)\n (False, None)\n '
try:
newval = next(self.tape[track_number])
except StopIteration:
self.tape_ended[track_number] = True
return (False, None)
for tape in self.tape_cache_manager:
tape.cache[track_number].append(newval)
return (True, newval)
def finished(self, track_number=None):
"\n Return whether the tape (or a particular track) has reached an\n end, i.e., there are no more letters in the cache and nothing\n more to read on the original tape.\n\n INPUT:\n\n - ``track_number`` -- an integer or ``None``. If ``None``,\n then ``True`` is returned if all tracks are finished.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_, FSMTransition)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: while True:\n ....: try:\n ....: word = TC2.preview_word(return_word=True)\n ....: except RuntimeError:\n ....: print('stop')\n ....: break\n ....: print('cache: {} {}'.format(TC2.cache, TC2))\n ....: print('finished: {} {} {}'.format(TC2.finished(),\n ....: TC2.finished(0), TC2.finished(1)))\n ....: TC2.forward(\n ....: FSMTransition(0, 0, word))\n cache: (deque([37]), deque([11])) multi-tape at (0, 0)\n finished: False False False\n cache: (deque([38]), deque([12])) multi-tape at (1, 1)\n finished: False False False\n cache: (deque([39]), deque([13])) multi-tape at (2, 2)\n finished: False False False\n cache: (deque([40]), deque([14])) multi-tape at (3, 3)\n finished: False False False\n stop\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([41]), deque([])) multi-tape at (4, 4)\n sage: print('finished: {} {} {}'.format(TC2.finished(),\n ....: TC2.finished(0), TC2.finished(1)))\n finished: False False True\n sage: TC2.preview_word()\n Traceback (most recent call last):\n ...\n RuntimeError: tape reached the end\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([41]), deque([])) multi-tape at (4, 4)\n sage: TC2.read(0)\n (False, None)\n sage: TC2.forward(FSMTransition(0, 0, [(0, None)]))\n sage: print('finished: {} {} {}'.format(TC2.finished(),\n ....: TC2.finished(0), TC2.finished(1)))\n finished: True True True\n "
if (track_number is None):
return all((self.finished(n) for (n, _) in enumerate(self.cache)))
if (not self.cache[track_number]):
self.read(track_number)
return (self.tape_ended[track_number] and (not self.cache[track_number]))
def preview_word(self, track_number=None, length=1, return_word=False):
"\n Reads a word from the input tape.\n\n INPUT:\n\n - ``track_number`` -- an integer or ``None``. If ``None``,\n then a tuple of words (one from each track) is returned.\n\n - ``length`` -- (default: ``1``) the length of the word(s).\n\n - ``return_word`` -- (default: ``False``) a boolean. If set,\n then a word is returned, otherwise a single letter (in which\n case ``length`` has to be ``1``).\n\n OUTPUT:\n\n A single letter or a word.\n\n A :python:`RuntimeError<library/exceptions.html#exceptions.RuntimeError>`\n is thrown if the tape (at least one track) has reached its end.\n\n Typically, this method is called from a hook-function of a\n state.\n\n The attribute ``position`` is not changed.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_, FSMTransition)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2.preview_word(), TC2.preview_word()\n ((37, 11), (37, 11))\n sage: while True:\n ....: try:\n ....: word = TC2.preview_word(return_word=True)\n ....: except RuntimeError:\n ....: print('stop')\n ....: break\n ....: print('read: {}'.format(word))\n ....: print('cache: {} {}'.format(TC2.cache, TC2))\n ....: TC2.forward(\n ....: FSMTransition(0, 0, word))\n ....: print('cache: {} {}'.format(TC2.cache, TC2))\n read: [(37, 11)]\n cache: (deque([37]), deque([11])) multi-tape at (0, 0)\n cache: (deque([]), deque([])) multi-tape at (1, 1)\n read: [(38, 12)]\n cache: (deque([38]), deque([12])) multi-tape at (1, 1)\n cache: (deque([]), deque([])) multi-tape at (2, 2)\n read: [(39, 13)]\n cache: (deque([39]), deque([13])) multi-tape at (2, 2)\n cache: (deque([]), deque([])) multi-tape at (3, 3)\n read: [(40, 14)]\n cache: (deque([40]), deque([14])) multi-tape at (3, 3)\n cache: (deque([]), deque([])) multi-tape at (4, 4)\n stop\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([41]), deque([])) multi-tape at (4, 4)\n sage: TC2.preview_word()\n Traceback (most recent call last):\n ...\n RuntimeError: tape reached the end\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([41]), deque([])) multi-tape at (4, 4)\n sage: TC2.preview_word(0)\n 41\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([41]), deque([])) multi-tape at (4, 4)\n sage: TC2.forward(FSMTransition(0, 0, [(41, None)]))\n sage: print('cache: {} {}'.format(TC2.cache, TC2))\n cache: (deque([]), deque([])) multi-tape at (5, 4)\n "
if ((not return_word) and (length != 1)):
raise ValueError('Should return a letter, but parameter length is not 1.')
if (track_number is None):
if self.is_multitape:
result = tuple((self.preview_word(n, length, return_word) for (n, _) in enumerate(self.cache)))
if (len(result) != len(self.cache)):
raise RuntimeError('tape reached the end')
if return_word:
return tupleofwords_to_wordoftuples(result)
else:
return result
else:
return self.preview_word(0, length, return_word)
track_cache = self.cache[track_number]
while (len(track_cache) < length):
if (not self.read(track_number)[0]):
raise RuntimeError('tape reached the end')
if return_word:
return list(itertools.islice(track_cache, 0, length))
else:
return track_cache[0]
def compare_to_tape(self, track_number, word):
'\n Return whether it is possible to read ``word`` from the given\n track successfully.\n\n INPUT:\n\n - ``track_number`` -- an integer.\n\n - ``word`` -- a tuple or list of letters.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCache_\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2.compare_to_tape(0, [37])\n True\n sage: TC2.compare_to_tape(1, [37])\n False\n sage: TC2.compare_to_tape(0, [37, 38])\n True\n sage: TC2.compare_to_tape(1, srange(11,15))\n True\n sage: TC2.compare_to_tape(1, srange(11,16))\n False\n sage: TC2.compare_to_tape(1, [])\n True\n '
track_cache = self.cache[track_number]
it_word = iter(word)
if any(((letter_on_track != letter_in_word) for (letter_on_track, letter_in_word) in zip(track_cache, it_word))):
return False
for letter_in_word in it_word:
(successful, letter_on_track) = self.read(track_number)
if (not successful):
return False
if (letter_in_word != letter_on_track):
return False
return True
def forward(self, transition):
'\n Forwards the tape according to the given transition.\n\n INPUT:\n\n - ``transition`` -- a transition of a finite state machine.\n\n OUTPUT:\n\n Nothing.\n\n If ``self.is_multitape`` is ``False``, then this function\n forwards ``self`` (track `0`) by the number of entries of\n ``transition.word_in`` different from ``None``.\n Otherwise (if ``self.is_multitape`` is\n ``True``), this function forwards each track of ``self`` by\n the length of each entry of ``transition.word_in``. Note that\n the actual values in the input word do not play a role\n (just the length).\n\n This function changes the attribute ``position``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_, FSMTransition,\n ....: tupleofwords_to_wordoftuples)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2, TC2.cache\n (multi-tape at (0, 0), (deque([]), deque([])))\n sage: letter = TC2.preview_word(); letter\n (37, 11)\n sage: TC2, TC2.cache\n (multi-tape at (0, 0), (deque([37]), deque([11])))\n sage: TC2.forward(FSMTransition(0, 0, [letter]))\n sage: TC2, TC2.cache\n (multi-tape at (1, 1), (deque([]), deque([])))\n sage: TC2.forward(FSMTransition(0, 0, [(0, 0), (None, 0)]))\n sage: TC2, TC2.cache\n (multi-tape at (2, 3), (deque([]), deque([])))\n sage: letter = TC2.preview_word(); letter\n (39, 14)\n sage: TC2, TC2.cache\n (multi-tape at (2, 3), (deque([39]), deque([14])))\n sage: word_in = tupleofwords_to_wordoftuples([[None], [None, None]])\n sage: TC2.forward(FSMTransition(0, 0, word_in))\n sage: TC2, TC2.cache\n (multi-tape at (2, 3), (deque([39]), deque([14])))\n sage: TC2.forward(FSMTransition(0, 0, [[0, None], [None, 0]]))\n sage: TC2, TC2.cache\n (multi-tape at (3, 4), (deque([]), deque([])))\n sage: TC2.forward(FSMTransition(0, 0, [(0, 0)]))\n Traceback (most recent call last):\n ...\n ValueError: forwarding tape is not possible\n '
def length(word):
return len(tuple((letter for letter in word if (letter is not None))))
if self.is_multitape:
increments = tuple((length(word) for word in zip(*transition.word_in)))
else:
increments = (length(transition.word_in),)
for (track_number, (track_cache, inc)) in enumerate(zip(self.cache, increments)):
for _ in range(inc):
if (not track_cache):
if (not self.read(track_number)[0]):
raise ValueError('forwarding tape is not possible')
track_cache.popleft()
position = [((p + increments[t]), t) for (p, t) in self.position]
self.position = tuple(sorted(position))
def transition_possible(self, transition):
'\n Tests whether the input word of ``transition`` can be read\n from the tape.\n\n INPUT:\n\n - ``transition`` -- a transition of a finite state machine.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_, FSMTransition)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2, TC2.cache\n (multi-tape at (0, 0), (deque([]), deque([])))\n sage: TC2.transition_possible(\n ....: FSMTransition(0, 0, [(37, 11), (38, 12), (None, 13)]))\n True\n sage: TC2.transition_possible(\n ....: FSMTransition(0, 0, [(37, 11), (38, 13)]))\n False\n sage: TC2.transition_possible(\n ....: FSMTransition(0, 0, [(37,), (38,)]))\n Traceback (most recent call last):\n ...\n TypeError: Transition from 0 to 0: (37,),(38,)|- has bad\n input word (entries should be tuples of size 2).\n '
if self.is_multitape:
word_in = transition.word_in
else:
word_in = tupleofwords_to_wordoftuples((transition.word_in,))
if any(((len(t) != len(self.cache)) for t in word_in)):
raise TypeError(('%s has bad input word (entries should be tuples of size %s).' % (transition, len(self.cache))))
return self._transition_possible_test_(word_in)
def _transition_possible_epsilon_(self, word_in):
'\n This helper function tests whether ``word_in`` equals ``epsilon``,\n i.e., whether it is the empty word or consists only of letters ``None``.\n\n INPUT:\n\n - ``word_in`` -- an input word of a transition.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2._transition_possible_epsilon_([])\n True\n sage: TC2._transition_possible_epsilon_([(None, None)])\n True\n sage: TC2._transition_possible_epsilon_(\n ....: [(None, None), (None, None)])\n True\n '
return all(((letter is None) for t in word_in for letter in t))
def _transition_possible_test_(self, word_in):
'\n This helper function tests whether ``word_in`` can be read\n from the tape.\n\n INPUT:\n\n - ``word_in`` -- an input word of a transition.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n This method is usually overridden in inherited classes,\n cf. :class:`_FSMTapeCacheDetectEpsilon_` and\n :class:`_FSMTapeCacheDetectAll_`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCache_, tupleofwords_to_wordoftuples)\n sage: TC2 = _FSMTapeCache_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TC2, TC2.cache\n (multi-tape at (0, 0), (deque([]), deque([])))\n sage: word_in = tupleofwords_to_wordoftuples(\n ....: [(37, 38), (11, 12, 13)])\n sage: TC2._transition_possible_test_(word_in)\n True\n sage: word_in = tupleofwords_to_wordoftuples(\n ....: [(37, 38), (11, 13)])\n sage: TC2._transition_possible_test_(word_in)\n False\n\n Note that this function does not perform a check whether the\n input word is correct or not. This is done by the higher-level\n method :meth:`.transition_possible`::\n\n sage: TC2._transition_possible_test_([(37,), (38,)])\n True\n\n This function does not accept words of epsilon-transitions::\n\n sage: TC2._transition_possible_test_([])\n False\n sage: TC2._transition_possible_test_([(None, None)])\n False\n '
if self._transition_possible_epsilon_(word_in):
return False
word_in_transposed = wordoftuples_to_tupleofwords(word_in)
return all((self.compare_to_tape(track_number, word) for (track_number, word) in enumerate(word_in_transposed)))
|
class _FSMTapeCacheDetectEpsilon_(_FSMTapeCache_):
'\n This is a class is similar to :class:`_FSMTapeCache_` but accepts\n only epsilon transitions.\n '
def __init__(self, *args, **kwargs):
'\n See :class:`_FSMTapeCache_` for more details.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCacheDetectEpsilon_\n sage: _FSMTapeCacheDetectEpsilon_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), False)\n tape at 0\n '
super().__init__(*args, **kwargs)
self._visited_states_ = set()
def __deepcopy__(self, memo):
'\n See :meth:`_FSMTapeCache_.deepcopy` for details.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCacheDetectEpsilon_\n sage: TC2 = _FSMTapeCacheDetectEpsilon_([], (xsrange(37, 42),),\n ....: [False], ((0, 0),), True)\n sage: TC2._visited_states_.add(1)\n sage: TC3 = deepcopy(TC2) # indirect doctest\n sage: TC3._visited_states_\n {1}\n '
new = super().__deepcopy__(memo)
new._visited_states_ = copy(self._visited_states_)
return new
def _transition_possible_test_(self, word_in):
'\n This helper function tests whether ``word_in`` equals ``epsilon``,\n i.e., whether it is the empty word or consists only of letters ``None``.\n\n INPUT:\n\n - ``word_in`` -- an input word of a transition.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: _FSMTapeCacheDetectEpsilon_)\n sage: TCE = _FSMTapeCacheDetectEpsilon_([], (xsrange(37, 42), xsrange(11,15)),\n ....: [False, False], ((0, 0), (0, 1)), True)\n sage: TCE._transition_possible_test_([])\n True\n sage: TCE._transition_possible_test_([(None, None)])\n True\n sage: TCE._transition_possible_test_([(37, 11), (38, 12)])\n False\n sage: TCE._transition_possible_test_([(37, 11), (38, 13)])\n False\n '
return self._transition_possible_epsilon_(word_in)
|
class _FSMTapeCacheDetectAll_(_FSMTapeCache_):
'\n This is a class is similar to :class:`_FSMTapeCache_` but accepts\n each transition.\n '
def compare_to_tape(self, track_number, word):
'\n Return whether it is possible to read a word of the same length\n as ``word`` (but ignoring its actual content)\n from the given track successfully.\n\n INPUT:\n\n - ``track_number`` -- an integer.\n\n - ``word`` -- a tuple or list of letters. Only its length is used.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n Note that this method usually returns ``True``. ``False`` can\n only be returned at the end of the input tape.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import _FSMTapeCacheDetectAll_\n sage: TC = _FSMTapeCacheDetectAll_(\n ....: [], (iter((11, 12)),),\n ....: [False], ((0, 0),), False)\n sage: TC.compare_to_tape(0, [])\n True\n sage: TC.compare_to_tape(0, [37])\n True\n sage: TC.compare_to_tape(0, [37, 38])\n True\n sage: TC.compare_to_tape(0, [37, 38, 39])\n False\n sage: TC.compare_to_tape(0, [1, 2])\n True\n '
track_cache = self.cache[track_number]
it_word = iter(word)
for _ in track_cache:
next(it_word)
for _ in it_word:
(successful, _) = self.read(track_number)
if (not successful):
return False
return True
|
def tupleofwords_to_wordoftuples(tupleofwords):
'\n Transposes a tuple of words over the alphabet to a word of tuples.\n\n INPUT:\n\n - ``tupleofwords`` -- a tuple of a list of letters.\n\n OUTPUT:\n\n A list of tuples.\n\n Missing letters in the words are padded with the letter ``None``\n (from the empty word).\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: tupleofwords_to_wordoftuples)\n sage: tupleofwords_to_wordoftuples(\n ....: ([1, 2], [3, 4, 5, 6], [7]))\n [(1, 3, 7), (2, 4, None), (None, 5, None), (None, 6, None)]\n '
return list(itertools.zip_longest(*tupleofwords, fillvalue=None))
|
def wordoftuples_to_tupleofwords(wordoftuples):
'\n Transposes a word of tuples to a tuple of words over the alphabet.\n\n INPUT:\n\n - ``wordoftuples`` -- a list of tuples of letters.\n\n OUTPUT:\n\n A tuple of lists.\n\n Letters ``None`` (empty word) are removed from each word in the output.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import (\n ....: wordoftuples_to_tupleofwords)\n sage: wordoftuples_to_tupleofwords(\n ....: [(1, 2), (1, None), (1, None), (1, 2), (None, 2)])\n ([1, 1, 1, 1], [2, 2, 2])\n '
if (not equal((len(t) for t in wordoftuples))):
raise ValueError('Not all entries of input have the same length.')
def remove_empty_letters(word):
return [letter for letter in word if (letter is not None)]
return tuple((remove_empty_letters(word) for word in zip(*wordoftuples)))
|
def is_FSMProcessIterator(PI):
'\n Tests whether or not ``PI`` inherits from :class:`FSMProcessIterator`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FSMProcessIterator, FSMProcessIterator\n sage: is_FSMProcessIterator(FSMProcessIterator(FiniteStateMachine([[0, 0, 0, 0]], initial_states=[0]), []))\n True\n '
return isinstance(PI, FSMProcessIterator)
|
class FSMProcessIterator(SageObject, Iterator):
"\n This class takes an input, feeds it into a finite state machine\n (automaton or transducer, in particular), tests whether this was\n successful and calculates the written output.\n\n INPUT:\n\n - ``fsm`` -- the finite state machine on which the input should be\n processed.\n\n - ``input_tape`` -- the input tape can be a list or an\n iterable with entries from the input alphabet. If we are\n working with a multi-tape machine (see parameter\n ``use_multitape_input`` and notes below), then the tape is a\n list or tuple of tracks, each of which can be a list or an\n iterable with entries from the input alphabet.\n\n - ``initial_state`` or ``initial_states`` -- the initial\n state(s) in which the machine starts. Either specify a\n single one with ``initial_state`` or a list of them with\n ``initial_states``. If both are given, ``initial_state``\n will be appended to ``initial_states``. If neither is\n specified, the initial states of the finite state machine\n are taken.\n\n - ``format_output`` -- a function that translates the written\n output (which is in form of a list) to something more\n readable. By default (``None``) identity is used here.\n\n - ``check_epsilon_transitions`` -- (default: ``True``) a\n boolean. If ``False``, then epsilon transitions are not\n taken into consideration during process.\n\n - ``write_final_word_out`` -- (default: ``True``) a boolean\n specifying whether the final output words should be written\n or not.\n\n - ``use_multitape_input`` -- (default: ``False``) a\n boolean. If ``True``, then the multi-tape mode of the\n process iterator is activated. See also the notes below for\n multi-tape machines.\n\n - ``process_all_prefixes_of_input`` -- (default: ``False``) a\n boolean. If ``True``, then each prefix of the input word is\n processed (instead of processing the whole input word at\n once). Consequently, there is an output generated for each\n of these prefixes.\n\n OUTPUT:\n\n An iterator.\n\n In its simplest form, it behaves like an iterator which, in\n each step, goes from one state to another. To decide which way\n to go, it uses the input words of the outgoing transitions and\n compares them to the input tape. More precisely, in each step,\n the process iterator takes an outgoing transition of the\n current state, whose input label equals the input letter of\n the tape. The output label of the transition, if present, is\n written on the output tape.\n\n If the choice of the outgoing transition is not unique (i.e.,\n we have a non-deterministic finite state machine), all\n possibilities are followed. This is done by splitting the\n process into several branches, one for each of the possible\n outgoing transitions.\n\n The process (iteration) stops if all branches are finished,\n i.e., for no branch, there is any transition whose input word\n coincides with the processed input tape. This can simply\n happen when the entire tape was read.\n When the process stops, a ``StopIteration`` exception is thrown.\n\n .. WARNING::\n\n Processing an input tape of length `n` usually takes at least `n+1`\n iterations, since there will be `n+1` states visited (in the\n case the taken transitions have input words consisting of single\n letters).\n\n An instance of this class is generated when\n :meth:`FiniteStateMachine.process` or\n :meth:`FiniteStateMachine.iter_process` of a finite state machine,\n an automaton, or a transducer is invoked.\n\n When working with multi-tape finite state machines, all input\n words of transitions are words of `k`-tuples of letters.\n Moreover, the input tape has to consist of `k` tracks, i.e.,\n be a list or tuple of `k` iterators, one for each track.\n\n .. WARNING::\n\n Working with multi-tape finite state machines is still\n experimental and can lead to wrong outputs.\n\n EXAMPLES:\n\n The following transducer reads binary words and outputs a word,\n where blocks of ones are replaced by just a single one. Further\n only words that end with a zero are accepted.\n\n ::\n\n sage: T = Transducer({'A': [('A', 0, 0), ('B', 1, None)],\n ....: 'B': [('B', 1, None), ('A', 0, [1, 0])]},\n ....: initial_states=['A'], final_states=['A'])\n sage: input = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0]\n sage: T.process(input)\n (True, 'A', [1, 0, 0, 1, 0, 1, 0])\n\n The function :meth:`FiniteStateMachine.process` (internally) uses a\n :class:`FSMProcessIterator`. We can do that manually, too, and get full\n access to the iteration process::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: it = FSMProcessIterator(T, input_tape=input)\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 'B'\n +-- tape at 1, [[]]\n process (1 branch)\n + at state 'B'\n +-- tape at 2, [[]]\n process (1 branch)\n + at state 'A'\n +-- tape at 3, [[1, 0]]\n process (1 branch)\n + at state 'A'\n +-- tape at 4, [[1, 0, 0]]\n process (1 branch)\n + at state 'B'\n +-- tape at 5, [[1, 0, 0]]\n process (1 branch)\n + at state 'A'\n +-- tape at 6, [[1, 0, 0, 1, 0]]\n process (1 branch)\n + at state 'B'\n +-- tape at 7, [[1, 0, 0, 1, 0]]\n process (1 branch)\n + at state 'B'\n +-- tape at 8, [[1, 0, 0, 1, 0]]\n process (1 branch)\n + at state 'B'\n +-- tape at 9, [[1, 0, 0, 1, 0]]\n process (1 branch)\n + at state 'A'\n +-- tape at 10, [[1, 0, 0, 1, 0, 1, 0]]\n process (0 branches)\n sage: it.result()\n [Branch(accept=True, state='A', output=[1, 0, 0, 1, 0, 1, 0])]\n\n ::\n\n sage: T = Transducer([(0, 0, 0, 'a'), (0, 1, 0, 'b'),\n ....: (1, 2, 1, 'c'), (2, 0, 0, 'd'),\n ....: (2, 1, None, 'd')],\n ....: initial_states=[0], final_states=[2])\n sage: sorted(T.process([0, 0, 1], format_output=lambda o: ''.join(o)))\n [(False, 1, 'abcd'), (True, 2, 'abc')]\n sage: it = FSMProcessIterator(T, input_tape=[0, 0, 1],\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 0\n +-- tape at 1, [['a']]\n + at state 1\n +-- tape at 1, [['b']]\n process (2 branches)\n + at state 0\n +-- tape at 2, [['a', 'a']]\n + at state 1\n +-- tape at 2, [['a', 'b']]\n process (2 branches)\n + at state 1\n +-- tape at 3, [['a', 'b', 'c', 'd']]\n + at state 2\n +-- tape at 3, [['a', 'b', 'c']]\n process (0 branches)\n sage: sorted(it.result())\n [Branch(accept=False, state=1, output='abcd'),\n Branch(accept=True, state=2, output='abc')]\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.process`,\n :meth:`Automaton.process`,\n :meth:`Transducer.process`,\n :meth:`FiniteStateMachine.iter_process`,\n :meth:`FiniteStateMachine.__call__`,\n :meth:`next`.\n\n TESTS::\n\n sage: T = Transducer([[0, 0, 0, 0]])\n sage: T.process([])\n Traceback (most recent call last):\n ...\n ValueError: No state is initial.\n\n ::\n\n sage: T = Transducer([[0, 1, 0, 0]], initial_states=[0, 1])\n sage: T.process([])\n [(False, 0, []), (False, 1, [])]\n\n ::\n\n sage: T = Transducer([[0, 0, 0, 0]],\n ....: initial_states=[0], final_states=[0])\n sage: T.state(0).final_word_out = [42]\n sage: T.process([0])\n (True, 0, [0, 42])\n sage: T.process([0], write_final_word_out=False)\n (True, 0, [0])\n "
class Current(dict):
"\n This class stores the branches which have to be processed\n during iteration and provides a nicer formatting of them.\n\n This class is derived from ``dict``. It is returned by the\n ``next``-function during iteration.\n\n EXAMPLES:\n\n In the following example you can see the dict directly and\n then the nicer output provided by this class::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])\n sage: for current in it:\n ....: print(dict(current))\n ....: print(current)\n {((1, 0),): {'A': Branch(tape_cache=tape at 1, outputs=[[1]])}}\n process (1 branch)\n + at state 'A'\n +-- tape at 1, [[1]]\n {((2, 0),): {'A': Branch(tape_cache=tape at 2, outputs=[[1, 0]])}}\n process (1 branch)\n + at state 'A'\n +-- tape at 2, [[1, 0]]\n {}\n process (0 branches)\n "
def __repr__(self):
'\n Return a nice representation of ``self``.\n\n OUTPUT:\n\n A string.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: T = Transducer([(0, 0, 0, 0)],\n ....: initial_states=[0], final_states=[0])\n sage: it = FSMProcessIterator(T, input_tape=[0, 0])\n sage: for current in it: # indirect doctest\n ....: print(current)\n process (1 branch)\n + at state 0\n +-- tape at 1, [[0]]\n process (1 branch)\n + at state 0\n +-- tape at 2, [[0, 0]]\n process (0 branches)\n '
data = sorted(((state, pos, tape_cache, outputs) for (pos, states) in self.items() for (state, (tape_cache, outputs)) in states.items()))
branch = ('branch' if (len(data) == 1) else 'branches')
result = ('process (%s %s)' % (len(data), branch))
for (s, sdata) in itertools.groupby(data, (lambda x: x[0])):
result += ('\n+ at state %s' % (s,))
for (state, pos, tape_cache, outputs) in sdata:
result += ('\n+-- %s, %s' % (tape_cache, outputs))
return result
FinishedBranch = namedtuple('Branch', 'accept, state, output')
'\n A :func:`named tuple <collections.namedtuple>` representing the\n attributes of a branch, once\n it is fully processed.\n '
def __init__(self, fsm, input_tape=None, initial_state=None, initial_states=[], use_multitape_input=False, check_epsilon_transitions=True, write_final_word_out=True, format_output=None, process_all_prefixes_of_input=False, **kwargs):
"\n See :class:`FSMProcessIterator` for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},\n ....: initial_states=['A'], final_states=['A'])\n sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 'A'\n +-- tape at 1, [[1]]\n process (1 branch)\n + at state 'A'\n +-- tape at 2, [[1, 0]]\n process (0 branches)\n sage: it.result()\n [Branch(accept=True, state='A', output=[1, 0])]\n "
self.fsm = fsm
self.is_multitape = use_multitape_input
initial_states = list(initial_states)
if (initial_state is not None):
initial_states.append(initial_state)
if (not initial_states):
initial_states = self.fsm.initial_states()
if (not initial_states):
raise ValueError('No state is initial.')
tape = []
if (input_tape is not None):
if self.is_multitape:
tape.extend(input_tape)
else:
tape.append(input_tape)
if (not tape):
raise TypeError('No input tape given.')
if (not all((isinstance(track, Iterable) for track in tape))):
raise TypeError('Given input tape is not iterable.')
self._input_tape_ = tuple((iter(track) for track in tape))
self._input_tape_ended_ = [False for _ in tape]
if (format_output is None):
self.format_output = list
else:
self.format_output = format_output
self.check_epsilon_transitions = check_epsilon_transitions
self.write_final_word_out = write_final_word_out
self.process_all_prefixes_of_input = process_all_prefixes_of_input
self._current_ = self.Current()
self._current_positions_ = []
self._tape_cache_manager_ = []
position_zero = tuple(((0, t) for (t, _) in enumerate(self._input_tape_)))
if (not hasattr(self, 'TapeCache')):
self.TapeCache = _FSMTapeCache_
for state in initial_states:
tape_cache = self.TapeCache(self._tape_cache_manager_, self._input_tape_, self._input_tape_ended_, position_zero, self.is_multitape)
self._push_branches_(state, tape_cache, [[]])
self._finished_ = []
_branch_ = namedtuple('Branch', 'tape_cache, outputs')
'\n A :func:`named tuple <collections.namedtuple>` representing the\n attributes of a branch at a particular state during processing.\n '
def _push_branch_(self, state, tape_cache, outputs):
"\n This helper function pushes a ``state`` together with\n ``tape_cache`` and ``outputs`` (i.e. a branch) to the queue\n ``self._current_``. See also :meth:`._push_branches_`.\n\n INPUT:\n\n - ``state`` -- state which has to be processed.\n\n - ``tape_cache`` -- an instance of :class:`_FSMTapeCache_` (storing\n information what to read next).\n\n - ``outputs`` -- a list of output tapes on each of which words\n were written until reaching ``state``.\n\n OUTPUT:\n\n Nothing.\n\n .. NOTE::\n\n ``tape_cache`` is discarded if ``self.__current__`` already\n contains a branch with the same position and state.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: A = Automaton({'a': [('a', 0), ('b', 1), ('c', 1)],\n ....: 'c': [('b', None)], 'b': [('c', None)]},\n ....: initial_states=['a'], final_states=['b', 'c'])\n sage: it = FSMProcessIterator(A, input_tape=[0, 1, 2]) # indirect doctest\n sage: it._current_\n process (1 branch)\n + at state 'a'\n +-- tape at 0, [[]]\n sage: it._push_branch_(\n ....: A.state('b'),\n ....: deepcopy(it._current_[((0, 0),)][A.state('a')][0]),\n ....: [[]])\n sage: it._current_\n process (2 branches)\n + at state 'a'\n +-- tape at 0, [[]]\n + at state 'b'\n +-- tape at 0, [[]]\n sage: it._push_branches_( # indirect doctest\n ....: A.state('c'),\n ....: deepcopy(it._current_[((0, 0),)][A.state('a')][0]),\n ....: [[]])\n sage: it._current_\n process (3 branches)\n + at state 'a'\n +-- tape at 0, [[]]\n + at state 'b'\n +-- tape at 0, [[]]\n + at state 'c'\n +-- tape at 0, [[]]\n\n ::\n\n sage: T = Transducer([(0, 1, 0, 'd'), (0, 1, 0, 'a'),\n ....: (0, 1, 0, 'a'), (0, 1, 0, 'a'),\n ....: (0, 1, 0, 'n'), (0, 1, 0, 'i'),\n ....: (0, 1, 0, 'e'), (0, 1, 0, 'l'),\n ....: (0, 1, 0, 'l'), (0, 1, 0, 'l'),\n ....: (1, 2, 0, ':'), (2, 3, 0, ')')],\n ....: initial_states=[0], final_states=[3])\n sage: T.process([0, 0, 0], format_output=lambda o: ''.join(o))\n [(True, 3, 'a:)'), (True, 3, 'd:)'), (True, 3, 'e:)'),\n (True, 3, 'i:)'), (True, 3, 'l:)'), (True, 3, 'n:)')]\n\n "
import heapq
if (tape_cache.position in self._current_):
states = self._current_[tape_cache.position]
else:
states = self._current_[tape_cache.position] = {}
heapq.heappush(self._current_positions_, tape_cache.position)
if (state in states):
existing = states[state]
new_outputs = existing.outputs
new_outputs.extend(outputs)
new_outputs = [t for (t, _) in itertools.groupby(sorted(new_outputs))]
states[state] = FSMProcessIterator._branch_(existing.tape_cache, new_outputs)
else:
states[state] = FSMProcessIterator._branch_(tape_cache, outputs)
def _push_branches_(self, state, tape_cache, outputs):
"\n This function pushes a branch (consisting of a ``state``, an\n input ``tape_cache`` and ``outputs``) and one other branch for\n each epsilon successor of ``state`` to the queue (containing\n branches to process).\n\n INPUT:\n\n - ``state`` -- state which has to be processed (i.e., the\n current state, this branch is in).\n\n - ``tape_cache`` -- an instance of :class:`_FSMTapeCache_` (storing\n information what to read next).\n\n - ``outputs`` -- a list of output tapes on each of which words\n were written until reaching ``state``.\n\n OUTPUT:\n\n Nothing.\n\n When this function is called, a branch is updated, which\n means, stored for further processing. If the state has epsilon\n successors, then a new branch for each epsilon successor is\n created. All these branches start on the same position on the\n tape and get the same (more precisely, a deepcopy of the) list\n of output tapes.\n\n Note that ``self._current_`` contains all states which have to\n be visited in the next steps during processing. The actual\n adding of the data is done in the helper function\n :meth:`._push_branch_`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: A = Automaton({'a': [('a', 0), ('b', 1), ('c', None)],\n ....: 'c': [('b', 2)]},\n ....: initial_states=['a'], final_states=['b', 'c'])\n sage: it = FSMProcessIterator(A, input_tape=[0, 1, 2]) # indirect doctest\n sage: it._current_\n process (2 branches)\n + at state 'a'\n +-- tape at 0, [[]]\n + at state 'c'\n +-- tape at 0, [[]]\n sage: it._push_branches_(\n ....: A.state('b'),\n ....: deepcopy(it._current_[((0, 0),)][A.state('a')][0]),\n ....: [[]])\n sage: it._current_\n process (3 branches)\n + at state 'a'\n +-- tape at 0, [[]]\n + at state 'b'\n +-- tape at 0, [[]]\n + at state 'c'\n +-- tape at 0, [[]]\n "
self._push_branch_(state, tape_cache, outputs)
if (not self.check_epsilon_transitions):
return
if state._in_epsilon_cycle_(self.fsm):
if (not state._epsilon_cycle_output_empty_(self.fsm)):
raise RuntimeError(('State %s is in an epsilon cycle (no input), but output is written.' % (state,)))
for (eps_state, eps_outputs) in state._epsilon_successors_(self.fsm).items():
if (eps_state == state):
continue
for eps_out in eps_outputs:
new_out = [(o + list(eps_out)) for o in outputs]
self._push_branch_(eps_state, deepcopy(tape_cache), new_out)
def __next__(self):
'\n Makes one step in processing the input tape.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n It returns the current status of the iterator (see below). A\n ``StopIteration`` exception is thrown when there is/was\n nothing to do (i.e. all branches ended with previous call\n of :meth:`.next`).\n\n The current status is a dictionary (encapsulated into an instance of\n :class:`~FSMProcessIterator.Current`).\n The keys are positions on\n the tape. The value corresponding to such a position is again\n a dictionary, where each entry represents a branch of the\n process. This dictionary maps the current state of a branch to\n a pair consisting of a tape cache and a list of output words,\n which were written during reaching this current state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMProcessIterator\n sage: inverter = Transducer({\'A\': [(\'A\', 0, 1), (\'A\', 1, 0)]},\n ....: initial_states=[\'A\'], final_states=[\'A\'])\n sage: it = FSMProcessIterator(inverter, input_tape=[0, 1])\n sage: next(it)\n process (1 branch)\n + at state \'A\'\n +-- tape at 1, [[1]]\n sage: next(it)\n process (1 branch)\n + at state \'A\'\n +-- tape at 2, [[1, 0]]\n sage: next(it)\n process (0 branches)\n sage: next(it)\n Traceback (most recent call last):\n ...\n StopIteration\n\n .. SEEALSO::\n\n :meth:`FiniteStateMachine.process`,\n :meth:`Automaton.process`,\n :meth:`Transducer.process`,\n :meth:`FiniteStateMachine.iter_process`,\n :meth:`FiniteStateMachine.__call__`,\n :class:`FSMProcessIterator`.\n\n TESTS::\n\n sage: Z = Transducer()\n sage: s = Z.add_state(0)\n sage: s.is_initial = True\n sage: s.is_final = True\n sage: s.final_word_out = [1, 2]\n sage: Z.process([])\n (True, 0, [1, 2])\n sage: it = FSMProcessIterator(Z, input_tape=[])\n sage: next(it)\n process (0 branches)\n sage: next(it)\n Traceback (most recent call last):\n ...\n StopIteration\n\n ::\n\n sage: N = Transducer([(0, 0, 0, 1)], initial_states=[0])\n sage: def h_old(state, process):\n ....: print("{} {}".format(state, process))\n sage: N.state(0).hook = h_old\n sage: N.process([0, 0])\n Traceback (most recent call last):\n ...\n ValueError: invalid input\n\n sage: def h_new(process, state, outputs):\n ....: print("{} {}".format(state, outputs))\n sage: N.state(0).hook = h_new\n sage: N.process([0, 0], check_epsilon_transitions=False)\n 0 [[]]\n 0 [[1]]\n 0 [[1, 1]]\n (False, 0, [1, 1])\n '
import heapq
if (not self._current_):
raise StopIteration
def write_word(outputs, word):
for o in outputs:
o.extend(word)
def step(current_state, input_tape, outputs):
next_transitions = None
state_said_finished = False
if hasattr(current_state, 'hook'):
if (len(sage_getargspec(current_state.hook).args) == 2):
raise ValueError('invalid input')
else:
try:
self._current_branch_input_tape_ = input_tape
next_transitions = current_state.hook(self, current_state, outputs)
except StopIteration:
next_transitions = []
state_said_finished = True
if isinstance(next_transitions, FSMTransition):
next_transitions = [next_transitions]
if ((next_transitions is not None) and (not isinstance(next_transitions, Iterable))):
raise ValueError('hook of state should return a transition or a list/tuple of transitions.')
write_word(outputs, current_state.word_out)
if (next_transitions is None):
next_transitions = [transition for transition in current_state.transitions if input_tape.transition_possible(transition)]
if (not next_transitions):
if (not (input_tape.finished() or state_said_finished or self.process_all_prefixes_of_input)):
return
if ((not next_transitions) or self.process_all_prefixes_of_input):
successful = current_state.is_final
if self.process_all_prefixes_of_input:
write_outputs = deepcopy(outputs)
else:
write_outputs = outputs
if (successful and self.write_final_word_out):
write_word(write_outputs, current_state.final_word_out)
for o in write_outputs:
self._finished_.append(FSMProcessIterator.FinishedBranch(accept=successful, state=current_state, output=self.format_output(o)))
if (not next_transitions):
return
new_currents = [(input_tape, outputs)]
if (len(next_transitions) > 1):
new_currents.extend([deepcopy(new_currents[0]) for _ in range((len(next_transitions) - 1))])
for (transition, (tape, out)) in zip(next_transitions, new_currents):
if hasattr(transition, 'hook'):
transition.hook(transition, self)
write_word(out, transition.word_out)
state = transition.to_state
tape.forward(transition)
self._push_branches_(state, tape, out)
return
states_dict = self._current_.pop(heapq.heappop(self._current_positions_))
for (state, branch) in states_dict.items():
step(state, branch.tape_cache, branch.outputs)
return self._current_
next = __next__
def result(self, format_output=None):
"\n Return the already finished branches during process.\n\n INPUT:\n\n - ``format_output`` -- a function converting the output from\n list form to something more readable (default: output the\n list directly).\n\n OUTPUT:\n\n A list of triples ``(accepted, state, output)``.\n\n See also the parameter ``format_output`` of\n :class:`FSMProcessIterator`.\n\n EXAMPLES::\n\n sage: inverter = Transducer({'A': [('A', 0, 'one'), ('A', 1, 'zero')]},\n ....: initial_states=['A'], final_states=['A'])\n sage: it = inverter.iter_process(input_tape=[0, 1, 1])\n sage: for _ in it:\n ....: pass\n sage: it.result()\n [Branch(accept=True, state='A', output=['one', 'zero', 'zero'])]\n sage: it.result(lambda L: ', '.join(L))\n [(True, 'A', 'one, zero, zero')]\n\n Using both the parameter ``format_output`` of\n :class:`FSMProcessIterator` and the parameter ``format_output``\n of :meth:`.result` leads to concatenation of the two\n functions::\n\n sage: it = inverter.iter_process(input_tape=[0, 1, 1],\n ....: format_output=lambda L: ', '.join(L))\n sage: for _ in it:\n ....: pass\n sage: it.result()\n [Branch(accept=True, state='A', output='one, zero, zero')]\n sage: it.result(lambda L: ', '.join(L))\n [(True, 'A', 'o, n, e, ,, , z, e, r, o, ,, , z, e, r, o')]\n "
if (format_output is None):
return self._finished_
return [(r[:2] + (format_output(r[2]),)) for r in self._finished_]
def preview_word(self, track_number=None, length=1, return_word=False):
'\n Read a word from the input tape.\n\n INPUT:\n\n - ``track_number`` -- an integer or ``None``. If ``None``,\n then a tuple of words (one from each track) is returned.\n\n - ``length`` -- (default: ``1``) the length of the word(s).\n\n - ``return_word`` -- (default: ``False``) a boolean. If set,\n then a word is returned, otherwise a single letter (in which\n case ``length`` has to be ``1``).\n\n OUTPUT:\n\n A single letter or a word.\n\n An exception ``StopIteration`` is thrown if the tape (at least\n one track) has reached its end.\n\n Typically, this method is called from a hook-function of a\n state.\n\n EXAMPLES::\n\n sage: inverter = Transducer({\'A\': [(\'A\', 0, \'one\'),\n ....: (\'A\', 1, \'zero\')]},\n ....: initial_states=[\'A\'], final_states=[\'A\'])\n sage: def state_hook(process, state, output):\n ....: print("We are now in state %s." % (state.label(),))\n ....: try:\n ....: w = process.preview_word()\n ....: except RuntimeError:\n ....: raise StopIteration\n ....: print("Next on the tape is a %s." % (w,))\n sage: inverter.state(\'A\').hook = state_hook\n sage: it = inverter.iter_process(\n ....: input_tape=[0, 1, 1],\n ....: check_epsilon_transitions=False)\n sage: for _ in it:\n ....: pass\n We are now in state A.\n Next on the tape is a 0.\n We are now in state A.\n Next on the tape is a 1.\n We are now in state A.\n Next on the tape is a 1.\n We are now in state A.\n sage: it.result()\n [Branch(accept=True, state=\'A\', output=[\'one\', \'zero\', \'zero\'])]\n '
return self._current_branch_input_tape_.preview_word(track_number, length, return_word)
|
class _FSMProcessIteratorEpsilon_(FSMProcessIterator):
"\n This class is similar to :class:`FSMProcessIterator`, but only\n accepts epsilon transitions during process. See\n :class:`FSMProcessIterator` for more information.\n\n EXAMPLES::\n\n sage: T = Transducer([(0, 1, 0, 'a'), (0, 2, None, 'b'),\n ....: (2, 1, None, 'c')])\n sage: from sage.combinat.finite_state_machine import _FSMProcessIteratorEpsilon_\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n\n To see what is going on, we let the transducer run::\n\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 2\n +-- tape at 0, [['b']]\n process (1 branch)\n + at state 1\n +-- tape at 0, [['b', 'c']]\n process (0 branches)\n\n This class has the additional attribute ``visited_states``::\n\n sage: it.visited_states\n {0: [''], 1: ['bc'], 2: ['b']}\n\n This means the following (let us skip the state `0` for a moment):\n State `1` can be reached by a epsilon path which write ``'bc'`` as\n output. Similarly, state `2` can be reached by writing ``'b'``. We\n started in state `0`, so this is included in visited states as\n well (``''`` means that nothing was written, which is clear, since\n no path had to be taken).\n\n We continue with the other states as initial states::\n\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(1),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (0 branches)\n sage: it.visited_states\n {1: ['']}\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(2),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 1\n +-- tape at 0, [['c']]\n process (0 branches)\n sage: it.visited_states\n {1: ['c'], 2: ['']}\n\n TESTS::\n\n sage: A = Automaton([(0, 1, 0), (1, 2, None), (2, 3, None),\n ....: (3, 1, None), (3, 4, None), (1, 4, None)])\n sage: it = _FSMProcessIteratorEpsilon_(A, initial_state=A.state(0))\n sage: for current in it:\n ....: print(current)\n process (0 branches)\n sage: it.visited_states\n {0: [[]]}\n sage: it = _FSMProcessIteratorEpsilon_(A, initial_state=A.state(1))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 2\n +-- tape at 0, [[]]\n + at state 4\n +-- tape at 0, [[]]\n process (1 branch)\n + at state 3\n +-- tape at 0, [[]]\n process (1 branch)\n + at state 4\n +-- tape at 0, [[]]\n process (0 branches)\n sage: it.visited_states\n {1: [[], []], 2: [[]], 3: [[]], 4: [[], []]}\n\n At this point note that in the previous output, state `1` (from\n which we started) was also reached by a non-trivial\n path. Moreover, there are two different paths from `1` to `4`.\n\n Let us continue with the other initial states::\n\n sage: it = _FSMProcessIteratorEpsilon_(A, initial_state=A.state(2))\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 3\n +-- tape at 0, [[]]\n process (2 branches)\n + at state 1\n +-- tape at 0, [[]]\n + at state 4\n +-- tape at 0, [[]]\n process (1 branch)\n + at state 4\n +-- tape at 0, [[]]\n process (0 branches)\n sage: it.visited_states\n {1: [[]], 2: [[], []], 3: [[]], 4: [[], []]}\n sage: it = _FSMProcessIteratorEpsilon_(A, initial_state=A.state(3))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [[]]\n + at state 4\n +-- tape at 0, [[]]\n process (2 branches)\n + at state 2\n +-- tape at 0, [[]]\n + at state 4\n +-- tape at 0, [[]]\n process (0 branches)\n sage: it.visited_states\n {1: [[]], 2: [[]], 3: [[], []], 4: [[], []]}\n sage: it = _FSMProcessIteratorEpsilon_(A, initial_state=A.state(4))\n sage: for current in it:\n ....: print(current)\n process (0 branches)\n sage: it.visited_states\n {4: [[]]}\n\n ::\n\n sage: T = Transducer([(0, 1, 0, 'a'), (1, 2, None, 'b'),\n ....: (2, 3, None, 'c'), (3, 1, None, 'd'),\n ....: (3, 4, None, 'e'), (1, 4, None, 'f')])\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (0 branches)\n sage: it.visited_states\n {0: ['']}\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(1),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 2\n +-- tape at 0, [['b']]\n + at state 4\n +-- tape at 0, [['f']]\n process (1 branch)\n + at state 3\n +-- tape at 0, [['b', 'c']]\n process (1 branch)\n + at state 4\n +-- tape at 0, [['b', 'c', 'e']]\n process (0 branches)\n sage: it.visited_states\n {1: ['', 'bcd'], 2: ['b'],\n 3: ['bc'], 4: ['f', 'bce']}\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(2),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (1 branch)\n + at state 3\n +-- tape at 0, [['c']]\n process (2 branches)\n + at state 1\n +-- tape at 0, [['c', 'd']]\n + at state 4\n +-- tape at 0, [['c', 'e']]\n process (1 branch)\n + at state 4\n +-- tape at 0, [['c', 'd', 'f']]\n process (0 branches)\n sage: it.visited_states\n {1: ['cd'], 2: ['', 'cdb'],\n 3: ['c'], 4: ['ce', 'cdf']}\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(3),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [['d']]\n + at state 4\n +-- tape at 0, [['e']]\n process (2 branches)\n + at state 2\n +-- tape at 0, [['d', 'b']]\n + at state 4\n +-- tape at 0, [['d', 'f']]\n process (0 branches)\n sage: it.visited_states\n {1: ['d'], 2: ['db'],\n 3: ['', 'dbc'], 4: ['e', 'df']}\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(4),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (0 branches)\n sage: it.visited_states\n {4: ['']}\n\n ::\n\n sage: T = Transducer([(0, 1, None, 'a'), (0, 2, None, 'b'),\n ....: (1, 3, None, 'c'), (2, 3, None, 'd'),\n ....: (3, 0, None, 'e')])\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [['a']]\n + at state 2\n +-- tape at 0, [['b']]\n process (1 branch)\n + at state 3\n +-- tape at 0, [['a', 'c'], ['b', 'd']]\n process (0 branches)\n sage: it.visited_states\n {0: ['', 'ace', 'bde'], 1: ['a'], 2: ['b'], 3: ['ac', 'bd']}\n\n ::\n\n sage: T = Transducer([(0, 1, None, None), (0, 2, None, 'b'),\n ....: (1, 3, None, None), (2, 3, None, 'd'),\n ....: (3, 0, None, None)])\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [[]]\n + at state 2\n +-- tape at 0, [['b']]\n process (1 branch)\n + at state 3\n +-- tape at 0, [[], ['b', 'd']]\n process (0 branches)\n sage: it.visited_states\n {0: ['', '', 'bd'], 1: [''], 2: ['b'], 3: ['', 'bd']}\n sage: T.state(0)._epsilon_cycle_output_empty_(T)\n False\n\n ::\n\n sage: T = Transducer([(0, 1, None, 'a'), (1, 2, None, 'b'),\n ....: (0, 2, None, 'c'), (2, 3, None, 'd'),\n ....: (3, 0, None, 'e')])\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [['a']]\n + at state 2\n +-- tape at 0, [['c']]\n process (2 branches)\n + at state 2\n +-- tape at 0, [['a', 'b']]\n + at state 3\n +-- tape at 0, [['c', 'd']]\n process (1 branch)\n + at state 3\n +-- tape at 0, [['a', 'b', 'd']]\n process (0 branches)\n sage: it.visited_states\n {0: ['', 'cde', 'abde'], 1: ['a'], 2: ['c', 'ab'], 3: ['cd', 'abd']}\n\n ::\n\n sage: T = Transducer([(0, 1, None, 'a'), (0, 2, None, 'b'),\n ....: (0, 2, None, 'c'), (2, 3, None, 'd'),\n ....: (3, 0, None, 'e')])\n sage: it = _FSMProcessIteratorEpsilon_(T, initial_state=T.state(0),\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 1\n +-- tape at 0, [['a']]\n + at state 2\n +-- tape at 0, [['b'], ['c']]\n process (1 branch)\n + at state 3\n +-- tape at 0, [['b', 'd'], ['c', 'd']]\n process (0 branches)\n sage: it.visited_states\n {0: ['', 'bde', 'cde'], 1: ['a'], 2: ['b', 'c'], 3: ['bd', 'cd']}\n "
def __init__(self, *args, **kwargs):
"\n See :class:`_FSMProcessIteratorEpsilon_` and\n :class:`FSMProcessIterator` for more information.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, None, 'a'), (1, 2, None, 'b')])\n sage: T.state(0)._epsilon_successors_(T) # indirect doctest\n {1: [['a']], 2: [['a', 'b']]}\n "
kwargs['input_tape'] = iter([])
self.TapeCache = _FSMTapeCacheDetectEpsilon_
self.visited_states = {}
kwargs['check_epsilon_transitions'] = False
return super().__init__(*args, **kwargs)
def _push_branch_(self, state, tape_cache, outputs):
"\n This helper function does the actual adding of a ``state`` to\n ``self._current_`` (during the update of a branch), but,\n in contrast to :meth:`FSMProcessIterator._push_branch_`, it\n skips adding when the state was already visited in this branch\n (i.e. detects whether ``state`` is in an epsilon cycle).\n\n INPUT:\n\n - ``state`` -- state which has to be processed.\n\n - ``tape_cache`` -- an instance of :class:`_FSMTapeCache_` (storing\n information what to read next).\n\n - ``outputs`` -- a list of output tapes on each of which words\n were written until reaching ``state``.\n\n OUTPUT:\n\n Nothing.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, None, 'a'), (1, 2, None, 'b'),\n ....: (2, 0, None, 'c')])\n sage: T.state(0)._epsilon_successors_(T) # indirect doctest\n {0: [['a', 'b', 'c']], 1: [['a']], 2: [['a', 'b']]}\n sage: T.state(1)._epsilon_successors_(T) # indirect doctest\n {0: [['b', 'c']], 1: [['b', 'c', 'a']], 2: [['b']]}\n sage: T.state(2)._epsilon_successors_(T) # indirect doctest\n {0: [['c']], 1: [['c', 'a']], 2: [['c', 'a', 'b']]}\n "
if (state not in self.visited_states):
self.visited_states[state] = []
self.visited_states[state].extend((self.format_output(o) for o in outputs))
found = (state in tape_cache._visited_states_)
tape_cache._visited_states_.add(state)
if found:
return
super()._push_branch_(state, tape_cache, outputs)
tape_at_state = self._current_[tape_cache.position][state].tape_cache
tape_at_state._visited_states_.update(tape_cache._visited_states_)
|
class _FSMProcessIteratorAll_(FSMProcessIterator):
"\n This class is similar to :class:`FSMProcessIterator`, but\n accepts all transitions during process. See\n :class:`FSMProcessIterator` for more information.\n\n This is used in :meth:`FiniteStateMachine.language`.\n\n EXAMPLES::\n\n sage: F = FiniteStateMachine(\n ....: {'A': [('A', 0, 'z'), ('B', 1, 'o'), ('B', -1, 'm')],\n ....: 'B': [('A', 0, 'z')]},\n ....: initial_states=['A'], final_states=['A', 'B'])\n sage: from sage.combinat.finite_state_machine import _FSMProcessIteratorAll_\n sage: it = _FSMProcessIteratorAll_(F, max_length=3,\n ....: format_output=lambda o: ''.join(o))\n sage: for current in it:\n ....: print(current)\n process (2 branches)\n + at state 'A'\n +-- tape at 1, [['z']]\n + at state 'B'\n +-- tape at 1, [['m'], ['o']]\n process (2 branches)\n + at state 'A'\n +-- tape at 2, [['m', 'z'], ['o', 'z'], ['z', 'z']]\n + at state 'B'\n +-- tape at 2, [['z', 'm'], ['z', 'o']]\n process (2 branches)\n + at state 'A'\n +-- tape at 3, [['m', 'z', 'z'], ['o', 'z', 'z'], ['z', 'm', 'z'],\n ['z', 'o', 'z'], ['z', 'z', 'z']]\n + at state 'B'\n +-- tape at 3, [['m', 'z', 'm'], ['m', 'z', 'o'], ['o', 'z', 'm'],\n ['o', 'z', 'o'], ['z', 'z', 'm'], ['z', 'z', 'o']]\n process (0 branches)\n sage: it.result()\n [Branch(accept=True, state='A', output='mzz'),\n Branch(accept=True, state='A', output='ozz'),\n Branch(accept=True, state='A', output='zmz'),\n Branch(accept=True, state='A', output='zoz'),\n Branch(accept=True, state='A', output='zzz'),\n Branch(accept=True, state='B', output='mzm'),\n Branch(accept=True, state='B', output='mzo'),\n Branch(accept=True, state='B', output='ozm'),\n Branch(accept=True, state='B', output='ozo'),\n Branch(accept=True, state='B', output='zzm'),\n Branch(accept=True, state='B', output='zzo')]\n "
def __init__(self, *args, **kwargs):
"\n See :class:`_FSMProcessIteratorAll_` and\n :class:`FSMProcessIterator` for more information.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, 0, 'a'), (1, 2, 1, 'b')],\n ....: initial_states=[0], final_states=[0, 1, 2])\n sage: T.determine_alphabets()\n sage: list(T.language(2)) # indirect doctest\n [[], ['a'], ['a', 'b']]\n "
max_length = kwargs.get('max_length')
if (max_length is None):
kwargs['input_tape'] = itertools.count()
else:
kwargs['input_tape'] = iter((0 for _ in range(max_length)))
self.TapeCache = _FSMTapeCacheDetectAll_
self.visited_states = {}
kwargs['check_epsilon_transitions'] = False
return super().__init__(*args, **kwargs)
|
@cached_function
def setup_latex_preamble():
'\n This function adds the package ``tikz`` with support for automata\n to the preamble of Latex so that the finite state machines can be\n drawn nicely.\n\n See the section on :ref:`finite_state_machine_LaTeX_output`\n in the introductory examples of this module.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import setup_latex_preamble\n sage: setup_latex_preamble()\n sage: (r"\\usepackage{tikz}" in latex.extra_preamble()) == latex.has_file("tikz.sty")\n True\n '
latex.add_package_to_preamble_if_available('tikz')
if latex.has_file('tikz.sty'):
latex.add_to_preamble('\\usetikzlibrary{automata}')
|
class AutomatonGenerators():
'\n A collection of constructors for several common automata.\n\n A list of all automata in this database is available via tab\n completion. Type "``automata.``" and then hit tab to see which\n automata are available.\n\n The automata currently in this class include:\n\n - :meth:`~AnyLetter`\n - :meth:`~AnyWord`\n - :meth:`~EmptyWord`\n - :meth:`~Word`\n - :meth:`~ContainsWord`\n '
def AnyLetter(self, input_alphabet):
'\n Return an automaton recognizing any letter of the given\n input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list, the input alphabet\n\n OUTPUT:\n\n An :class:`~Automaton`.\n\n EXAMPLES::\n\n sage: A = automata.AnyLetter([0, 1])\n sage: A([])\n False\n sage: A([0])\n True\n sage: A([1])\n True\n sage: A([0, 0])\n False\n\n .. SEEALSO::\n\n :meth:`AnyWord`\n '
z = ZZ(0)
o = ZZ(1)
return Automaton([(z, o, _) for _ in input_alphabet], initial_states=[z], final_states=[o])
def AnyWord(self, input_alphabet):
'\n Return an automaton recognizing any word of the given\n input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list, the input alphabet\n\n OUTPUT:\n\n An :class:`~Automaton`.\n\n EXAMPLES::\n\n sage: A = automata.AnyWord([0, 1])\n sage: A([0])\n True\n sage: A([1])\n True\n sage: A([0, 1])\n True\n sage: A([0, 2])\n False\n\n This is equivalent to taking the :meth:`~FiniteStateMachine.kleene_star`\n of :meth:`AnyLetter` and minimizing the result. This method\n immediately gives a minimized version::\n\n sage: B = automata.AnyLetter([0, 1]).kleene_star().minimization().relabeled()\n sage: B == A\n True\n\n .. SEEALSO::\n\n :meth:`AnyLetter`,\n :meth:`Word`.\n '
z = ZZ(0)
return Automaton([(z, z, _) for _ in input_alphabet], initial_states=[z], final_states=[z])
def EmptyWord(self, input_alphabet=None):
'\n Return an automaton recognizing the empty word.\n\n INPUT:\n\n - ``input_alphabet`` -- (default: ``None``) an iterable\n or ``None``.\n\n OUTPUT:\n\n An :class:`~Automaton`.\n\n EXAMPLES::\n\n sage: A = automata.EmptyWord()\n sage: A([])\n True\n sage: A([0])\n False\n\n .. SEEALSO::\n\n :meth:`AnyLetter`,\n :meth:`AnyWord`.\n '
z = ZZ(0)
return Automaton(initial_states=[z], final_states=[z], input_alphabet=input_alphabet)
def Word(self, word, input_alphabet=None):
'\n Return an automaton recognizing the given word.\n\n INPUT:\n\n - ``word`` -- an iterable.\n\n - ``input_alphabet`` -- a list or ``None``. If ``None``,\n then the letters occurring in the word are used.\n\n OUTPUT:\n\n An :class:`~Automaton`.\n\n EXAMPLES::\n\n sage: A = automata.Word([0])\n sage: A.transitions()\n [Transition from 0 to 1: 0|-]\n sage: [A(w) for w in ([], [0], [1])]\n [False, True, False]\n sage: A = automata.Word([0, 1, 0])\n sage: A.transitions()\n [Transition from 0 to 1: 0|-,\n Transition from 1 to 2: 1|-,\n Transition from 2 to 3: 0|-]\n sage: [A(w) for w in ([], [0], [0, 1], [0, 1, 1], [0, 1, 0])]\n [False, False, False, False, True]\n\n If the input alphabet is not given, it is derived from the given\n word. ::\n\n sage: A.input_alphabet\n [0, 1]\n sage: A = automata.Word([0, 1, 0], input_alphabet=[0, 1, 2])\n sage: A.input_alphabet\n [0, 1, 2]\n\n .. SEEALSO::\n\n :meth:`AnyWord`,\n :meth:`ContainsWord`.\n\n TESTS::\n\n sage: from sage.rings.integer import is_Integer\n sage: all(is_Integer(s.label()) for s in A.states())\n True\n '
letters = list(word)
length = len(letters)
from sage.rings.integer_ring import ZZ
return Automaton([(ZZ(i), ZZ((i + 1)), letter) for (i, letter) in enumerate(letters)], initial_states=[ZZ(0)], final_states=[ZZ(length)], input_alphabet=input_alphabet)
def ContainsWord(self, word, input_alphabet):
'\n Return an automaton recognizing the words containing\n the given word as a factor.\n\n INPUT:\n\n - ``word`` -- a list (or other iterable) of letters, the\n word we are looking for.\n\n - ``input_alphabet`` -- a list or other iterable, the input\n alphabet.\n\n OUTPUT:\n\n An :class:`~Automaton`.\n\n EXAMPLES::\n\n sage: A = automata.ContainsWord([0, 1, 0, 1, 1],\n ....: input_alphabet=[0, 1])\n sage: A([1, 0, 1, 0, 1, 0, 1, 1, 0, 0])\n True\n sage: A([1, 0, 1, 0, 1, 0, 1, 0])\n False\n\n This is equivalent to taking the concatenation of :meth:`AnyWord`,\n :meth:`Word` and :meth:`AnyWord` and minimizing the result. This\n method immediately gives a minimized version::\n\n sage: B = (automata.AnyWord([0, 1]) *\n ....: automata.Word([0, 1, 0, 1, 1], [0, 1]) *\n ....: automata.AnyWord([0, 1])).minimization()\n sage: B.is_equivalent(A)\n True\n\n .. SEEALSO::\n\n :meth:`~TransducerGenerators.CountSubblockOccurrences`,\n :meth:`AnyWord`,\n :meth:`Word`.\n '
word = tuple(word)
def starts_with(what, pattern):
return ((len(what) >= len(pattern)) and (what[:len(pattern)] == pattern))
def transition_function(read, input):
if (read == word):
return (word, None)
current = (read + (input,))
k = 0
while (not starts_with(word, current[k:])):
k += 1
return (current[k:], None)
return Automaton(transition_function, input_alphabet=input_alphabet, initial_states=[()], final_states=[word])
|
class TransducerGenerators():
'\n A collection of constructors for several common transducers.\n\n A list of all transducers in this database is available via tab\n completion. Type "``transducers.``" and then hit tab to see which\n transducers are available.\n\n The transducers currently in this class include:\n\n - :meth:`~Identity`\n - :meth:`~abs`\n - :meth:`~TransducerGenerators.operator`\n - :meth:`~all`\n - :meth:`~any`\n - :meth:`~add`\n - :meth:`~sub`\n - :meth:`~CountSubblockOccurrences`\n - :meth:`~Wait`\n - :meth:`~GrayCode`\n - :meth:`~Recursion`\n '
def Identity(self, input_alphabet):
'\n Returns the identity transducer realizing the identity map.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n OUTPUT:\n\n A transducer mapping each word over ``input_alphabet`` to\n itself.\n\n EXAMPLES::\n\n sage: T = transducers.Identity([0, 1])\n sage: sorted(T.transitions())\n [Transition from 0 to 0: 0|0,\n Transition from 0 to 0: 1|1]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T.input_alphabet\n [0, 1]\n sage: T.output_alphabet\n [0, 1]\n sage: T([0, 1, 0, 1, 1])\n [0, 1, 0, 1, 1]\n\n '
return Transducer([(0, 0, d, d) for d in input_alphabet], input_alphabet=input_alphabet, output_alphabet=input_alphabet, initial_states=[0], final_states=[0])
def CountSubblockOccurrences(self, block, input_alphabet):
'\n Returns a transducer counting the number of (possibly\n overlapping) occurrences of a block in the input.\n\n INPUT:\n\n - ``block`` -- a list (or other iterable) of letters.\n\n - ``input_alphabet`` -- a list or other iterable.\n\n OUTPUT:\n\n A transducer counting (in unary) the number of occurrences of the given\n block in the input. Overlapping occurrences are counted several\n times.\n\n Denoting the block by `b_0\\ldots b_{k-1}`, the input word by\n `i_0\\ldots i_L` and the output word by `o_0\\ldots o_L`, we\n have `o_j = 1` if and only if `i_{j-k+1}\\ldots i_{j} = b_0\\ldots\n b_{k-1}`. Otherwise, `o_j = 0`.\n\n EXAMPLES:\n\n #. Counting the number of ``10`` blocks over the alphabet\n ``[0, 1]``::\n\n sage: T = transducers.CountSubblockOccurrences(\n ....: [1, 0],\n ....: [0, 1])\n sage: sorted(T.transitions())\n [Transition from () to (): 0|0,\n Transition from () to (1,): 1|0,\n Transition from (1,) to (): 0|1,\n Transition from (1,) to (1,): 1|0]\n sage: T.input_alphabet\n [0, 1]\n sage: T.output_alphabet\n [0, 1]\n sage: T.initial_states()\n [()]\n sage: T.final_states()\n [(), (1,)]\n\n Check some sequence::\n\n sage: T([0, 1, 0, 1, 1, 0])\n [0, 0, 1, 0, 0, 1]\n\n #. Counting the number of ``11`` blocks over the alphabet\n ``[0, 1]``::\n\n sage: T = transducers.CountSubblockOccurrences(\n ....: [1, 1],\n ....: [0, 1])\n sage: sorted(T.transitions())\n [Transition from () to (): 0|0,\n Transition from () to (1,): 1|0,\n Transition from (1,) to (): 0|0,\n Transition from (1,) to (1,): 1|1]\n\n Check some sequence::\n\n sage: T([0, 1, 0, 1, 1, 0])\n [0, 0, 0, 0, 1, 0]\n\n #. Counting the number of ``1010`` blocks over the\n alphabet ``[0, 1, 2]``::\n\n sage: T = transducers.CountSubblockOccurrences(\n ....: [1, 0, 1, 0],\n ....: [0, 1, 2])\n sage: sorted(T.transitions())\n [Transition from () to (): 0|0,\n Transition from () to (1,): 1|0,\n Transition from () to (): 2|0,\n Transition from (1,) to (1, 0): 0|0,\n Transition from (1,) to (1,): 1|0,\n Transition from (1,) to (): 2|0,\n Transition from (1, 0) to (): 0|0,\n Transition from (1, 0) to (1, 0, 1): 1|0,\n Transition from (1, 0) to (): 2|0,\n Transition from (1, 0, 1) to (1, 0): 0|1,\n Transition from (1, 0, 1) to (1,): 1|0,\n Transition from (1, 0, 1) to (): 2|0]\n sage: input = [0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 2]\n sage: output = [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]\n sage: T(input) == output\n True\n\n .. SEEALSO::\n\n :meth:`~AutomatonGenerators.ContainsWord`\n '
block_as_tuple = tuple(block)
def starts_with(what, pattern):
return ((len(what) >= len(pattern)) and (what[:len(pattern)] == pattern))
def transition_function(read, input):
current = (read + (input,))
if (starts_with(block_as_tuple, current) and (len(block_as_tuple) > len(current))):
return (current, 0)
else:
k = 1
while (not starts_with(block_as_tuple, current[k:])):
k += 1
return (current[k:], int((block_as_tuple == current)))
T = Transducer(transition_function, input_alphabet=input_alphabet, output_alphabet=[0, 1], initial_states=[()])
for s in T.iter_states():
s.is_final = True
return T
def Wait(self, input_alphabet, threshold=1):
"\n Writes ``False`` until reading the ``threshold``-th occurrence\n of a true input letter; then writes ``True``.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``threshold`` -- a positive integer specifying how many\n occurrences of ``True`` inputs are waited for.\n\n OUTPUT:\n\n A transducer writing ``False`` until the ``threshold``-th true\n (Python's standard conversion to boolean is used to convert the\n actual input to boolean) input is read. Subsequently, the\n transducer writes ``True``.\n\n EXAMPLES::\n\n sage: T = transducers.Wait([0, 1])\n sage: T([0, 0, 1, 0, 1, 0])\n [False, False, True, True, True, True]\n sage: T2 = transducers.Wait([0, 1], threshold=2)\n sage: T2([0, 0, 1, 0, 1, 0])\n [False, False, False, False, True, True]\n "
def transition(state, input):
if (state == threshold):
return (threshold, True)
if (not input):
return (state, False)
return ((state + 1), ((state + 1) == threshold))
T = Transducer(transition, input_alphabet=input_alphabet, initial_states=[0])
for s in T.iter_states():
s.is_final = True
return T
def map(self, f, input_alphabet):
'\n Return a transducer which realizes a function\n on the alphabet.\n\n INPUT:\n\n - ``f`` -- function to realize.\n\n - ``input_alphabet`` -- a list or other iterable.\n\n OUTPUT:\n\n A transducer mapping an input letter `x` to\n `f(x)`.\n\n EXAMPLES:\n\n The following binary transducer realizes component-wise\n absolute value (this transducer is also available as :meth:`.abs`)::\n\n sage: T = transducers.map(abs, [-1, 0, 1])\n sage: T.transitions()\n [Transition from 0 to 0: -1|1,\n Transition from 0 to 0: 0|0,\n Transition from 0 to 0: 1|1]\n sage: T.input_alphabet\n [-1, 0, 1]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([-1, 1, 0, 1])\n [1, 1, 0, 1]\n\n .. SEEALSO::\n\n :meth:`Automaton.with_output()\n <sage.combinat.finite_state_machine.Automaton.with_output>`.\n '
return Transducer((lambda state, input: (0, f(input))), input_alphabet=input_alphabet, initial_states=[0], final_states=[0])
def operator(self, operator, input_alphabet, number_of_operands=2):
'\n Returns a transducer which realizes an operation\n on tuples over the given input alphabet.\n\n INPUT:\n\n - ``operator`` -- operator to realize. It is a function which\n takes ``number_of_operands`` input arguments (each out of\n ``input_alphabet``).\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``number_of_operands`` -- (default: `2`) it specifies the number\n of input arguments the operator takes.\n\n OUTPUT:\n\n A transducer mapping an input letter `(i_1, \\dots, i_n)` to\n `\\mathrm{operator}(i_1, \\dots, i_n)`. Here, `n` equals\n ``number_of_operands``.\n\n The input alphabet of the generated transducer is the Cartesian\n product of ``number_of_operands`` copies of ``input_alphabet``.\n\n EXAMPLES:\n\n The following binary transducer realizes component-wise\n addition (this transducer is also available as :meth:`.add`)::\n\n sage: import operator\n sage: T = transducers.operator(operator.add, [0, 1])\n sage: T.transitions()\n [Transition from 0 to 0: (0, 0)|0,\n Transition from 0 to 0: (0, 1)|1,\n Transition from 0 to 0: (1, 0)|1,\n Transition from 0 to 0: (1, 1)|2]\n sage: T.input_alphabet\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([(0, 0), (0, 1), (1, 0), (1, 1)])\n [0, 1, 1, 2]\n\n Note that for a unary operator the input letters of the\n new transducer are tuples of length `1`::\n\n sage: T = transducers.operator(abs,\n ....: [-1, 0, 1],\n ....: number_of_operands=1)\n sage: T([-1, 1, 0])\n Traceback (most recent call last):\n ...\n ValueError: Invalid input sequence.\n sage: T([(-1,), (1,), (0,)])\n [1, 1, 0]\n\n Compare this with the transducer generated by :meth:`.map`::\n\n sage: T = transducers.map(abs,\n ....: [-1, 0, 1])\n sage: T([-1, 1, 0])\n [1, 1, 0]\n\n In fact, this transducer is also available as :meth:`.abs`::\n\n sage: T = transducers.abs([-1, 0, 1])\n sage: T([-1, 1, 0])\n [1, 1, 0]\n '
from itertools import product
def transition_function(state, operands):
return (0, operator(*operands))
pairs = list(product(input_alphabet, repeat=number_of_operands))
return Transducer(transition_function, input_alphabet=pairs, initial_states=[0], final_states=[0])
def all(self, input_alphabet, number_of_operands=2):
'\n Returns a transducer which realizes logical ``and`` over the given\n input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``number_of_operands`` -- (default: `2`) specifies the number\n of input arguments for the ``and`` operation.\n\n OUTPUT:\n\n A transducer mapping an input word\n `(i_{01}, \\ldots, i_{0d})\\ldots (i_{k1}, \\ldots, i_{kd})` to the word\n `(i_{01} \\land \\cdots \\land i_{0d})\\ldots (i_{k1} \\land \\cdots \\land i_{kd})`.\n\n The input alphabet of the generated transducer is the Cartesian\n product of ``number_of_operands`` copies of ``input_alphabet``.\n\n EXAMPLES:\n\n The following transducer realizes letter-wise\n logical ``and``::\n\n sage: T = transducers.all([False, True])\n sage: T.transitions()\n [Transition from 0 to 0: (False, False)|False,\n Transition from 0 to 0: (False, True)|False,\n Transition from 0 to 0: (True, False)|False,\n Transition from 0 to 0: (True, True)|True]\n sage: T.input_alphabet\n [(False, False), (False, True), (True, False), (True, True)]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([(False, False), (False, True), (True, False), (True, True)])\n [False, False, False, True]\n\n More than two operands and other input alphabets (with\n conversion to boolean) are also possible::\n\n sage: T3 = transducers.all([0, 1], number_of_operands=3)\n sage: T3([(0, 0, 0), (1, 0, 0), (1, 1, 1)])\n [False, False, True]\n '
return self.operator((lambda *args: all(args)), input_alphabet, number_of_operands)
def any(self, input_alphabet, number_of_operands=2):
'\n Returns a transducer which realizes logical ``or`` over the given\n input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``number_of_operands`` -- (default: `2`) specifies the number\n of input arguments for the ``or`` operation.\n\n OUTPUT:\n\n A transducer mapping an input word\n `(i_{01}, \\ldots, i_{0d})\\ldots (i_{k1}, \\ldots, i_{kd})` to the word\n `(i_{01} \\lor \\cdots \\lor i_{0d})\\ldots (i_{k1} \\lor \\cdots \\lor i_{kd})`.\n\n The input alphabet of the generated transducer is the Cartesian\n product of ``number_of_operands`` copies of ``input_alphabet``.\n\n EXAMPLES:\n\n The following transducer realizes letter-wise\n logical ``or``::\n\n sage: T = transducers.any([False, True])\n sage: T.transitions()\n [Transition from 0 to 0: (False, False)|False,\n Transition from 0 to 0: (False, True)|True,\n Transition from 0 to 0: (True, False)|True,\n Transition from 0 to 0: (True, True)|True]\n sage: T.input_alphabet\n [(False, False), (False, True), (True, False), (True, True)]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([(False, False), (False, True), (True, False), (True, True)])\n [False, True, True, True]\n\n More than two operands and other input alphabets (with\n conversion to boolean) are also possible::\n\n sage: T3 = transducers.any([0, 1], number_of_operands=3)\n sage: T3([(0, 0, 0), (1, 0, 0), (1, 1, 1)])\n [False, True, True]\n '
return self.operator((lambda *args: any(args)), input_alphabet, number_of_operands)
def add(self, input_alphabet, number_of_operands=2):
'\n Returns a transducer which realizes addition on pairs over the\n given input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``number_of_operands`` -- (default: `2`) it specifies the number\n of input arguments the operator takes.\n\n OUTPUT:\n\n A transducer mapping an input word\n `(i_{01}, \\ldots, i_{0d})\\ldots (i_{k1}, \\ldots, i_{kd})` to the word\n `(i_{01} + \\cdots + i_{0d})\\ldots (i_{k1} + \\cdots + i_{kd})`.\n\n The input alphabet of the generated transducer is the Cartesian\n product of ``number_of_operands`` copies of ``input_alphabet``.\n\n EXAMPLES:\n\n The following transducer realizes letter-wise\n addition::\n\n sage: T = transducers.add([0, 1])\n sage: T.transitions()\n [Transition from 0 to 0: (0, 0)|0,\n Transition from 0 to 0: (0, 1)|1,\n Transition from 0 to 0: (1, 0)|1,\n Transition from 0 to 0: (1, 1)|2]\n sage: T.input_alphabet\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([(0, 0), (0, 1), (1, 0), (1, 1)])\n [0, 1, 1, 2]\n\n More than two operands can also be handled::\n\n sage: T3 = transducers.add([0, 1], number_of_operands=3)\n sage: T3.input_alphabet\n [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),\n (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]\n sage: T3([(0, 0, 0), (0, 1, 0), (0, 1, 1), (1, 1, 1)])\n [0, 1, 2, 3]\n '
return self.operator((lambda *args: sum(args)), input_alphabet, number_of_operands=number_of_operands)
def sub(self, input_alphabet):
"\n Returns a transducer which realizes subtraction on pairs over\n the given input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n OUTPUT:\n\n A transducer mapping an input word `(i_0, i'_0)\\ldots (i_k, i'_k)`\n to the word `(i_0 - i'_0)\\ldots (i_k - i'_k)`.\n\n The input alphabet of the generated transducer is the Cartesian\n product of two copies of ``input_alphabet``.\n\n EXAMPLES:\n\n The following transducer realizes letter-wise\n subtraction::\n\n sage: T = transducers.sub([0, 1])\n sage: T.transitions()\n [Transition from 0 to 0: (0, 0)|0,\n Transition from 0 to 0: (0, 1)|-1,\n Transition from 0 to 0: (1, 0)|1,\n Transition from 0 to 0: (1, 1)|0]\n sage: T.input_alphabet\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([(0, 0), (0, 1), (1, 0), (1, 1)])\n [0, -1, 1, 0]\n "
return self.operator(operator.sub, input_alphabet)
def weight(self, input_alphabet, zero=0):
"\n Returns a transducer which realizes the Hamming weight of the input\n over the given input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n - ``zero`` -- the zero symbol in the alphabet used\n\n OUTPUT:\n\n A transducer mapping `i_0\\ldots i_k` to `(i_0\\neq 0)\\ldots(i_k\\neq 0)`.\n\n The Hamming weight is defined as the number of non-zero digits in the\n input sequence over the alphabet ``input_alphabet`` (see\n :wikipedia:`Hamming_weight`). The output sequence of the transducer is\n a unary encoding of the Hamming weight. Thus the sum of the output\n sequence is the Hamming weight of the input.\n\n EXAMPLES::\n\n sage: W = transducers.weight([-1, 0, 2])\n sage: W.transitions()\n [Transition from 0 to 0: -1|1,\n Transition from 0 to 0: 0|0,\n Transition from 0 to 0: 2|1]\n sage: unary_weight = W([-1, 0, 0, 2, -1])\n sage: unary_weight\n [1, 0, 0, 1, 1]\n sage: weight = add(unary_weight)\n sage: weight\n 3\n\n Also the joint Hamming weight can be computed::\n\n sage: v1 = vector([-1, 0])\n sage: v0 = vector([0, 0])\n sage: W = transducers.weight([v1, v0])\n sage: unary_weight = W([v1, v0, v1, v0])\n sage: add(unary_weight)\n 2\n\n For the input alphabet ``[-1, 0, 1]`` the weight transducer is the\n same as the absolute value transducer\n :meth:`~TransducerGenerators.abs`::\n\n sage: W = transducers.weight([-1, 0, 1])\n sage: A = transducers.abs([-1, 0, 1])\n sage: W == A\n True\n\n For other input alphabets, we can specify the zero symbol::\n\n sage: W = transducers.weight(['a', 'b'], zero='a')\n sage: add(W(['a', 'b', 'b']))\n 2\n "
def weight(state, input):
weight = int((input != zero))
return (0, weight)
return Transducer(weight, input_alphabet=input_alphabet, initial_states=[0], final_states=[0])
def abs(self, input_alphabet):
'\n Returns a transducer which realizes the letter-wise\n absolute value of an input word over the given input alphabet.\n\n INPUT:\n\n - ``input_alphabet`` -- a list or other iterable.\n\n OUTPUT:\n\n A transducer mapping `i_0\\ldots i_k`\n to `|i_0|\\ldots |i_k|`.\n\n EXAMPLES:\n\n The following transducer realizes letter-wise\n absolute value::\n\n sage: T = transducers.abs([-1, 0, 1])\n sage: T.transitions()\n [Transition from 0 to 0: -1|1,\n Transition from 0 to 0: 0|0,\n Transition from 0 to 0: 1|1]\n sage: T.initial_states()\n [0]\n sage: T.final_states()\n [0]\n sage: T([-1, -1, 0, 1])\n [1, 1, 0, 1]\n\n '
return self.map(abs, input_alphabet)
def GrayCode(self):
'\n Returns a transducer converting the standard binary\n expansion to Gray code.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A transducer.\n\n Cf. the :wikipedia:`Gray_code` for a description of the Gray code.\n\n EXAMPLES::\n\n sage: G = transducers.GrayCode()\n sage: G\n Transducer with 3 states\n sage: for v in srange(10):\n ....: print("{} {}".format(v, G(v.digits(base=2))))\n 0 []\n 1 [1]\n 2 [1, 1]\n 3 [0, 1]\n 4 [0, 1, 1]\n 5 [1, 1, 1]\n 6 [1, 0, 1]\n 7 [0, 0, 1]\n 8 [0, 0, 1, 1]\n 9 [1, 0, 1, 1]\n\n In the example :ref:`Gray Code <finite_state_machine_gray_code_example>`\n in the documentation of the\n :doc:`finite_state_machine` module, the Gray code\n transducer is derived from the algorithm converting the binary\n expansion to the Gray code. The result is the same as the one\n given here.\n '
z = ZZ(0)
o = ZZ(1)
return Transducer([[0, 1, z, None], [0, 2, o, None], [1, 1, z, z], [1, 2, o, o], [2, 1, z, o], [2, 2, o, z]], initial_states=[0], final_states=[1], with_final_word_out=[0])
RecursionRule = namedtuple('RecursionRule', ['K', 'r', 'k', 's', 't'])
def _parse_recursion_equation_(self, equation, base, function, var, word_function=None, output_rings=[ZZ, QQ]):
"\n Parse one equation as admissible in :meth:`~.Recursion`.\n\n INPUT:\n\n - ``equation`` -- An equation of the form\n\n - ``f(base^K * n + r) == f(base^k * n + s) + t`` for some\n integers ``0 <= k < K``, ``r`` and some ``t``---valid for\n all ``n`` such that the arguments on both sides are\n non-negative---\n\n or the form\n\n - ``f(r) == t`` for some integer ``r`` and some ``t``.\n\n - ``base`` -- see :meth:`~Recursion`.\n\n - ``function`` -- see :meth:`~Recursion`.\n\n - ``var`` -- see :meth:`~Recursion`.\n\n - ``output_rings`` -- see :meth:`~Recursion`.\n\n OUTPUT:\n\n A ``RecursionRule`` if the equation is of the first form\n described above and a dictionary ``{r: [t]}`` otherwise.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: var('n')\n n\n sage: function('f')\n f\n sage: transducers._parse_recursion_equation_(\n ....: f(8*n + 7) == f(2*n + 3) + 5,\n ....: 2, f, n)\n RecursionRule(K=3, r=7, k=1, s=3, t=[5])\n sage: transducers._parse_recursion_equation_(\n ....: f(42) == 5,\n ....: 2, f, n)\n {42: [5]}\n\n TESTS:\n\n The following tests check that the equations are well-formed::\n\n sage: transducers._parse_recursion_equation_(f(4*n + 1), 2, f, n) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n ValueError: f(4*n + 1) is not an equation with ==.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(n) + 1 == f(2*n), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: f(n) + 1 is not an evaluation of f.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n, 5) == 3, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: f(2*n, 5) does not have one argument.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(1/n) == f(n) + 3, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 1/n is not a polynomial in n.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(n^2 + 5) == 3, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: n^2 + 5 is not a polynomial of degree 1.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(3*n + 5) == f(n) + 7, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 3 is not a power of 2.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(n + 5) == f(n) + 7, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 1 is less than 2.\n\n ::\n\n sage: transducers._parse_recursion_equation_( # needs sage.symbolic\n ....: f(2*n + 1) == f(n + 1) + f(n) + 2,\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: f(n + 1) + f(n) + 2 does not contain\n exactly one summand which is an evaluation of f.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == sin(n) + 2, # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: sin(n) + 2 does not contain exactly one\n summand which is an evaluation of f.\n\n ::\n\n sage: transducers._parse_recursion_equation_( # needs sage.symbolic\n ....: f(2*n + 1) == f(n) + n + 2,\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: n + 2 contains n.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == sin(n), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: sin(n) is not an evaluation of f.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == f(n, 2), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: f(n, 2) does not have exactly one argument.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == f(1/n), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 1/n is not a polynomial in n.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == f(n^2 + 5), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: n^2 + 5 is not a polynomial of degree 1.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == f(3*n + 5), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 3 is not a power of 2.\n\n ::\n\n sage: transducers._parse_recursion_equation_( # needs sage.symbolic\n ....: f(2*n + 1) == f((1/2)*n + 5),\n ....: QQ(2), f, n)\n Traceback (most recent call last):\n ...\n ValueError: 1/2 is less than 1.\n\n ::\n\n sage: transducers._parse_recursion_equation_(f(2*n + 1) == f(2*n + 5), # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: 2 is greater or equal than 2.\n "
from sage.functions.log import log
def is_scalar(expression):
return (var not in expression.variables())
def convert_output(output):
for ring in output_rings:
try:
return ring(output)
except (ValueError, TypeError):
pass
return output
def to_list(output):
if (output == 0):
return []
elif ((word_function is not None) and (output.operator() == word_function)):
return [convert_output(_) for _ in output.operands()]
else:
return [convert_output(output)]
base_ring = base.parent()
if (equation.operator() != operator.eq):
raise ValueError(('%s is not an equation with ==.' % equation))
assert (len(equation.operands()) == 2), ('%s is not an equation with two operands.' % equation)
(left_side, right_side) = equation.operands()
if (left_side.operator() != function):
raise ValueError(('%s is not an evaluation of %s.' % (left_side, function)))
if (len(left_side.operands()) != 1):
raise ValueError(('%s does not have one argument.' % (left_side,)))
try:
polynomial_left = base_ring[var](left_side.operands()[0])
except Exception:
raise ValueError(('%s is not a polynomial in %s.' % (left_side.operands()[0], var)))
if ((polynomial_left in base_ring) and is_scalar(right_side)):
return {polynomial_left: to_list(right_side)}
if (polynomial_left.degree() != 1):
raise ValueError(('%s is not a polynomial of degree 1.' % (polynomial_left,)))
[r, base_power_K] = list(polynomial_left)
try:
K = log(base_power_K, base=base)
except RuntimeError:
K = 1
try:
K = K.simplify()
except AttributeError:
pass
if (K not in ZZ):
raise ValueError(('%s is not a power of %s.' % (base_power_K, base)))
if (K < 1):
raise ValueError(('%d is less than %d.' % (base_power_K, base)))
from sage.symbolic.operators import add_vararg
if (right_side.operator() == add_vararg):
function_calls = [o for o in right_side.operands() if (o.operator() == function)]
other_terms = [o for o in right_side.operands() if (o.operator() != function)]
if (len(function_calls) != 1):
raise ValueError(('%s does not contain exactly one summand which is an evaluation of %s.' % (right_side, function)))
next_function = function_calls[0]
t = sum(other_terms)
if (not is_scalar(t)):
raise ValueError(('%s contains %s.' % (t, var)))
else:
next_function = right_side
t = 0
if (next_function.operator() != function):
raise ValueError(('%s is not an evaluation of %s.' % (next_function, function)))
if (len(next_function.operands()) != 1):
raise ValueError(('%s does not have exactly one argument.' % (next_function,)))
try:
polynomial_right = base_ring[var](next_function.operands()[0])
except Exception:
raise ValueError(('%s is not a polynomial in %s.' % (next_function.operands()[0], var)))
if (polynomial_right.degree() != 1):
raise ValueError(('%s is not a polynomial of degree 1.' % (polynomial_right,)))
[s, base_power_k] = list(polynomial_right)
k = log(base_power_k, base=base)
try:
k = k.simplify()
except AttributeError:
pass
if (k not in ZZ):
raise ValueError(('%s is not a power of %s.' % (base_power_k, base)))
if (k < 0):
raise ValueError(('%s is less than 1.' % (base_power_k,)))
if (k >= K):
raise ValueError(('%d is greater or equal than %d.' % (base_power_k, base_power_K)))
parsed_equation = (function((((base ** K) * var) + r)) == (function((((base ** k) * var) + s)) + t))
assert (equation == parsed_equation), ('Parsing of %s failed for unknown reasons.' % (equation,))
rule = self.RecursionRule(K=K, r=r, k=k, s=s, t=to_list(t))
return rule
def Recursion(self, recursions, base, function=None, var=None, input_alphabet=None, word_function=None, is_zero=None, output_rings=[ZZ, QQ]):
'\n Return a transducer realizing the given recursion when reading\n the digit expansion with base ``base``.\n\n INPUT:\n\n - ``recursions`` -- list or iterable of equations. Each\n equation has either the form\n\n - ``f(base^K * n + r) == f(base^k * n + s) + t`` for some\n integers ``0 <= k < K``, ``r`` and some ``t``---valid for\n all ``n`` such that the arguments on both sides are\n non-negative---\n\n or the form\n\n - ``f(r) == t`` for some integer ``r`` and some ``t``.\n\n Alternatively, an equation may be replaced by a\n ``transducers.RecursionRule`` with the attributes ``K``,\n ``r``, ``k``, ``s``, ``t`` as above or a tuple ``(r, t)``.\n Note that ``t`` *must* be a list in this case.\n\n - ``base`` -- base of the digit expansion.\n\n - ``function`` -- symbolic function ``f`` occurring in the\n recursions.\n\n - ``var`` -- symbolic variable.\n\n - ``input_alphabet`` -- (default: ``None``) a list of digits\n to be used as the input alphabet. If ``None`` and the base\n is an integer, ``input_alphabet`` is chosen to be\n ``srange(base.abs())``.\n\n - ``word_function`` -- (default: ``None``) a symbolic function.\n If not ``None``, ``word_function(arg1, ..., argn)`` in a symbolic\n recurrence relation is interpreted as a transition with output\n ``[arg1, ..., argn]``. This could not be entered in a symbolic\n recurrence relation because lists do not coerce into the\n :class:`~sage.symbolic.ring.SymbolicRing`.\n\n - ``is_zero`` -- (default: ``None``) a callable. The recursion\n relations are only well-posed if there is no cycle with\n non-zero output and input consisting of zeros. This parameter\n is used to determine whether the output of such a cycle is\n non-zero. By default, the output must evaluate to ``False`` as\n a boolean.\n\n - ``output_rings`` -- (default: ``[ZZ, QQ]``) a list of\n rings. The output labels are converted into the first ring of\n the list in which they are contained. If they are not\n contained in any ring, they remain in whatever ring they are\n after parsing the recursions, typically the symbolic ring.\n\n OUTPUT:\n\n A transducer ``T``.\n\n The transducer is constructed such that ``T(expansion) == f(n)``\n if ``expansion`` is the digit expansion of ``n`` to the base\n ``base`` with the given input alphabet as set of digits. Here,\n the ``+`` on the right hand side of the recurrence relation is\n interpreted as the concatenation of words.\n\n The formal equations and initial conditions in the recursion\n have to be selected such that ``f`` is uniquely defined.\n\n EXAMPLES:\n\n - The following example computes the Hamming weight of the\n ternary expansion of integers. ::\n\n sage: # needs sage.symbolic\n sage: function(\'f\')\n f\n sage: var(\'n\')\n n\n sage: T = transducers.Recursion([\n ....: f(3*n + 1) == f(n) + 1,\n ....: f(3*n + 2) == f(n) + 1,\n ....: f(3*n) == f(n),\n ....: f(0) == 0],\n ....: 3, f, n)\n sage: T.transitions()\n [Transition from (0, 0) to (0, 0): 0|-,\n Transition from (0, 0) to (0, 0): 1|1,\n Transition from (0, 0) to (0, 0): 2|1]\n\n To illustrate what this transducer does, we consider the\n example of `n=601`::\n\n sage: # needs sage.symbolic\n sage: ternary_expansion = 601.digits(base=3)\n sage: ternary_expansion\n [1, 2, 0, 1, 1, 2]\n sage: weight_sequence = T(ternary_expansion)\n sage: weight_sequence\n [1, 1, 1, 1, 1]\n sage: sum(weight_sequence)\n 5\n\n Note that the digit zero does not show up in the output because\n the equation ``f(3*n) == f(n)`` means that no output is added to\n ``f(n)``.\n\n - The following example computes the Hamming weight of the\n non-adjacent form, cf. the :wikipedia:`Non-adjacent_form`. ::\n\n sage: # needs sage.symbolic\n sage: function(\'f\')\n f\n sage: var(\'n\')\n n\n sage: T = transducers.Recursion([\n ....: f(4*n + 1) == f(n) + 1,\n ....: f(4*n - 1) == f(n) + 1,\n ....: f(2*n) == f(n),\n ....: f(0) == 0],\n ....: 2, f, n)\n sage: T.transitions()\n [Transition from (0, 0) to (0, 0): 0|-,\n Transition from (0, 0) to (1, 1): 1|-,\n Transition from (1, 1) to (0, 0): 0|1,\n Transition from (1, 1) to (1, 0): 1|1,\n Transition from (1, 0) to (1, 1): 0|-,\n Transition from (1, 0) to (1, 0): 1|-]\n sage: [(s.label(), s.final_word_out)\n ....: for s in T.iter_final_states()]\n [((0, 0), []),\n ((1, 1), [1]),\n ((1, 0), [1])]\n\n As we are interested in the weight only, we also output `1`\n for numbers congruent to `3` mod `4`. The actual expansion\n is computed in the next example.\n\n Consider the example of `29=(100\\bar 101)_2` (as usual,\n the digit `-1` is denoted by `\\bar 1` and digits are\n written from the most significant digit at the left to the\n least significant digit at the right; for the transducer,\n we have to give the digits in the reverse order)::\n\n sage: NAF = [1, 0, -1, 0, 0, 1]\n sage: ZZ(NAF, base=2)\n 29\n sage: binary_expansion = 29.digits(base=2)\n sage: binary_expansion\n [1, 0, 1, 1, 1]\n sage: T(binary_expansion) # needs sage.symbolic\n [1, 1, 1]\n sage: sum(T(binary_expansion)) # needs sage.symbolic\n 3\n\n Indeed, the given non-adjacent form has three non-zero\n digits.\n\n - The following example computes the non-adjacent form from the\n binary expansion, cf. the :wikipedia:`Non-adjacent_form`. In\n contrast to the previous example, we actually compute the\n expansion, not only the weight.\n\n We have to write the output `0` when converting an even number.\n This cannot be encoded directly by an equation in the symbolic\n ring, because ``f(2*n) == f(n) + 0`` would be equivalent to\n ``f(2*n) == f(n)`` and an empty output would be written.\n Therefore, we wrap the output in the symbolic function ``w``\n and use the parameter ``word_function`` to announce this.\n\n Similarly, we use ``w(-1, 0)`` to write an output word of\n length `2` in one iteration. Finally, we write ``f(0) == w()``\n to write an empty word upon completion.\n\n Moreover, there is a cycle with output ``[0]`` which---from\n the point of view of this method---is a contradicting recursion.\n We override this by the parameter ``is_zero``. ::\n\n sage: # needs sage.symbolic\n sage: var(\'n\')\n n\n sage: function(\'f w\')\n (f, w)\n sage: T = transducers.Recursion([\n ....: f(2*n) == f(n) + w(0),\n ....: f(4*n + 1) == f(n) + w(1, 0),\n ....: f(4*n - 1) == f(n) + w(-1, 0),\n ....: f(0) == w()],\n ....: 2, f, n,\n ....: word_function=w,\n ....: is_zero=lambda x: sum(x).is_zero())\n sage: T.transitions()\n [Transition from (0, 0) to (0, 0): 0|0,\n Transition from (0, 0) to (1, 1): 1|-,\n Transition from (1, 1) to (0, 0): 0|1,0,\n Transition from (1, 1) to (1, 0): 1|-1,0,\n Transition from (1, 0) to (1, 1): 0|-,\n Transition from (1, 0) to (1, 0): 1|0]\n sage: for s in T.iter_states():\n ....: print("{} {}".format(s, s.final_word_out))\n (0, 0) []\n (1, 1) [1, 0]\n (1, 0) [1, 0]\n\n We again consider the example of `n=29`::\n\n sage: T(29.digits(base=2)) # needs sage.symbolic\n [1, 0, -1, 0, 0, 1, 0]\n\n The same transducer can also be entered bypassing the\n symbolic equations::\n\n sage: R = transducers.RecursionRule\n sage: TR = transducers.Recursion([\n ....: R(K=1, r=0, k=0, s=0, t=[0]),\n ....: R(K=2, r=1, k=0, s=0, t=[1, 0]),\n ....: R(K=2, r=-1, k=0, s=0, t=[-1, 0]),\n ....: (0, [])],\n ....: 2,\n ....: is_zero=lambda x: sum(x).is_zero())\n sage: TR == T # needs sage.symbolic\n True\n\n - Here is an artificial example where some of the `s` are\n negative::\n\n sage: # needs sage.symbolic\n sage: function(\'f\')\n f\n sage: var(\'n\')\n n\n sage: T = transducers.Recursion([\n ....: f(2*n + 1) == f(n-1) + 1,\n ....: f(2*n) == f(n),\n ....: f(1) == 1,\n ....: f(0) == 0], 2, f, n)\n sage: T.transitions()\n [Transition from (0, 0) to (0, 0): 0|-,\n Transition from (0, 0) to (1, 1): 1|-,\n Transition from (1, 1) to (-1, 1): 0|1,\n Transition from (1, 1) to (0, 0): 1|1,\n Transition from (-1, 1) to (-1, 2): 0|-,\n Transition from (-1, 1) to (1, 2): 1|-,\n Transition from (-1, 2) to (-1, 1): 0|1,\n Transition from (-1, 2) to (0, 0): 1|1,\n Transition from (1, 2) to (-1, 2): 0|1,\n Transition from (1, 2) to (1, 2): 1|1]\n sage: [(s.label(), s.final_word_out)\n ....: for s in T.iter_final_states()]\n [((0, 0), []),\n ((1, 1), [1]),\n ((-1, 1), [0]),\n ((-1, 2), [0]),\n ((1, 2), [1])]\n\n - Abelian complexity of the paperfolding sequence\n (cf. [HKP2015]_, Example 2.8)::\n\n sage: # needs sage.symbolic\n sage: T = transducers.Recursion([\n ....: f(4*n) == f(2*n),\n ....: f(4*n+2) == f(2*n+1)+1,\n ....: f(16*n+1) == f(8*n+1),\n ....: f(16*n+5) == f(4*n+1)+2,\n ....: f(16*n+11) == f(4*n+3)+2,\n ....: f(16*n+15) == f(2*n+2)+1,\n ....: f(1) == 2, f(0) == 0]\n ....: + [f(16*n+jj) == f(2*n+1)+2 for jj in [3,7,9,13]],\n ....: 2, f, n)\n sage: T.transitions()\n [Transition from (0, 0) to (0, 1): 0|-,\n Transition from (0, 0) to (1, 1): 1|-,\n Transition from (0, 1) to (0, 1): 0|-,\n Transition from (0, 1) to (1, 1): 1|1,\n Transition from (1, 1) to (1, 2): 0|-,\n Transition from (1, 1) to (3, 2): 1|-,\n Transition from (1, 2) to (1, 3): 0|-,\n Transition from (1, 2) to (5, 3): 1|-,\n Transition from (3, 2) to (3, 3): 0|-,\n Transition from (3, 2) to (7, 3): 1|-,\n Transition from (1, 3) to (1, 3): 0|-,\n Transition from (1, 3) to (1, 1): 1|2,\n Transition from (5, 3) to (1, 2): 0|2,\n Transition from (5, 3) to (1, 1): 1|2,\n Transition from (3, 3) to (1, 1): 0|2,\n Transition from (3, 3) to (3, 2): 1|2,\n Transition from (7, 3) to (1, 1): 0|2,\n Transition from (7, 3) to (2, 1): 1|1,\n Transition from (2, 1) to (1, 1): 0|1,\n Transition from (2, 1) to (2, 1): 1|-]\n sage: for s in T.iter_states():\n ....: print("{} {}".format(s, s.final_word_out))\n (0, 0) []\n (0, 1) []\n (1, 1) [2]\n (1, 2) [2]\n (3, 2) [2, 2]\n (1, 3) [2]\n (5, 3) [2, 2]\n (3, 3) [2, 2]\n (7, 3) [2, 2]\n (2, 1) [1, 2]\n sage: list(sum(T(n.bits())) for n in srange(1, 21))\n [2, 3, 4, 3, 4, 5, 4, 3, 4, 5, 6, 5, 4, 5, 4, 3, 4, 5, 6, 5]\n\n - We now demonstrate the use of the ``output_rings``\n parameter. If no ``output_rings`` are specified, the\n output labels are converted into ``ZZ``::\n\n sage: # needs sage.symbolic\n sage: function(\'f\')\n f\n sage: var(\'n\')\n n\n sage: T = transducers.Recursion([\n ....: f(2*n + 1) == f(n) + 1,\n ....: f(2*n) == f(n),\n ....: f(0) == 2],\n ....: 2, f, n)\n sage: for t in T.transitions():\n ....: print([x.parent() for x in t.word_out])\n []\n [Integer Ring]\n sage: [x.parent() for x in T.states()[0].final_word_out]\n [Integer Ring]\n\n In contrast, if ``output_rings`` is set to the empty list, the\n results are not converted::\n\n sage: T = transducers.Recursion([ # needs sage.symbolic\n ....: f(2*n + 1) == f(n) + 1,\n ....: f(2*n) == f(n),\n ....: f(0) == 2],\n ....: 2, f, n, output_rings=[])\n sage: for t in T.transitions(): # needs sage.symbolic\n ....: print([x.parent() for x in t.word_out])\n []\n [Symbolic Ring]\n sage: [x.parent() for x in T.states()[0].final_word_out] # needs sage.symbolic\n [Symbolic Ring]\n\n Finally, we use a somewhat questionable conversion::\n\n sage: T = transducers.Recursion([ # needs sage.rings.finite_rings sage.symbolic\n ....: f(2*n + 1) == f(n) + 1,\n ....: f(2*n) == f(n),\n ....: f(0) == 0],\n ....: 2, f, n, output_rings=[GF(5)])\n sage: for t in T.transitions(): # needs sage.rings.finite_rings sage.symbolic\n ....: print([x.parent() for x in t.word_out])\n []\n [Finite Field of size 5]\n\n .. TODO::\n\n Extend the method to\n\n - non-integral bases,\n\n - higher dimensions.\n\n ALGORITHM:\n\n See [HKP2015]_, Section 6. However, there are also recursion\n transitions for states of level `<\\kappa` if the recursion rules\n allow such a transition. Furthermore, the intermediate step of a\n non-deterministic transducer is left out by implicitly using\n recursion transitions. The well-posedness is checked in a\n truncated version of the recursion digraph.\n\n TESTS:\n\n The following tests fail due to missing or superfluous recursions\n or initial conditions. ::\n\n sage: var(\'n\') # needs sage.symbolic\n n\n sage: function(\'f\') # needs sage.symbolic\n f\n sage: transducers.Recursion([f(2*n) == f(n)], # needs sage.symbolic\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: Missing recursions for input congruent to\n [1] modulo 2.\n\n ::\n\n sage: transducers.Recursion([f(2*n + 1) == f(n), # needs sage.symbolic\n ....: f(4*n) == f(2*n) + 1,\n ....: f(2*n) == f(n) + 1],\n ....: 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: Conflicting rules congruent to 0 modulo 4.\n\n ::\n\n sage: transducers.Recursion([f(2*n + 1) == f(n) + 1, # needs sage.symbolic\n ....: f(2*n) == f(n),\n ....: f(0) == 0,\n ....: f(42) == 42], 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: Superfluous initial values for [42].\n\n ::\n\n sage: transducers.Recursion([f(2*n + 1) == f(n) + 1, # needs sage.symbolic\n ....: f(2*n) == f(n - 2) + 4,\n ....: f(0) == 0], 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: Missing initial values for [2].\n\n Here is an example of a transducer with a conflicting rule\n (it cannot hold for `n = 0`)::\n\n sage: T = transducers.Recursion([ # needs sage.symbolic\n ....: f(2*n + 1) == f(n - 1),\n ....: f(2*n) == f(n) + 1,\n ....: f(1) == 1,\n ....: f(0) == 0], 2, f, n)\n Traceback (most recent call last):\n ...\n ValueError: Conflicting recursion for [0].\n '
from sage.graphs.digraph import DiGraph
from sage.arith.srange import srange
if (is_zero is None):
is_zero = (lambda x: (not x))
RuleRight = namedtuple('Rule', ['k', 's', 't'])
initial_values = {}
rules = []
if ((input_alphabet is None) and (base in ZZ)):
input_alphabet = list(srange(base.abs()))
for equation in recursions:
if isinstance(equation, self.RecursionRule):
rules.append(equation)
elif (isinstance(equation, tuple) and (len(equation) == 2)):
initial_values[equation[0]] = equation[1]
else:
parsed = self._parse_recursion_equation_(equation, base, function, var, word_function, output_rings)
if isinstance(parsed, dict):
initial_values.update(parsed)
elif isinstance(parsed, self.RecursionRule):
rules.append(parsed)
else:
assert False
max_K = max((rule.K for rule in rules))
residues = [[None for r in range((base ** k))] for k in range((max_K + 1))]
for given_rule in rules:
(q, remainder) = given_rule.r.quo_rem((base ** given_rule.K))
rule = self.RecursionRule(K=given_rule.K, r=remainder, k=given_rule.k, s=(given_rule.s - ((base ** given_rule.k) * q)), t=given_rule.t)
for m in range(((max_K - rule.K) + 1)):
for ell in range((base ** m)):
R = (rule.r + ((base ** rule.K) * ell))
if (residues[(rule.K + m)][R] is not None):
raise ValueError(('Conflicting rules congruent to %d modulo %d.' % (R, (base ** (rule.K + m)))))
residues[(rule.K + m)][R] = RuleRight(k=(rule.k + m), s=(rule.s + (ell * (base ** rule.k))), t=rule.t)
missing_residues = [R for (R, rule) in enumerate(residues[max_K]) if (rule is None)]
if missing_residues:
raise ValueError(('Missing recursions for input congruent to %s modulo %s.' % (missing_residues, (base ** max_K))))
required_initial_values = set()
def recursion_transition(carry, level, force_nonnegative_target):
'\n Compute recursion transition leaving state ``(carry, level)``.\n\n INPUT:\n\n - ``carry`` -- integer.\n\n - ``level`` -- integer.\n\n - ``force_nonnegative_target`` -- boolean. If ``True``, only\n recursion transitions leading to a non-negative carry are\n returned.\n\n OUTPUT:\n\n A tuple ``((new_carry, new_level), output)`` if a recursion\n transition matching the specifications exists; otherwise,\n ``None``.\n '
if (level >= max_K):
K = max_K
else:
K = level
(m, r) = ZZ(carry).quo_rem((base ** K))
rule = residues[K][r]
if (rule is None):
return None
new_carry = (((base ** rule.k) * m) + rule.s)
new_level = ((rule.k + level) - K)
if ((new_carry + (base ** new_level)) < 0):
return None
if ((new_carry < 0) and force_nonnegative_target):
return None
if ((new_carry < 0) and (carry >= 0)):
required_initial_values.add(carry)
return ((new_carry, new_level), rule.t)
def recursion_transitions(carry, level, force_nonnegative_target):
'\n Compute the target and output of a maximal path of\n recursion transitions starting at state ``(carry, level)``.\n\n INPUT:\n\n - ``carry`` -- integer.\n\n - ``level`` -- integer.\n\n - ``force_nonnegative_target`` -- boolean. If ``True``, only\n recursion transitions leading to a non-negative carry are\n allowed.\n\n OUTPUT:\n\n A tuple ``((new_carry, new_level), output)``.\n '
(c, j) = (carry, level)
output = []
while True:
transition = recursion_transition(c, j, force_nonnegative_target)
if (transition is None):
break
(c, j) = transition[0]
output += transition[1]
return ((c, j), output)
def transition_function(states2, input):
(state_carry, state_level) = states2
((carry, level), output) = recursion_transitions(state_carry, state_level, False)
carry += (input * (base ** level))
level += 1
((carry, level), new_output) = recursion_transitions(carry, level, True)
return ((carry, level), (output + new_output))
T = Transducer(transition_function, initial_states=[(0, 0)], input_alphabet=input_alphabet)
def edge_recursion_digraph(n):
'\n Compute the list of outgoing edges of ``n`` in the recursion digraph.\n\n INPUT:\n\n - ``n`` -- integer.\n\n OUTPUT:\n\n A list ``[(A(n), label)]`` if `A(n)<\\infty`; otherwise an empty list.\n '
(m, r) = ZZ(n).quo_rem((base ** max_K))
rule = residues[max_K][r]
result = (((base ** rule.k) * m) + rule.s)
if (result >= 0):
return [(result, rule.t)]
else:
return []
def f(n):
'\n Compute f(n) as defined by the recursion\n '
if (n in initial_values):
return initial_values[n]
[(m, offset)] = edge_recursion_digraph(n)
return (offset + f(m))
carries = set((state.label()[0] for state in T.iter_states()))
recursion_digraph = DiGraph({carry: dict(edge_recursion_digraph(carry)) for carry in carries if (carry >= 0)}, multiedges=False)
initial_values_set = set(initial_values)
missing_initial_values = required_initial_values.difference(initial_values_set)
if missing_initial_values:
raise ValueError(('Missing initial values for %s.' % sorted(missing_initial_values)))
for cycle in recursion_digraph.all_simple_cycles():
assert (cycle[0] is cycle[(- 1)])
cycle_set = set(cycle)
intersection = cycle_set.intersection(initial_values_set)
if (not intersection):
raise ValueError(('Missing initial condition for one of %s.' % cycle[1:]))
if (len(intersection) > 1):
raise ValueError(('Too many initial conditions, only give one of %s.' % cycle[1:]))
required_initial_values.update(intersection)
output_sum = sum([e[2] for e in recursion_digraph.outgoing_edge_iterator(cycle[1:])], [])
if (not is_zero(output_sum)):
raise ValueError(('Conflicting recursion for %s.' % cycle[1:]))
superfluous_initial_values = initial_values_set.difference(required_initial_values)
if superfluous_initial_values:
raise ValueError(('Superfluous initial values for %s.' % sorted(superfluous_initial_values)))
for state in T.iter_states():
state.is_final = True
if (state.label()[0] >= 0):
state.final_word_out = f(state.label()[0])
else:
state.final_word_out = ZZ(0)
return T
|
class FQSymBasis_abstract(CombinatorialFreeModule, BindableClass):
'\n Abstract base class for bases of FQSym.\n\n This must define two attributes:\n\n - ``_prefix`` -- the basis prefix\n - ``_basis_name`` -- the name of the basis and must match one\n of the names that the basis can be constructed from FQSym\n '
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: TestSuite(algebras.FQSym(QQ).F()).run() # long time\n '
CombinatorialFreeModule.__init__(self, alg.base_ring(), Permutations(), category=FQSymBases(alg), bracket='', prefix=self._prefix)
def _coerce_map_from_(self, R):
"\n Return ``True`` if there is a coercion from ``R`` into ``self``\n and ``False`` otherwise.\n\n The things that coerce into ``self`` are\n\n - free quasi-symmetric functions over a base with\n a coercion map into ``self.base_ring()``\n - free symmetric functions over a base with\n a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: F = algebras.FQSym(GF(7)).F(); F\n Free Quasi-symmetric functions over Finite Field of size 7 in the F basis\n\n Elements of the free quasi-symmetric functions canonically coerce in::\n\n sage: x, y, z = F([1]), F([2,1]), F([1,3,2])\n sage: F.coerce(x+y) == x+y\n True\n\n The free quasi-symmetric functions over `\\ZZ` coerces in,\n since `\\ZZ` coerces to `\\GF{7}`::\n\n sage: G = algebras.FQSym(ZZ).F()\n sage: Gx, Gy = G([1]), G([2,1])\n sage: z = F.coerce(Gx+Gy); z\n F[1] + F[2, 1]\n sage: z.parent() is F\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so free\n quasi-symmetric functions over `\\GF{7}` does not coerce\n to the same algebra over `\\ZZ`::\n\n sage: G.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Free Quasi-symmetric functions\n over Finite Field of size 7 in the F basis to\n Free Quasi-symmetric functions over Integer Ring in the F basis\n\n Check that `FSym` bases coerce in::\n\n sage: FSym = algebras.FSym(ZZ)\n sage: TG = FSym.G()\n sage: t = StandardTableau([[1,3],[2,4],[5]])\n sage: F(TG[t])\n F[2, 1, 5, 4, 3] + F[2, 5, 1, 4, 3] + F[2, 5, 4, 1, 3]\n + F[5, 2, 1, 4, 3] + F[5, 2, 4, 1, 3]\n sage: algebras.FQSym(QQ)(TG[t])\n F[2, 1, 5, 4, 3] + F[2, 5, 1, 4, 3] + F[2, 5, 4, 1, 3]\n + F[5, 2, 1, 4, 3] + F[5, 2, 4, 1, 3]\n sage: G7 = algebras.FQSym(GF(7)).G()\n sage: G7(TG[[1,2],[3,4]])\n G[2, 4, 1, 3] + G[3, 4, 1, 2]\n\n TESTS::\n\n sage: F = algebras.FQSym(ZZ).F()\n sage: G = algebras.FQSym(QQ).F()\n sage: F.has_coerce_map_from(G)\n False\n sage: G.has_coerce_map_from(F)\n True\n sage: F.has_coerce_map_from(QQ)\n False\n sage: G.has_coerce_map_from(QQ)\n True\n sage: F.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n "
if isinstance(R, FQSymBasis_abstract):
if (R.realization_of() == self.realization_of()):
return True
if (not self.base_ring().has_coerce_map_from(R.base_ring())):
return False
if (self._basis_name == R._basis_name):
def coerce_base_ring(self, x):
return self._from_dict(x.monomial_coefficients())
return coerce_base_ring
target = getattr(self.realization_of(), R._basis_name)()
return self._coerce_map_via([target], R)
from sage.combinat.chas.fsym import FreeSymmetricFunctions
if isinstance(R, FreeSymmetricFunctions.Fundamental):
if (not self.base_ring().has_coerce_map_from(R.base_ring())):
return False
G = self.realization_of().G()
P = G._indices
def G_to_G_on_basis(t):
return G.sum_of_monomials((P(sigma) for sigma in Permutations(t.size()) if (sigma.right_tableau() == t)))
phi = R.module_morphism(G_to_G_on_basis, codomain=G)
if (self is G):
return phi
else:
return (self.coerce_map_from(G) * phi)
return super()._coerce_map_from_(R)
@cached_method
def an_element(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ)\n sage: F = A.F()\n sage: F.an_element()\n F[1] + 2*F[1, 2] + 2*F[2, 1]\n sage: G = A.G()\n sage: G.an_element()\n G[1] + 2*G[1, 2] + 2*G[2, 1]\n sage: M = A.M()\n sage: M.an_element()\n M[1] + 2*M[1, 2] + 4*M[2, 1]\n '
o = self.monomial(Permutation([1]))
return (o + ((2 * o) * o))
|
class FreeQuasisymmetricFunctions(UniqueRepresentation, Parent):
'\n The free quasi-symmetric functions.\n\n The Hopf algebra `FQSym` of free quasi-symmetric functions\n over a commutative ring `R` is the free `R`-module with basis\n indexed by all permutations (i.e., the indexing set is\n the disjoint union of all symmetric groups).\n Its product is determined by the shifted shuffles of two\n permutations, whereas its coproduct is given by splitting\n a permutation (regarded as a word) into two (at every\n possible point) and standardizing the two pieces.\n This Hopf algebra was introduced in [MR]_.\n See [GriRei18]_ (Chapter 8) for a treatment using modern\n notations.\n\n In more detail:\n For each `n \\geq 0`, consider the symmetric group `S_n`.\n Let `S` be the disjoint union of the `S_n` over all\n `n \\geq 0`.\n Then, `FQSym` is the free `R`-module with basis\n `(F_w)_{w \\in S}`.\n This `R`-module is graded, with the `n`-th graded\n component being spanned by all `F_w` for `w \\in S_n`.\n A multiplication is defined on `FQSym` as follows:\n For any two permutations `u \\in S_k` and `v \\in S_l`,\n we set\n\n .. MATH::\n\n F_u F_v = \\sum F_w ,\n\n where the sum is over all shuffles of `u` with `v[k]`.\n Here, the permutations `u` and `v` are regarded as words\n (by writing them in one-line notation), and `v[k]` means\n the word obtained from `v` by increasing each letter by\n `k` (for example, `(1,4,2,3)[5] = (6,9,7,8)`); and the\n shuffles `w` are translated back into permutations.\n This defines an associative multiplication on `FQSym`;\n its unity is `F_e`, where `e` is the identity\n permutation in `S_0`.\n\n In Section 1.3 of [AguSot05]_, Aguiar and Sottile construct a\n different basis of `FQSym`. Their basis, called the\n *monomial basis* and denoted by `(\\mathcal{M}_u)`,\n is also indexed by permutations. It is connected to the\n above F-basis by the relation\n\n .. MATH::\n\n F_u = \\sum_v \\mathcal{M}_v ,\n\n where the sum ranges over all permutations `v` such that each\n inversion of `u` is an inversion of `v`. (An *inversion* of a\n permutation `w` means a pair `(i, j)` of positions satisfying\n `i < j` and `w(i) > w(j)`.) The above relation yields a\n unitriangular change-of-basis matrix, and thus can be used to\n compute the `\\mathcal{M}_u` by Mobius inversion.\n\n Another classical basis of `FQSym` is `(G_w)_{w \\in S}`,\n where `G_w = F_{w^{-1}}`.\n This is just a relabeling of the basis `(F_w)_{w \\in S}`,\n but is a more natural choice from some viewpoints.\n\n The algebra `FQSym` is often identified with ("realized as") a\n subring of the ring of all bounded-degree noncommutative power\n series in countably many indeterminates (i.e., elements in\n `R \\langle \\langle x_1, x_2, x_3, \\ldots \\rangle \\rangle` of bounded\n degree). Namely, consider words over the alphabet `\\{1, 2, 3, \\ldots\\}`;\n every noncommutative power series is an infinite `R`-linear\n combination of these words.\n Consider the `R`-linear map that sends each `G_u` to the sum of\n all words whose standardization (also known as "standard\n permutation"; see\n :meth:`~sage.combinat.words.finite_word.FiniteWord_class.standard_permutation`)\n is `u`. This map is an injective `R`-algebra homomorphism, and\n thus embeds `FQSym` into the latter ring.\n\n As an associative algebra, `FQSym` has the richer structure\n of a dendriform algebra. This means that the associative\n product ``*`` is decomposed as a sum of two binary operations\n\n .. MATH::\n\n x y = x \\succ y + x \\prec y\n\n that satisfy the axioms:\n\n .. MATH::\n\n (x \\succ y) \\prec z = x \\succ (y \\prec z),\n\n .. MATH::\n\n (x \\prec y) \\prec z = x \\prec (y z),\n\n .. MATH::\n\n (x y) \\succ z = x \\succ (y \\succ z).\n\n These two binary operations are defined similarly to the\n (associative) product above: We set\n\n .. MATH::\n\n F_u \\prec F_v = \\sum F_w ,\n\n where the sum is now over all shuffles of `u` with `v[k]`\n whose first letter is taken from `u` (rather than from\n `v[k]`). Similarly,\n\n .. MATH::\n\n F_u \\succ F_v = \\sum F_w ,\n\n where the sum is over all remaining shuffles of `u` with\n `v[k]`.\n\n .. TODO::\n\n Decide what `1 \\prec 1` and `1 \\succ 1` are.\n\n .. NOTE::\n\n The usual binary operator ``*`` is used for the\n associative product.\n\n EXAMPLES::\n\n sage: F = algebras.FQSym(ZZ).F()\n sage: x,y,z = F([1]), F([1,2]), F([1,3,2])\n sage: (x * y) * z\n F[1, 2, 3, 4, 6, 5] + ...\n\n The product of `FQSym` is associative::\n\n sage: x * (y * z) == (x * y) * z\n True\n\n The associative product decomposes into two parts::\n\n sage: x * y == F.prec(x, y) + F.succ(x, y)\n True\n\n The axioms of a dendriform algebra hold::\n\n sage: F.prec(F.succ(x, y), z) == F.succ(x, F.prec(y, z))\n True\n sage: F.prec(F.prec(x, y), z) == F.prec(x, y * z)\n True\n sage: F.succ(x * y, z) == F.succ(x, F.succ(y, z))\n True\n\n `FQSym` is also known as the Malvenuto-Reutenauer algebra::\n\n sage: algebras.MalvenutoReutenauer(ZZ)\n Free Quasi-symmetric functions over Integer Ring\n\n REFERENCES:\n\n - [MR]_\n - [LR1998]_\n - [GriRei18]_\n '
def __init__(self, R):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: A = algebras.FQSym(QQ); A\n Free Quasi-symmetric functions over Rational Field\n sage: TestSuite(A).run() # long time (3s)\n\n sage: F = algebras.FQSym(QQ)\n sage: TestSuite(F).run() # long time (3s)\n '
category = HopfAlgebras(R).Graded().Connected()
Parent.__init__(self, base=R, category=category.WithRealizations())
F = self.F()
G = self.G()
F.module_morphism(G._F_to_G_on_basis, codomain=G, category=category).register_as_coercion()
G.module_morphism(G._G_to_F_on_basis, codomain=F, category=category).register_as_coercion()
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.FQSym(QQ) # indirect doctest\n Free Quasi-symmetric functions over Rational Field\n '
s = 'Free Quasi-symmetric functions over {}'
return s.format(self.base_ring())
def a_realization(self):
'\n Return a particular realization of ``self`` (the F-basis).\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: FQSym.a_realization()\n Free Quasi-symmetric functions over Rational Field in the F basis\n '
return self.F()
_shorthands = tuple(['F', 'G', 'M'])
class F(FQSymBasis_abstract):
'\n The F-basis of `FQSym`.\n\n This is the basis `(F_w)`, with `w` ranging over all\n permutations. See the documentation of\n :class:`FreeQuasisymmetricFunctions` for details.\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: FQSym.F()\n Free Quasi-symmetric functions over Rational Field in the F basis\n '
_prefix = 'F'
_basis_name = 'F'
def _element_constructor_(self, x):
'\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.FQSym(QQ).F()\n sage: x, y, z = R([1]), R([2,1]), R([3,2,1])\n sage: R(x)\n F[1]\n sage: R(x+4*y)\n F[1] + 4*F[2, 1]\n sage: R(1)\n F[]\n\n sage: D = algebras.FQSym(ZZ).F()\n sage: X, Y, Z = D([1]), D([2,1]), D([3,2,1])\n sage: R(X-Y).parent()\n Free Quasi-symmetric functions over Rational Field in the F basis\n\n sage: R([1, 3, 2])\n F[1, 3, 2]\n sage: R(Permutation([1, 3, 2]))\n F[1, 3, 2]\n sage: R(SymmetricGroup(4)(Permutation([1,3,4,2])))\n F[1, 3, 4, 2]\n '
if isinstance(x, (list, tuple, PermutationGroupElement)):
x = Permutation(x)
try:
P = x.parent()
if isinstance(P, FreeQuasisymmetricFunctions.F):
if (P is self):
return x
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
pass
return CombinatorialFreeModule._element_constructor_(self, x)
def __getitem__(self, r):
'\n The default implementation of ``__getitem__`` interprets\n the input as a tuple, which in case of permutations\n is interpreted as cycle notation, even though the input\n looks like a one-line notation.\n We override this method to amend this.\n\n EXAMPLES::\n\n sage: F = algebras.FQSym(QQ).F()\n sage: F[3, 2, 1]\n F[3, 2, 1]\n sage: F[1]\n F[1]\n '
if isinstance(r, tuple):
r = list(r)
elif (r == 1):
r = [1]
return super().__getitem__(r)
def degree_on_basis(self, t):
'\n Return the degree of a permutation in\n the algebra of free quasi-symmetric functions.\n\n This is the size of the permutation (i.e., the `n`\n for which the permutation belongs to `S_n`).\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: u = Permutation([2,1])\n sage: A.degree_on_basis(u)\n 2\n '
return len(t)
def product_on_basis(self, x, y):
'\n Return the `*` associative product of two permutations.\n\n This is the shifted shuffle of `x` and `y`.\n\n .. SEEALSO::\n\n :meth:`succ_product_on_basis`, :meth:`prec_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = Permutation([1])\n sage: A.product_on_basis(x, x)\n F[1, 2] + F[2, 1]\n '
return self.sum_of_monomials((u for u in x.shifted_shuffle(y)))
def succ_product_on_basis(self, x, y):
'\n Return the `\\succ` product of two permutations.\n\n This is the shifted shuffle of `x` and `y` with the additional\n condition that the first letter of the result comes from `y`.\n\n The usual symbol for this operation is `\\succ`.\n\n .. SEEALSO::\n\n - :meth:`product_on_basis`, :meth:`prec_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = Permutation([1,2])\n sage: A.succ_product_on_basis(x, x)\n F[3, 1, 2, 4] + F[3, 1, 4, 2] + F[3, 4, 1, 2]\n sage: y = Permutation([])\n sage: A.succ_product_on_basis(x, y) == 0\n True\n sage: A.succ_product_on_basis(y, x) == A(x)\n True\n\n TESTS::\n\n sage: u = A.one().support()[0] # this is F[]\n sage: A.succ_product_on_basis(x, u)\n 0\n sage: A.succ_product_on_basis(u, x)\n F[1, 2]\n sage: A.succ_product_on_basis(u, u)\n Traceback (most recent call last):\n ...\n ValueError: products | < | and | > | are not defined\n '
if (not y):
if (not x):
raise ValueError('products | < | and | > | are not defined')
else:
return self.zero()
basis = self.basis()
if (not x):
return basis[y]
K = basis.keys()
n = len(x)
shy = Word([(a + n) for a in y])
shy0 = shy[0]
return self.sum_of_monomials((K(([shy0] + list(u))) for u in Word(x).shuffle(Word(shy[1:]))))
def prec_product_on_basis(self, x, y):
'\n Return the `\\prec` product of two permutations.\n\n This is the shifted shuffle of `x` and `y` with the additional\n condition that the first letter of the result comes from `x`.\n\n The usual symbol for this operation is `\\prec`.\n\n .. SEEALSO::\n\n :meth:`product_on_basis`, :meth:`succ_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = Permutation([1,2])\n sage: A.prec_product_on_basis(x, x)\n F[1, 2, 3, 4] + F[1, 3, 2, 4] + F[1, 3, 4, 2]\n sage: y = Permutation([])\n sage: A.prec_product_on_basis(x, y) == A(x)\n True\n sage: A.prec_product_on_basis(y, x) == 0\n True\n\n TESTS::\n\n sage: u = A.one().support()[0] # this is F[]\n sage: A.prec_product_on_basis(x, u)\n F[1, 2]\n sage: A.prec_product_on_basis(u, x)\n 0\n sage: A.prec_product_on_basis(u, u)\n Traceback (most recent call last):\n ...\n ValueError: products | < | and | > | are not defined\n '
if ((not x) and (not y)):
raise ValueError('products | < | and | > | are not defined')
if (not x):
return self.zero()
basis = self.basis()
if (not y):
return basis[x]
K = basis.keys()
n = len(x)
shy = Word([(a + n) for a in y])
x0 = x[0]
return self.sum_of_monomials((K(([x0] + list(u))) for u in Word(x[1:]).shuffle(shy)))
def coproduct_on_basis(self, x):
'\n Return the coproduct of `F_{\\sigma}` for `\\sigma` a permutation\n (here, `\\sigma` is ``x``).\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = A([1])\n sage: ascii_art(A.coproduct(A.one())) # indirect doctest\n 1 # 1\n\n sage: ascii_art(A.coproduct(x)) # indirect doctest\n 1 # F + F # 1\n [1] [1]\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x, y, z = A([1]), A([2,1]), A([3,2,1])\n sage: A.coproduct(z)\n F[] # F[3, 2, 1] + F[1] # F[2, 1] + F[2, 1] # F[1]\n + F[3, 2, 1] # F[]\n '
if (not x):
return self.one().tensor(self.one())
return sum((self(Word(x[:i]).standard_permutation()).tensor(self(Word(x[i:]).standard_permutation())) for i in range((len(x) + 1))))
class Element(FQSymBasis_abstract.Element):
def to_symmetric_group_algebra(self, n=None):
'\n Return the element of a symmetric group algebra\n corresponding to the element ``self`` of `FQSym`.\n\n INPUT:\n\n - ``n`` -- integer (default: the maximal degree of ``self``);\n the rank of the target symmetric group algebra\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = A([1,3,2,4]) + 5/2 * A([1,2,4,3])\n sage: x.to_symmetric_group_algebra()\n 5/2*[1, 2, 4, 3] + [1, 3, 2, 4]\n sage: x.to_symmetric_group_algebra(n=7)\n 5/2*[1, 2, 4, 3, 5, 6, 7] + [1, 3, 2, 4, 5, 6, 7]\n sage: a = A.zero().to_symmetric_group_algebra(); a\n 0\n sage: parent(a)\n Symmetric group algebra of order 0 over Rational Field\n\n sage: y = A([1,3,2,4]) + 5/2 * A([2,1])\n sage: y.to_symmetric_group_algebra()\n [1, 3, 2, 4] + 5/2*[2, 1, 3, 4]\n sage: y.to_symmetric_group_algebra(6)\n [1, 3, 2, 4, 5, 6] + 5/2*[2, 1, 3, 4, 5, 6]\n '
if (not self):
if (n is None):
n = 0
return SymmetricGroupAlgebra(self.base_ring(), n).zero()
m = self.maximal_degree()
if (n is None):
n = m
elif (n < m):
raise ValueError('n must be at least the maximal degree')
SGA = SymmetricGroupAlgebra(self.base_ring(), n)
return SGA._from_dict({Permutations(n)(key): c for (key, c) in self})
class G(FQSymBasis_abstract):
'\n The G-basis of `FQSym`.\n\n This is the basis `(G_w)`, with `w` ranging over all\n permutations. See the documentation of\n :class:`FreeQuasisymmetricFunctions` for details.\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: G = FQSym.G(); G\n Free Quasi-symmetric functions over Rational Field in the G basis\n\n sage: G([3, 1, 2]).coproduct()\n G[] # G[3, 1, 2] + G[1] # G[2, 1] + G[1, 2] # G[1]\n + G[3, 1, 2] # G[]\n\n sage: G([3, 1, 2]) * G([2, 1])\n G[3, 1, 2, 5, 4] + G[4, 1, 2, 5, 3] + G[4, 1, 3, 5, 2]\n + G[4, 2, 3, 5, 1] + G[5, 1, 2, 4, 3] + G[5, 1, 3, 4, 2]\n + G[5, 1, 4, 3, 2] + G[5, 2, 3, 4, 1] + G[5, 2, 4, 3, 1]\n + G[5, 3, 4, 2, 1]\n '
_prefix = 'G'
_basis_name = 'G'
def _element_constructor_(self, x):
'\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.FQSym(QQ).G()\n sage: x, y, z = R([1]), R([2,1]), R([3,2,1])\n sage: R(x)\n G[1]\n sage: R(x+4*y)\n G[1] + 4*G[2, 1]\n sage: R(1)\n G[]\n\n sage: D = algebras.FQSym(ZZ).G()\n sage: X, Y, Z = D([1]), D([2,1]), D([3,2,1])\n sage: R(X-Y).parent()\n Free Quasi-symmetric functions over Rational Field in the G basis\n\n sage: R([1, 3, 2])\n G[1, 3, 2]\n sage: R(Permutation([1, 3, 2]))\n G[1, 3, 2]\n sage: R(SymmetricGroup(4)(Permutation([1,3,4,2])))\n G[1, 3, 4, 2]\n\n sage: RF = algebras.FQSym(QQ).F()\n sage: R(RF([2, 3, 4, 1]))\n G[4, 1, 2, 3]\n sage: R(RF([3, 2, 4, 1]))\n G[4, 2, 1, 3]\n sage: DF = algebras.FQSym(ZZ).F()\n sage: D(DF([2, 3, 4, 1]))\n G[4, 1, 2, 3]\n sage: R(DF([2, 3, 4, 1]))\n G[4, 1, 2, 3]\n sage: RF(R[2, 3, 4, 1])\n F[4, 1, 2, 3]\n '
if isinstance(x, (list, tuple, PermutationGroupElement)):
x = Permutation(x)
try:
P = x.parent()
if isinstance(P, FreeQuasisymmetricFunctions.G):
if (P is self):
return x
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
pass
return CombinatorialFreeModule._element_constructor_(self, x)
def __getitem__(self, r):
'\n The default implementation of ``__getitem__`` interprets\n the input as a tuple, which in case of permutations\n is interpreted as cycle notation, even though the input\n looks like a one-line notation.\n We override this method to amend this.\n\n EXAMPLES::\n\n sage: G = algebras.FQSym(QQ).G()\n sage: G[3, 2, 1]\n G[3, 2, 1]\n sage: G[1]\n G[1]\n '
if isinstance(r, tuple):
r = list(r)
elif (r == 1):
r = [1]
return super().__getitem__(r)
def _G_to_F_on_basis(self, w):
'\n Return `G_w` in terms of the F basis.\n\n INPUT:\n\n - ``w`` -- a permutation\n\n OUTPUT:\n\n - An element of the F basis\n\n TESTS::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: G = FQSym.G()\n sage: F(G[3, 2, 1] - 4 * G[4, 2, 1, 3])\n F[3, 2, 1] - 4*F[3, 2, 4, 1]\n sage: all(F(G._G_to_F_on_basis(w)) == G[w] for i in range(5)\n ....: for w in Permutations(i))\n True\n sage: G[3, 2, 1] == F[3, 2, 1]\n True\n sage: G[4, 2, 1, 3] == F[3, 2, 4, 1]\n True\n sage: G[4, 2, 1, 3] == F[4, 2, 1, 3]\n False\n '
F = self.realization_of().F()
return F.basis()[w.inverse()]
def _F_to_G_on_basis(self, w):
'\n Return `F_w` in terms of the G basis.\n\n INPUT:\n\n - ``w`` -- a permutation\n\n OUTPUT:\n\n - An element of the G basis\n\n TESTS::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: G = FQSym.G()\n sage: G(F[3, 2, 1] - 4 * F[4, 2, 1, 3])\n G[3, 2, 1] - 4*G[3, 2, 4, 1]\n sage: all(G(G._F_to_G_on_basis(w)) == F[w] for i in range(5)\n ....: for w in Permutations(i))\n True\n sage: F[3, 2, 1] == G[3, 2, 1]\n True\n sage: F[4, 2, 1, 3] == G[3, 2, 4, 1]\n True\n sage: F[4, 2, 1, 3] == G[4, 2, 1, 3]\n False\n '
return self.basis()[w.inverse()]
def degree_on_basis(self, t):
'\n Return the degree of a permutation in\n the algebra of free quasi-symmetric functions.\n\n This is the size of the permutation (i.e., the `n`\n for which the permutation belongs to `S_n`).\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).G()\n sage: u = Permutation([2,1])\n sage: A.degree_on_basis(u)\n 2\n '
return len(t)
class M(FQSymBasis_abstract):
'\n The M-basis of `FQSym`.\n\n This is the Monomial basis `(\\mathcal{M}_w)`, with `w` ranging\n over all permutations. See the documentation of :class:`FQSym`\n for details.\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: M = FQSym.M(); M\n Free Quasi-symmetric functions over Rational Field in the Monomial basis\n\n sage: M([3, 1, 2]).coproduct()\n M[] # M[3, 1, 2] + M[1] # M[1, 2] + M[3, 1, 2] # M[]\n sage: M([3, 2, 1]).coproduct()\n M[] # M[3, 2, 1] + M[1] # M[2, 1] + M[2, 1] # M[1]\n + M[3, 2, 1] # M[]\n\n sage: M([1, 2]) * M([1])\n M[1, 2, 3] + 2*M[1, 3, 2] + M[2, 3, 1] + M[3, 1, 2]\n '
_prefix = 'M'
_basis_name = 'Monomial'
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: M = algebras.FQSym(QQ).M()\n sage: TestSuite(M).run(elements=M.some_elements()[:-1]) # long time\n '
FQSymBasis_abstract.__init__(self, alg)
F = self.realization_of().F()
phi = F.module_morphism(self._F_to_M_on_basis, codomain=self, unitriangular='lower')
phi.register_as_coercion()
phi_i = self.module_morphism(self._M_to_F_on_basis, codomain=F, unitriangular='lower')
phi_i.register_as_coercion()
def _element_constructor_(self, x):
'\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.FQSym(QQ).M()\n sage: x, y, z = R([1]), R([2,1]), R([3,2,1])\n sage: R(x)\n M[1]\n sage: R(x+4*y)\n M[1] + 4*M[2, 1]\n sage: R(1)\n M[]\n\n sage: D = algebras.FQSym(ZZ).M()\n sage: X, Y, Z = D([1]), D([2,1]), D([3,2,1])\n sage: R(X-Y).parent()\n Free Quasi-symmetric functions over Rational Field in the Monomial basis\n\n sage: R([1, 3, 2])\n M[1, 3, 2]\n sage: R(Permutation([1, 3, 2]))\n M[1, 3, 2]\n sage: R(SymmetricGroup(4)(Permutation([1,3,4,2])))\n M[1, 3, 4, 2]\n\n sage: RF = algebras.FQSym(QQ).F()\n sage: R(RF([2, 3, 4, 1]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: R(RF([3, 2, 4, 1]))\n M[3, 2, 4, 1] + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: DF = algebras.FQSym(ZZ).F()\n sage: D(DF([2, 3, 4, 1]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: R(DF([2, 3, 4, 1]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: RF(R[2, 3, 4, 1])\n F[2, 3, 4, 1] - F[2, 4, 3, 1] - F[3, 2, 4, 1] + F[4, 3, 2, 1]\n\n sage: RG = algebras.FQSym(QQ).G()\n sage: R(RG([4, 1, 2, 3]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: R(RG([4, 2, 1, 3]))\n M[3, 2, 4, 1] + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: DG = algebras.FQSym(ZZ).G()\n sage: D(DG([4, 1, 2, 3]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: R(DG([4, 1, 2, 3]))\n M[2, 3, 4, 1] + M[2, 4, 3, 1] + M[3, 2, 4, 1] + M[3, 4, 2, 1]\n + M[4, 2, 3, 1] + M[4, 3, 2, 1]\n sage: RG(R[2, 3, 4, 1])\n G[4, 1, 2, 3] - G[4, 1, 3, 2] - G[4, 2, 1, 3] + G[4, 3, 2, 1]\n '
if isinstance(x, (list, tuple, PermutationGroupElement)):
x = Permutation(x)
try:
P = x.parent()
if isinstance(P, FreeQuasisymmetricFunctions.M):
if (P is self):
return x
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
pass
return CombinatorialFreeModule._element_constructor_(self, x)
def __getitem__(self, r):
'\n The default implementation of ``__getitem__`` interprets\n the input as a tuple, which in case of permutations\n is interpreted as cycle notation, even though the input\n looks like a one-line notation.\n We override this method to amend this.\n\n EXAMPLES::\n\n sage: M = algebras.FQSym(QQ).M()\n sage: M[3, 2, 1]\n M[3, 2, 1]\n sage: M[1]\n M[1]\n '
if isinstance(r, tuple):
r = list(r)
elif (r == 1):
r = [1]
return super().__getitem__(r)
def _F_to_M_on_basis(self, w):
'\n Return `F_w` in terms of the M basis.\n\n INPUT:\n\n - ``w`` -- a permutation\n\n OUTPUT:\n\n - An element of the M basis\n\n TESTS::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: M = FQSym.M()\n sage: M(F[3, 2, 1] - 4 * F[4, 2, 1, 3])\n M[3, 2, 1] - 4*M[4, 2, 1, 3] - 4*M[4, 3, 1, 2] - 4*M[4, 3, 2, 1]\n sage: all(M(M._F_to_M_on_basis(w)) == F[w] for i in range(5)\n ....: for w in Permutations(i))\n True\n sage: F[3, 2, 1] == M[3, 2, 1]\n True\n sage: F[4, 2, 1, 3] == M[3, 2, 4, 1]\n False\n '
return self.sum_of_monomials(w.permutohedron_greater(side='left'))
def _M_to_F_on_basis(self, w):
'\n Return `\\mathcal{M}_w` in terms of the F basis.\n\n INPUT:\n\n - ``w`` -- a permutation\n\n OUTPUT:\n\n - An element of the F basis\n\n ALGORITHM:\n\n If `w` is any permutation in `S_n`, then\n\n .. MATH::\n\n \\mathcal{M}_w = \\sum_u (-1)^{j(w, u)} F_u,\n\n where the sum ranges over all permutations `u \\in S_n`\n obtained as follows:\n\n * Let `v = w^{-1}`.\n\n * Subdivide the list `(v(1), v(2), \\ldots, v(n))` into\n an arbitrary number of nonempty blocks (by putting\n dividers between adjacent entries) in such a way that\n each block is strictly increasing (i.e., each descent\n of `v` is followed by a divider, but not every\n divider must necessarily follow a descent).\n\n * Reverse the order of entries in each block.\n\n * Remove the dividers. The resulting list is the\n one-line notation `(x(1), x(2), \\ldots, x(n))` of\n some permutation `x \\in S_n`.\n\n * Set `u = x^{-1}`. Also, let `j(w, u)` be `n` minus\n the number of blocks in our subdivision.\n\n This formula is equivalent to the formula (1.13) in\n [AguSot05]_, since Corollary 3.2.8 in [BB2005]_ expresses\n the Mobius function of the weak order.\n\n TESTS::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: M = FQSym.M()\n sage: F(M[3, 2, 1] - 4 * F[4, 2, 1, 3])\n F[3, 2, 1] - 4*F[4, 2, 1, 3]\n sage: all(F(M._M_to_F_on_basis(w)) == M[w] for i in range(5) # indirect doctest\n ....: for w in Permutations(i))\n True\n sage: all(M(F(M[w])) == M[w] for i in range(5)\n ....: for w in Permutations(i))\n True\n sage: M[3, 2, 1] == F[3, 2, 1]\n True\n sage: M[3, 2, 4, 1] == F[4, 2, 1, 3]\n False\n sage: F(M[[]]) == F[[]]\n True\n '
F = self.realization_of().F()
if (len(w) <= 1):
return F.monomial(w)
w_i = w.inverse()
w_i = w_i[:]
n = len(w_i)
des = tuple((([0] + [g for g in range(1, n) if (w_i[(g - 1)] > w_i[g])]) + [n]))
non_des = [g for g in range(1, n) if (w_i[(g - 1)] < w_i[g])]
Perms = self.basis().keys()
R = self.base_ring()
one = R.one()
mine = (- one)
dc = {w: one}
from itertools import combinations
for k in range(len(non_des)):
kk = (k + len(des))
for extra_des in combinations(non_des, k):
breakpoints = sorted((des + extra_des))
p = sum([w_i[breakpoints[g]:breakpoints[(g + 1)]][::(- 1)] for g in range((kk - 1))], [])
u = Perms(p).inverse()
dc[u] = (one if ((n % 2) != (kk % 2)) else mine)
return F._from_dict(dc)
def degree_on_basis(self, t):
'\n Return the degree of a permutation in\n the algebra of free quasi-symmetric functions.\n\n This is the size of the permutation (i.e., the `n`\n for which the permutation belongs to `S_n`).\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).M()\n sage: u = Permutation([2,1])\n sage: A.degree_on_basis(u)\n 2\n '
return len(t)
def coproduct_on_basis(self, x):
'\n Return the coproduct of `\\mathcal{M}_{\\sigma}` for `\\sigma`\n a permutation (here, `\\sigma` is ``x``).\n\n This uses Theorem 3.1 in [AguSot05]_.\n\n EXAMPLES::\n\n sage: M = algebras.FQSym(QQ).M()\n sage: x = M([1])\n sage: ascii_art(M.coproduct(M.one())) # indirect doctest\n 1 # 1\n\n sage: ascii_art(M.coproduct(x)) # indirect doctest\n 1 # M + M # 1\n [1] [1]\n\n sage: M.coproduct(M([2, 1, 3]))\n M[] # M[2, 1, 3] + M[2, 1, 3] # M[]\n sage: M.coproduct(M([2, 3, 1]))\n M[] # M[2, 3, 1] + M[1, 2] # M[1] + M[2, 3, 1] # M[]\n sage: M.coproduct(M([3, 2, 1]))\n M[] # M[3, 2, 1] + M[1] # M[2, 1] + M[2, 1] # M[1]\n + M[3, 2, 1] # M[]\n sage: M.coproduct(M([3, 4, 2, 1]))\n M[] # M[3, 4, 2, 1] + M[1, 2] # M[2, 1] + M[2, 3, 1] # M[1]\n + M[3, 4, 2, 1] # M[]\n sage: M.coproduct(M([3, 4, 1, 2]))\n M[] # M[3, 4, 1, 2] + M[1, 2] # M[1, 2] + M[3, 4, 1, 2] # M[]\n '
n = len(x)
if (not n):
return self.one().tensor(self.one())
return sum((self(Word(x[:i]).standard_permutation()).tensor(self(Word(x[i:]).standard_permutation())) for i in range((n + 1)) if ((i == 0) or (i == n) or (min(x[:i]) > max(x[i:])))))
class Element(FQSymBasis_abstract.Element):
def star_involution(self):
'\n Return the image of the element ``self`` of `FQSym`\n under the star involution.\n\n See\n :meth:`FQSymBases.ElementMethods.star_involution`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`omega_involution`, :meth:`psi_involution`\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: M = FQSym.M()\n sage: M[[2,3,1]].star_involution()\n M[3, 1, 2]\n sage: M[[]].star_involution()\n M[]\n\n TESTS::\n\n sage: F = FQSym.F()\n sage: all(M(F[w]).star_involution() == M(F[w].star_involution())\n ....: for w in Permutations(4))\n True\n '
M = self.parent()
return M._from_dict({w.complement().reverse(): c for (w, c) in self}, remove_zeros=False)
|
class FQSymBases(Category_realization_of_parent):
'\n The category of graded bases of `FQSym` indexed by permutations.\n '
def __init__(self, base):
'\n Initialize the bases of an `FQSym`\n\n INPUT:\n\n - ``base`` -- an instance of `FQSym`\n\n TESTS::\n\n sage: from sage.combinat.fqsym import FQSymBases\n sage: FQSym = algebras.FQSym(ZZ)\n sage: bases = FQSymBases(FQSym)\n sage: FQSym.F() in bases\n True\n '
Category_realization_of_parent.__init__(self, base)
def _repr_(self):
'\n Return the representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.fqsym import FQSymBases\n sage: FQSym = algebras.FQSym(ZZ)\n sage: FQSymBases(FQSym)\n Category of bases of Free Quasi-symmetric functions over Integer Ring\n '
return 'Category of bases of {}'.format(self.base())
def super_categories(self):
'\n The super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.fqsym import FQSymBases\n sage: FQSym = algebras.FQSym(ZZ)\n sage: bases = FQSymBases(FQSym)\n sage: bases.super_categories()\n [Category of realizations of Free Quasi-symmetric functions over Integer Ring,\n Join of Category of realizations of Hopf algebras over Integer Ring\n and Category of graded algebras over Integer Ring\n and Category of graded coalgebras over Integer Ring,\n Category of graded connected Hopf algebras with basis over Integer Ring]\n '
R = self.base().base_ring()
return [self.base().Realizations(), HopfAlgebras(R).Graded().Realizations(), HopfAlgebras(R).Graded().WithBasis().Graded().Connected()]
class ParentMethods():
def _repr_(self):
'\n Text representation of this basis of `FQSym`.\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: FQSym.F()\n Free Quasi-symmetric functions over Integer Ring in the F basis\n '
return '{} in the {} basis'.format(self.realization_of(), self._basis_name)
def __getitem__(self, p):
'\n Return the basis element indexed by ``p``.\n\n INPUT:\n\n - ``p`` -- a permutation\n\n EXAMPLES::\n\n sage: R = algebras.FQSym(QQ).F()\n sage: R[[1, 3, 2]]\n F[1, 3, 2]\n sage: R[Permutation([1, 3, 2])]\n F[1, 3, 2]\n sage: R[SymmetricGroup(4)(Permutation([1,3,4,2]))]\n F[1, 3, 4, 2]\n '
return self.monomial(Permutation(p))
def basis(self, degree=None):
'\n The basis elements (optionally: of the specified degree).\n\n OUTPUT: Family\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: G = FQSym.G()\n sage: G.basis()\n Lazy family (Term map from Standard permutations to Free Quasi-symmetric functions over Rational Field in the G basis(i))_{i in Standard permutations}\n sage: G.basis().keys()\n Standard permutations\n sage: G.basis(degree=3).keys()\n Standard permutations of 3\n sage: G.basis(degree=3).list()\n [G[1, 2, 3], G[1, 3, 2], G[2, 1, 3], G[2, 3, 1], G[3, 1, 2], G[3, 2, 1]]\n '
from sage.sets.family import Family
if (degree is None):
return Family(self._indices, self.monomial)
else:
return Family(Permutations(degree), self.monomial)
def is_field(self, proof=True):
'\n Return whether this `FQSym` is a field.\n\n EXAMPLES::\n\n sage: F = algebras.FQSym(QQ).F()\n sage: F.is_field()\n False\n '
return False
def is_commutative(self):
'\n Return whether this `FQSym` is commutative.\n\n EXAMPLES::\n\n sage: F = algebras.FQSym(ZZ).F()\n sage: F.is_commutative()\n False\n '
return self.base_ring().is_zero()
def some_elements(self):
'\n Return some elements of the free quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ)\n sage: F = A.F()\n sage: F.some_elements()\n [F[], F[1], F[1, 2] + F[2, 1], F[] + F[1, 2] + F[2, 1]]\n sage: G = A.G()\n sage: G.some_elements()\n [G[], G[1], G[1, 2] + G[2, 1], G[] + G[1, 2] + G[2, 1]]\n sage: M = A.M()\n sage: M.some_elements()\n [M[], M[1], M[1, 2] + 2*M[2, 1], M[] + M[1, 2] + 2*M[2, 1]]\n '
u = self.one()
o = self.monomial(Permutation([1]))
x = (o * o)
y = (u + x)
return [u, o, x, y]
@cached_method
def one_basis(self):
'\n Return the index of the unit.\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: A.one_basis()\n []\n '
Perm = self.basis().keys()
return Perm([])
@lazy_attribute
def succ(self):
'\n Return the `\\succ` product.\n\n On the F-basis of ``FQSym``, this product is determined by\n `F_x \\succ F_y = \\sum F_z`, where the sum ranges over all `z`\n in the shifted shuffle of `x` and `y` with the additional\n condition that the first letter of the result comes from `y`.\n\n The usual symbol for this operation is `\\succ`.\n\n .. SEEALSO::\n\n :meth:`~sage.categories.magmas.Magmas.ParentMethods.product`,\n :meth:`prec`\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = A([1])\n sage: A.succ(x, x)\n F[2, 1]\n sage: y = A([3,1,2])\n sage: A.succ(x, y)\n F[4, 1, 2, 3] + F[4, 2, 1, 3] + F[4, 2, 3, 1]\n sage: A.succ(y, x)\n F[4, 3, 1, 2]\n '
try:
suc = self.succ_product_on_basis
except AttributeError:
return self.succ_by_coercion
return self._module_morphism(self._module_morphism(suc, position=0, codomain=self), position=1)
def succ_by_coercion(self, x, y):
'\n Return `x \\succ y`, computed using coercion to the F-basis.\n\n See :meth:`succ` for the definition of the objects involved.\n\n EXAMPLES::\n\n sage: G = algebras.FQSym(ZZ).G()\n sage: G.succ(G([1]), G([2, 3, 1])) # indirect doctest\n G[2, 3, 4, 1] + G[3, 2, 4, 1] + G[4, 2, 3, 1]\n '
F = self.realization_of().a_realization()
return self(F.succ(F(x), F(y)))
@lazy_attribute
def prec(self):
'\n Return the `\\prec` product.\n\n On the F-basis of ``FQSym``, this product is determined by\n `F_x \\prec F_y = \\sum F_z`, where the sum ranges over all `z`\n in the shifted shuffle of `x` and `y` with the additional\n condition that the first letter of the result comes from `x`.\n\n The usual symbol for this operation is `\\prec`.\n\n .. SEEALSO::\n\n :meth:`~sage.categories.magmas.Magmas.ParentMethods.product`,\n :meth:`succ`\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: x = A([2,1])\n sage: A.prec(x, x)\n F[2, 1, 4, 3] + F[2, 4, 1, 3] + F[2, 4, 3, 1]\n sage: y = A([2,1,3])\n sage: A.prec(x, y)\n F[2, 1, 4, 3, 5] + F[2, 4, 1, 3, 5] + F[2, 4, 3, 1, 5]\n + F[2, 4, 3, 5, 1]\n sage: A.prec(y, x)\n F[2, 1, 3, 5, 4] + F[2, 1, 5, 3, 4] + F[2, 1, 5, 4, 3]\n + F[2, 5, 1, 3, 4] + F[2, 5, 1, 4, 3] + F[2, 5, 4, 1, 3]\n '
try:
pre = self.prec_product_on_basis
except AttributeError:
return self.prec_by_coercion
return self._module_morphism(self._module_morphism(pre, position=0, codomain=self), position=1)
def prec_by_coercion(self, x, y):
'\n Return `x \\prec y`, computed using coercion to the F-basis.\n\n See :meth:`prec` for the definition of the objects involved.\n\n EXAMPLES::\n\n sage: G = algebras.FQSym(ZZ).G()\n sage: a = G([1])\n sage: b = G([2, 3, 1])\n sage: G.prec(a, b) + G.succ(a, b) == a * b # indirect doctest\n True\n '
F = self.realization_of().a_realization()
return self(F.prec(F(x), F(y)))
def from_symmetric_group_algebra(self, x):
'\n Return the element of `FQSym` corresponding to the element\n `x` of a symmetric group algebra.\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).F()\n sage: SGA4 = SymmetricGroupAlgebra(QQ, 4)\n sage: x = SGA4([1,3,2,4]) + 5/2 * SGA4([1,2,4,3])\n sage: A.from_symmetric_group_algebra(x)\n 5/2*F[1, 2, 4, 3] + F[1, 3, 2, 4]\n sage: A.from_symmetric_group_algebra(SGA4.zero())\n 0\n '
return self._from_dict({Permutation(key): c for (key, c) in x})
class ElementMethods():
def omega_involution(self):
'\n Return the image of the element ``self`` of `FQSym`\n under the omega involution.\n\n The `\\omega` involution is defined as the\n linear map `FQSym \\to FQSym` that sends each basis\n element `F_u` of the F-basis of `FQSym`\n to the basis element `F_{u \\circ w_0}`, where `w_0` is\n the longest word (i.e., `w_0(i) = n + 1 - i`) in the\n symmetric group `S_n` that contains `u`. The `\\omega`\n involution is a graded algebra automorphism and a\n coalgebra anti-automorphism of `FQSym`. Every\n permutation `u \\in S_n` satisfies\n\n .. MATH::\n\n \\omega(F_u) = F_{u \\circ w_0}, \\qquad\n \\omega(G_u) = G_{w_0 \\circ u},\n\n where standard notations for classical bases of `FQSym`\n are being used (that is, `F` for the F-basis, and\n `G` for the G-basis).\n In other words, writing permutations in one-line notation,\n we have\n\n .. MATH::\n\n \\omega(F_{(u_1, u_2, \\ldots, u_n)})\n = F_{(u_n, u_{n-1}, \\ldots, u_1)}, \\qquad\n \\omega(G_{(u_1, u_2, \\ldots, u_n)})\n = G_{(n+1-u_1, n+1-u_2, \\ldots, n+1-u_n)}.\n\n If we also consider the `\\omega` involution\n (:meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.omega_involution`)\n of the quasisymmetric functions (by slight abuse\n of notation), and if we let `\\pi` be the canonical\n projection `FQSym \\to QSym`, then\n `\\pi \\circ \\omega = \\omega \\circ \\pi`.\n\n Additionally, consider the `\\psi` involution\n (:meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution`)\n of the noncommutative symmetric functions, and if we let\n `\\iota` be the canonical inclusion `NSym \\to FQSym`,\n then `\\omega \\circ \\iota = \\iota \\circ \\psi`.\n\n .. TODO::\n\n Duality?\n\n .. SEEALSO::\n\n :meth:`psi_involution`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: F[[2,3,1]].omega_involution()\n F[1, 3, 2]\n sage: (3*F[[1]] - 4*F[[]] + 5*F[[1,2]]).omega_involution()\n -4*F[] + 3*F[1] + 5*F[2, 1]\n sage: G = FQSym.G()\n sage: G[[2,3,1]].omega_involution()\n G[2, 1, 3]\n sage: M = FQSym.M()\n sage: M[[2,3,1]].omega_involution()\n -M[1, 2, 3] - M[2, 1, 3] - M[3, 1, 2]\n\n The omega involution is an algebra homomorphism::\n\n sage: (F[1,2] * F[1]).omega_involution()\n F[2, 1, 3] + F[2, 3, 1] + F[3, 2, 1]\n sage: F[1,2].omega_involution() * F[1].omega_involution()\n F[2, 1, 3] + F[2, 3, 1] + F[3, 2, 1]\n\n The omega involution intertwines the antipode\n and the inverse of the antipode::\n\n sage: all( F(I).antipode().omega_involution().antipode()\n ....: == F(I).omega_involution()\n ....: for I in Permutations(4) )\n True\n\n Testing the `\\pi \\circ \\omega = \\omega \\circ \\pi` relation\n noticed above::\n\n sage: all( M[I].omega_involution().to_qsym()\n ....: == M[I].to_qsym().omega_involution()\n ....: for I in Permutations(4) )\n True\n\n Testing the `\\omega \\circ \\iota = \\iota \\circ \\psi` relation::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: all( S[I].psi_involution().to_fqsym() == S[I].to_fqsym().omega_involution()\n ....: for I in Compositions(4) )\n True\n\n .. TODO::\n\n Check further commutative squares.\n '
parent = self.parent()
F = parent.realization_of().F()
dct = {I.reverse(): coeff for (I, coeff) in F(self)}
return parent(F._from_dict(dct, remove_zeros=False))
def psi_involution(self):
'\n Return the image of the element ``self`` of `FQSym`\n under the psi involution.\n\n The `\\psi` involution is defined as the\n linear map `FQSym \\to FQSym` that sends each basis\n element `F_u` of the F-basis of `FQSym`\n to the basis element `F_{w_0 \\circ u}`, where `w_0` is\n the longest word (i.e., `w_0(i) = n + 1 - i`) in the\n symmetric group `S_n` that contains `u`. The `\\psi`\n involution is a graded coalgebra automorphism and\n an algebra anti-automorphism of `FQSym`. Every\n permutation `u \\in S_n` satisfies\n\n .. MATH::\n\n \\psi(F_u) = F_{w_0 \\circ u}, \\qquad\n \\psi(G_u) = G_{u \\circ w_0},\n\n where standard notations for classical bases of `FQSym`\n are being used (that is, `F` for the F-basis, and\n `G` for the G-basis). In other words, writing\n permutations in one-line notation, we have\n\n .. MATH::\n\n \\psi(F_{(u_1, u_2, \\ldots, u_n)})\n = F_{(n+1-u_1, n+1-u_2, \\ldots, n+1-u_n)}, \\qquad\n \\psi(G_{(u_1, u_2, \\ldots, u_n)})\n = G_{(u_n, u_{n-1}, \\ldots, u_1)}.\n\n If we also consider the `\\psi` involution\n (:meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution`)\n of the quasisymmetric functions (by slight abuse of\n notation), and if we let `\\pi` be the canonical\n projection `FQSym \\to QSym`, then\n `\\pi \\circ \\psi = \\psi \\circ \\pi`.\n\n Additionally, consider the `\\omega` involution\n (:meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.omega_involution`)\n of the noncommutative symmetric functions, and if we let\n `\\iota` be the canonical inclusion `NSym \\to FQSym`,\n then `\\psi \\circ \\iota = \\iota \\circ \\omega`.\n\n .. TODO::\n\n Duality?\n\n .. SEEALSO::\n\n :meth:`omega_involution`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: F[[2,3,1]].psi_involution()\n F[2, 1, 3]\n sage: (3*F[[1]] - 4*F[[]] + 5*F[[1,2]]).psi_involution()\n -4*F[] + 3*F[1] + 5*F[2, 1]\n sage: G = FQSym.G()\n sage: G[[2,3,1]].psi_involution()\n G[1, 3, 2]\n sage: M = FQSym.M()\n sage: M[[2,3,1]].psi_involution()\n -M[1, 2, 3] - M[1, 3, 2] - M[2, 3, 1]\n\n The `\\psi` involution intertwines the antipode\n and the inverse of the antipode::\n\n sage: all( F(I).antipode().psi_involution().antipode()\n ....: == F(I).psi_involution()\n ....: for I in Permutations(4) )\n True\n\n Testing the `\\pi \\circ \\psi = \\psi \\circ \\pi` relation above::\n\n sage: all( M[I].psi_involution().to_qsym()\n ....: == M[I].to_qsym().psi_involution()\n ....: for I in Permutations(4) )\n True\n\n Testing the `\\psi \\circ \\iota = \\iota \\circ \\omega` relation::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: all( S[I].omega_involution().to_fqsym() == S[I].to_fqsym().psi_involution()\n ....: for I in Compositions(4) )\n True\n\n .. TODO::\n\n Check further commutative squares.\n '
parent = self.parent()
F = parent.realization_of().F()
dct = {I.complement(): coeff for (I, coeff) in F(self)}
return parent(F._from_dict(dct, remove_zeros=False))
def star_involution(self):
'\n Return the image of the element ``self`` of `FQSym`\n under the star involution.\n\n The star involution is defined as the\n linear map `FQSym \\to FQSym` that sends each basis\n element `F_u` of the F-basis of `FQSym`\n to the basis element `F_{w_0 \\circ u \\circ w_0}`, where\n `w_0` is the longest word (i.e., `w_0(i) = n + 1 - i`)\n in the symmetric group `S_n` that contains `u`.\n The star involution is a graded Hopf algebra\n anti-automorphism of `FQSym`.\n It is denoted by `f \\mapsto f^*`. Every permutation\n `u \\in S_n` satisfies\n\n .. MATH::\n\n (F_u)^* = F_{w_0 \\circ u \\circ w_0}, \\qquad\n (G_u)^* = G_{w_0 \\circ u \\circ w_0}, \\qquad\n (\\mathcal{M}_u)^* = \\mathcal{M}_{w_0 \\circ u \\circ w_0},\n\n where standard notations for classical bases of `FQSym`\n are being used (that is, `F` for the F-basis,\n `G` for the G-basis, and `\\mathcal{M}` for the Monomial\n basis). In other words, writing permutations in one-line\n notation, we have\n\n .. MATH::\n\n (F_{(u_1, u_2, \\ldots, u_n)})^*\n = F_{(n+1-u_n, n+1-u_{n-1}, \\ldots, n+1-u_1)}, \\qquad\n (G_{(u_1, u_2, \\ldots, u_n)})^*\n = G_{(n+1-u_n, n+1-u_{n-1}, \\ldots, n+1-u_1)},\n\n and\n\n .. MATH::\n\n (\\mathcal{M}_{(u_1, u_2, \\ldots, u_n)})^*\n = \\mathcal{M}_{(n+1-u_n, n+1-u_{n-1}, \\ldots, n+1-u_1)}.\n\n Let us denote the star involution by `(\\ast)` as well.\n\n If we also denote by `(\\ast)` the star involution of\n of the quasisymmetric functions\n (:meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution`)\n and if we let `\\pi : FQSym \\to QSym` be the canonical\n projection then `\\pi \\circ (\\ast) = (\\ast) \\circ \\pi`.\n Similar for the noncommutative symmetric functions\n (:meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution`)\n with `\\pi : NSym \\to FQSym` being the canonical inclusion\n and the word quasisymmetric functions\n (:meth:`~sage.combinat.chas.wqsym.WordQuasiSymmetricFunctions.Bases.ElementMethods.star_involution`)\n with `\\pi : FQSym \\to WQSym` the canonical inclusion.\n\n .. TODO::\n\n Duality?\n\n .. SEEALSO::\n\n :meth:`omega_involution`, :meth:`psi_involution`\n\n EXAMPLES::\n\n sage: FQSym = algebras.FQSym(ZZ)\n sage: F = FQSym.F()\n sage: F[[2,3,1]].star_involution()\n F[3, 1, 2]\n sage: (3*F[[1]] - 4*F[[]] + 5*F[[1,2]]).star_involution()\n -4*F[] + 3*F[1] + 5*F[1, 2]\n sage: G = FQSym.G()\n sage: G[[2,3,1]].star_involution()\n G[3, 1, 2]\n sage: M = FQSym.M()\n sage: M[[2,3,1]].star_involution()\n M[3, 1, 2]\n\n The star involution commutes with the antipode::\n\n sage: all( F(I).antipode().star_involution()\n ....: == F(I).star_involution().antipode()\n ....: for I in Permutations(4) )\n True\n\n Testing the `\\pi \\circ (\\ast) = (\\ast) \\circ \\pi` relation::\n\n sage: all( M[I].star_involution().to_qsym()\n ....: == M[I].to_qsym().star_involution()\n ....: for I in Permutations(4) )\n True\n\n Similar for `NSym`::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: all( S[I].star_involution().to_fqsym() == S[I].to_fqsym().star_involution()\n ....: for I in Compositions(4) )\n True\n\n Similar for `WQSym`::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: all( F(I).to_wqsym().star_involution()\n ....: == F(I).star_involution().to_wqsym()\n ....: for I in Permutations(4) )\n True\n\n .. TODO::\n\n Check further commutative squares.\n '
parent = self.parent()
F = parent.realization_of().F()
dct = {I.complement().reverse(): coeff for (I, coeff) in F(self)}
return parent(F._from_dict(dct, remove_zeros=False))
def to_symmetric_group_algebra(self, n=None):
'\n Return the element of a symmetric group algebra\n corresponding to the element ``self`` of `FQSym`.\n\n INPUT:\n\n - ``n`` -- integer (default: the maximal degree of ``self``);\n the rank of the target symmetric group algebra\n\n EXAMPLES::\n\n sage: A = algebras.FQSym(QQ).G()\n sage: x = A([1,3,2,4]) + 5/2 * A([2,3,4,1])\n sage: x.to_symmetric_group_algebra()\n [1, 3, 2, 4] + 5/2*[4, 1, 2, 3]\n '
F = self.parent().realization_of().F()
return F(self).to_symmetric_group_algebra(n=n)
def to_wqsym(self):
'\n Return the image of ``self`` under the canonical\n inclusion map `FQSym \\to WQSym`.\n\n The canonical inclusion map `FQSym \\to WQSym` is\n an injective homomorphism of Hopf algebras. It sends\n a basis element `G_w` of `FQSym` to the sum of\n basis elements `\\mathbf{M}_u` of `WQSym`, where `u`\n ranges over all packed words whose standardization\n is `w`.\n\n .. SEEALSO::\n\n :class:`WordQuasiSymmetricFunctions` for a\n definition of `WQSym`.\n\n EXAMPLES::\n\n sage: G = algebras.FQSym(QQ).G()\n sage: x = G[1, 3, 2]\n sage: x.to_wqsym()\n M[{1}, {3}, {2}] + M[{1, 3}, {2}]\n sage: G[1, 2].to_wqsym()\n M[{1}, {2}] + M[{1, 2}]\n sage: F = algebras.FQSym(QQ).F()\n sage: F[3, 1, 2].to_wqsym()\n M[{3}, {1}, {2}] + M[{3}, {1, 2}]\n sage: G[2, 3, 1].to_wqsym()\n M[{3}, {1}, {2}] + M[{3}, {1, 2}]\n '
parent = self.parent()
FQSym = parent.realization_of()
G = FQSym.G()
from sage.combinat.chas.wqsym import WordQuasiSymmetricFunctions
M = WordQuasiSymmetricFunctions(parent.base_ring()).M()
OSP = M.basis().keys()
from sage.combinat.words.finite_word import word_to_ordered_set_partition
def to_wqsym_on_G_basis(w):
dc = w.inverse().descents_composition()
res = M.zero()
for comp in dc.finer():
v = w.destandardize(comp)
res += M[OSP(word_to_ordered_set_partition(v))]
return res
return M.linear_combination(((to_wqsym_on_G_basis(w), coeff) for (w, coeff) in G(self)))
def to_qsym(self):
'\n Return the image of ``self`` under the canonical\n projection `FQSym \\to QSym`.\n\n The canonical projection `FQSym \\to QSym` is a\n surjective homomorphism of Hopf algebras. It sends a\n basis element `F_w` of `FQSym` to the basis element\n `F_{\\operatorname{Comp} w}` of the fundamental basis\n of `QSym`, where `\\operatorname{Comp} w` stands for\n the descent composition\n (:meth:`sage.combinat.permutation.Permutation.descents_composition`)\n of the permutation `w`.\n\n .. SEEALSO::\n\n :class:`QuasiSymmetricFunctions` for a\n definition of `QSym`.\n\n EXAMPLES::\n\n sage: G = algebras.FQSym(QQ).G()\n sage: x = G[1, 3, 2]\n sage: x.to_qsym()\n F[2, 1]\n sage: G[2, 3, 1].to_qsym()\n F[1, 2]\n sage: F = algebras.FQSym(QQ).F()\n sage: F[2, 3, 1].to_qsym()\n F[2, 1]\n sage: (F[2, 3, 1] + F[1, 3, 2] + F[1, 2, 3]).to_qsym()\n 2*F[2, 1] + F[3]\n sage: F2 = algebras.FQSym(GF(2)).F()\n sage: F2[2, 3, 1].to_qsym()\n F[2, 1]\n sage: (F2[2, 3, 1] + F2[1, 3, 2] + F2[1, 2, 3]).to_qsym()\n F[3]\n '
parent = self.parent()
FQSym = parent.realization_of()
F = FQSym.F()
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
QF = QuasiSymmetricFunctions(parent.base_ring()).F()
return QF.sum_of_terms(((w.descents_composition(), coeff) for (w, coeff) in F(self)))
|
class FreeDendriformAlgebra(CombinatorialFreeModule):
"\n The free dendriform algebra.\n\n Dendriform algebras are associative algebras, where the associative\n product `*` is decomposed as a sum of two binary operations\n\n .. MATH::\n\n x * y = x \\succ y + x \\prec y\n\n that satisfy the axioms:\n\n .. MATH::\n\n (x \\succ y) \\prec z = x \\succ (y \\prec z),\n\n .. MATH::\n\n (x \\prec y) \\prec z = x \\prec (y * z).\n\n .. MATH::\n\n (x * y) \\succ z = x \\succ (y \\succ z).\n\n The free Dendriform algebra on a given set `E` has an explicit\n description using (planar) binary trees, just as the free\n associative algebra can be described using words. The underlying\n vector space has a basis indexed by finite binary trees endowed\n with a map from their vertices to `E`. In this basis, the\n associative product of two (decorated) binary trees `S * T` is the\n sum over all possible ways of identifying (glueing) the rightmost path in\n `S` and the leftmost path in `T`.\n\n The decomposition of the associative product as the sum of two\n binary operations `\\succ` and\n `\\prec` is made by separating the terms according to the origin of\n the root vertex. For `x \\succ y`, one keeps the terms where the root\n vertex comes from `y`, whereas for `x \\prec y` one keeps the terms\n where the root vertex comes from `x`.\n\n The free dendriform algebra can also be considered as the free\n algebra over the Dendriform operad.\n\n .. NOTE::\n\n The usual binary operator `*` is used for the\n associative product.\n\n EXAMPLES::\n\n sage: F = algebras.FreeDendriform(ZZ, 'xyz')\n sage: x,y,z = F.gens()\n sage: (x * y) * z\n B[x[., y[., z[., .]]]] + B[x[., z[y[., .], .]]] + B[y[x[., .], z[., .]]] + B[z[x[., y[., .]], .]] + B[z[y[x[., .], .], .]]\n\n The free dendriform algebra is associative::\n\n sage: x * (y * z) == (x * y) * z\n True\n\n The associative product decomposes in two parts::\n\n sage: x * y == F.prec(x, y) + F.succ(x, y)\n True\n\n The axioms hold::\n\n sage: F.prec(F.succ(x, y), z) == F.succ(x, F.prec(y, z))\n True\n sage: F.prec(F.prec(x, y), z) == F.prec(x, y * z)\n True\n sage: F.succ(x * y, z) == F.succ(x, F.succ(y, z))\n True\n\n When there is only one generator, unlabelled trees are used instead::\n\n sage: F1 = algebras.FreeDendriform(QQ)\n sage: w = F1.gen(0); w\n B[[., .]]\n sage: w * w * w\n B[[., [., [., .]]]] + B[[., [[., .], .]]] + B[[[., .], [., .]]] + B[[[., [., .]], .]] + B[[[[., .], .], .]]\n\n The set `E` can be infinite::\n\n sage: F = algebras.FreeDendriform(QQ, ZZ)\n sage: w = F.gen(1); w\n B[1[., .]]\n sage: x = F.gen(2); x\n B[-1[., .]]\n sage: w*x\n B[-1[1[., .], .]] + B[1[., -1[., .]]]\n\n REFERENCES:\n\n - [LR1998]_\n "
@staticmethod
def __classcall_private__(cls, R, names=None):
"\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: F1 = algebras.FreeDendriform(QQ, 'xyz')\n sage: F2 = algebras.FreeDendriform(QQ, ['x','y','z'])\n sage: F3 = algebras.FreeDendriform(QQ, Alphabet('xyz'))\n sage: F1 is F2 and F1 is F3\n True\n "
if (names is not None):
if (',' in names):
names = [u for u in names if (u != ',')]
names = Alphabet(names)
if (R not in Rings()):
raise TypeError('argument R must be a ring')
return super().__classcall__(cls, R, names)
def __init__(self, R, names=None):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: A = algebras.FreeDendriform(QQ, '@'); A\n Free Dendriform algebra on one generator ['@'] over Rational Field\n sage: TestSuite(A).run() # long time (3s)\n\n sage: F = algebras.FreeDendriform(QQ, 'xy')\n sage: TestSuite(F).run() # long time (3s)\n "
if (names is None):
Trees = BinaryTrees()
key = BinaryTree._sort_key
self._alphabet = Alphabet(['o'])
else:
Trees = LabelledBinaryTrees()
key = LabelledBinaryTree._sort_key
self._alphabet = names
cat = HopfAlgebras(R).WithBasis().Graded().Connected()
CombinatorialFreeModule.__init__(self, R, Trees, latex_prefix='', sorting_key=key, category=cat)
def variable_names(self):
"\n Return the names of the variables.\n\n EXAMPLES::\n\n sage: R = algebras.FreeDendriform(QQ, 'xy')\n sage: R.variable_names()\n {'x', 'y'}\n "
return self._alphabet
def _repr_(self):
"\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.FreeDendriform(QQ, '@') # indirect doctest\n Free Dendriform algebra on one generator ['@'] over Rational Field\n "
n = self.algebra_generators().cardinality()
finite = bool((n < Infinity))
if (not finite):
gen = 'generators indexed by'
elif (n == 1):
gen = 'one generator'
else:
gen = '{} generators'.format(n)
s = 'Free Dendriform algebra on {} {} over {}'
if finite:
try:
return s.format(gen, self._alphabet.list(), self.base_ring())
except NotImplementedError:
return s.format(gen, self._alphabet, self.base_ring())
else:
return s.format(gen, self._alphabet, self.base_ring())
def gen(self, i):
"\n Return the ``i``-th generator of the algebra.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: F = algebras.FreeDendriform(ZZ, 'xyz')\n sage: F.gen(0)\n B[x[., .]]\n\n sage: F.gen(4)\n Traceback (most recent call last):\n ...\n IndexError: argument i (= 4) must be between 0 and 2\n "
G = self.algebra_generators()
n = G.cardinality()
if ((i < 0) or (not (i < n))):
m = 'argument i (= {}) must be between 0 and {}'.format(i, (n - 1))
raise IndexError(m)
return G[G.keys().unrank(i)]
@cached_method
def algebra_generators(self):
"\n Return the generators of this algebra.\n\n These are the binary trees with just one vertex.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(ZZ, 'fgh'); A\n Free Dendriform algebra on 3 generators ['f', 'g', 'h']\n over Integer Ring\n sage: list(A.algebra_generators())\n [B[f[., .]], B[g[., .]], B[h[., .]]]\n\n sage: A = algebras.FreeDendriform(QQ, ['x1','x2'])\n sage: list(A.algebra_generators())\n [B[x1[., .]], B[x2[., .]]]\n "
Trees = self.basis().keys()
return Family(self._alphabet, (lambda a: self.monomial(Trees([], a))))
def change_ring(self, R):
"\n Return the free dendriform algebra in the same variables over `R`.\n\n INPUT:\n\n - ``R`` -- a ring\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(ZZ, 'fgh')\n sage: A.change_ring(QQ)\n Free Dendriform algebra on 3 generators ['f', 'g', 'h'] over\n Rational Field\n "
return FreeDendriformAlgebra(R, names=self.variable_names())
def gens(self):
"\n Return the generators of ``self`` (as an algebra).\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(ZZ, 'fgh')\n sage: A.gens()\n (B[f[., .]], B[g[., .]], B[h[., .]])\n "
return tuple(self.algebra_generators())
def degree_on_basis(self, t):
"\n Return the degree of a binary tree in the free Dendriform algebra.\n\n This is the number of vertices.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ,'@')\n sage: RT = A.basis().keys()\n sage: u = RT([], '@')\n sage: A.degree_on_basis(u.over(u))\n 2\n "
return t.node_number()
@cached_method
def an_element(self):
"\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ, 'xy')\n sage: A.an_element()\n B[x[., .]] + 2*B[x[., x[., .]]] + 2*B[x[x[., .], .]]\n "
o = self.gen(0)
return (o + ((2 * o) * o))
def some_elements(self):
"\n Return some elements of the free dendriform algebra.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: A.some_elements()\n [B[.],\n B[[., .]],\n B[[., [., .]]] + B[[[., .], .]],\n B[.] + B[[., [., .]]] + B[[[., .], .]]]\n\n With several generators::\n\n sage: A = algebras.FreeDendriform(QQ, 'xy')\n sage: A.some_elements()\n [B[.],\n B[x[., .]],\n B[x[., x[., .]]] + B[x[x[., .], .]],\n B[.] + B[x[., x[., .]]] + B[x[x[., .], .]]]\n "
u = self.one()
o = self.gen(0)
x = (o * o)
y = (u + x)
return [u, o, x, y]
def one_basis(self):
"\n Return the index of the unit.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ, '@')\n sage: A.one_basis()\n .\n sage: A = algebras.FreeDendriform(QQ, 'xy')\n sage: A.one_basis()\n .\n "
Trees = self.basis().keys()
return Trees(None)
def product_on_basis(self, x, y):
'\n Return the `*` associative dendriform product of two trees.\n\n This is the sum over all possible ways of identifying the\n rightmost path in `x` and the leftmost path in `y`. Every term\n corresponds to a shuffle of the vertices on the rightmost path\n in `x` and the vertices on the leftmost path in `y`.\n\n .. SEEALSO::\n\n - :meth:`succ_product_on_basis`, :meth:`prec_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = RT([])\n sage: A.product_on_basis(x, x)\n B[[., [., .]]] + B[[[., .], .]]\n '
return self.sum((self.basis()[u] for u in x.dendriform_shuffle(y)))
def succ_product_on_basis(self, x, y):
'\n Return the `\\succ` dendriform product of two trees.\n\n This is the sum over all possible ways to identify the rightmost path\n in `x` and the leftmost path in `y`, with the additional condition\n that the root vertex of the result comes from `y`.\n\n The usual symbol for this operation is `\\succ`.\n\n .. SEEALSO::\n\n - :meth:`product_on_basis`, :meth:`prec_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = RT([])\n sage: A.succ_product_on_basis(x, x)\n B[[[., .], .]]\n\n TESTS::\n\n sage: u = A.one().support()[0]\n sage: A.succ_product_on_basis(u, u)\n Traceback (most recent call last):\n ...\n ValueError: dendriform products | < | and | > | are not defined\n '
if y.is_empty():
if x.is_empty():
raise ValueError('dendriform products | < | and | > | are not defined')
else:
return []
if x.is_empty():
return [y]
K = self.basis().keys()
if hasattr(y, 'label'):
return self.sum((self.basis()[K([u, y[1]], y.label())] for u in x.dendriform_shuffle(y[0])))
return self.sum((self.basis()[K([u, y[1]])] for u in x.dendriform_shuffle(y[0])))
@lazy_attribute
def succ(self):
'\n Return the `\\succ` dendriform product.\n\n This is the sum over all possible ways of identifying the\n rightmost path in `x` and the leftmost path in `y`, with the\n additional condition that the root vertex of the result comes\n from `y`.\n\n The usual symbol for this operation is `\\succ`.\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`prec`, :meth:`over`, :meth:`under`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = A.gen(0)\n sage: A.succ(x, x)\n B[[[., .], .]]\n '
suc = self.succ_product_on_basis
return self._module_morphism(self._module_morphism(suc, position=0, codomain=self), position=1)
def prec_product_on_basis(self, x, y):
'\n Return the `\\prec` dendriform product of two trees.\n\n This is the sum over all possible ways of identifying the\n rightmost path in `x` and the leftmost path in `y`, with the\n additional condition that the root vertex of the result comes\n from `x`.\n\n The usual symbol for this operation is `\\prec`.\n\n .. SEEALSO::\n\n - :meth:`product_on_basis`, :meth:`succ_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = RT([])\n sage: A.prec_product_on_basis(x, x)\n B[[., [., .]]]\n\n TESTS::\n\n sage: u = A.one().support()[0]\n sage: A.prec_product_on_basis(u, u)\n Traceback (most recent call last):\n ...\n ValueError: dendriform products | < | and | > | are not defined\n '
if (x.is_empty() and y.is_empty()):
raise ValueError('dendriform products | < | and | > | are not defined')
if x.is_empty():
return []
if y.is_empty():
return [x]
K = self.basis().keys()
if hasattr(y, 'label'):
return self.sum((self.basis()[K([x[0], u], x.label())] for u in x[1].dendriform_shuffle(y)))
return self.sum((self.basis()[K([x[0], u])] for u in x[1].dendriform_shuffle(y)))
@lazy_attribute
def prec(self):
'\n Return the `\\prec` dendriform product.\n\n This is the sum over all possible ways to identify the rightmost path\n in `x` and the leftmost path in `y`, with the additional condition\n that the root vertex of the result comes from `x`.\n\n The usual symbol for this operation is `\\prec`.\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`succ`, :meth:`over`, :meth:`under`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = A.gen(0)\n sage: A.prec(x, x)\n B[[., [., .]]]\n '
pre = self.prec_product_on_basis
return self._module_morphism(self._module_morphism(pre, position=0, codomain=self), position=1)
@lazy_attribute
def over(self):
'\n Return the over product.\n\n The over product `x/y` is the binary tree obtained by\n grafting the root of `y` at the rightmost leaf of `x`.\n\n The usual symbol for this operation is `/`.\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`succ`, :meth:`prec`, :meth:`under`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = A.gen(0)\n sage: A.over(x, x)\n B[[., [., .]]]\n '
def ov(x, y):
return self._monomial(x.over(y))
return self._module_morphism(self._module_morphism(ov, position=0, codomain=self), position=1)
@lazy_attribute
def under(self):
'\n Return the under product.\n\n The over product `x \\backslash y` is the binary tree obtained by\n grafting the root of `x` at the leftmost leaf of `y`.\n\n The usual symbol for this operation is `\\backslash`.\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`succ`, :meth:`prec`, :meth:`over`\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: RT = A.basis().keys()\n sage: x = A.gen(0)\n sage: A.under(x, x)\n B[[[., .], .]]\n '
def und(x, y):
return self._monomial(x.under(y))
return self._module_morphism(self._module_morphism(und, position=0, codomain=self), position=1)
def coproduct_on_basis(self, x):
"\n Return the coproduct of a binary tree.\n\n EXAMPLES::\n\n sage: A = algebras.FreeDendriform(QQ)\n sage: x = A.gen(0)\n sage: ascii_art(A.coproduct(A.one())) # indirect doctest\n 1 # 1\n\n sage: ascii_art(A.coproduct(x)) # indirect doctest\n 1 # B + B # 1\n o o\n\n sage: A = algebras.FreeDendriform(QQ, 'xyz')\n sage: x, y, z = A.gens()\n sage: w = A.under(z,A.over(x,y))\n sage: A.coproduct(z)\n B[.] # B[z[., .]] + B[z[., .]] # B[.]\n sage: A.coproduct(w)\n B[.] # B[x[z[., .], y[., .]]] + B[x[., .]] # B[z[., y[., .]]] +\n B[x[., .]] # B[y[z[., .], .]] + B[x[., y[., .]]] # B[z[., .]] +\n B[x[z[., .], .]] # B[y[., .]] + B[x[z[., .], y[., .]]] # B[.]\n "
B = self.basis()
Trees = B.keys()
if (not x.node_number()):
return self.one().tensor(self.one())
(L, R) = list(x)
try:
root = x.label()
except AttributeError:
root = '@'
resu = self.one().tensor(self.monomial(x))
resu += sum((((cL * cR) * self.monomial(Trees([LL[0], RR[0]], root)).tensor((self.monomial(LL[1]) * self.monomial(RR[1])))) for (LL, cL) in self.coproduct_on_basis(L) for (RR, cR) in self.coproduct_on_basis(R)))
return resu
def _element_constructor_(self, x):
"\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.FreeDendriform(QQ, 'xy')\n sage: x, y = R.gens()\n sage: R(x)\n B[x[., .]]\n sage: R(x+4*y)\n B[x[., .]] + 4*B[y[., .]]\n\n sage: Trees = R.basis().keys()\n sage: R(Trees([],'x'))\n B[x[., .]]\n sage: D = algebras.FreeDendriform(ZZ, 'xy')\n sage: X, Y = D.gens()\n sage: R(X-Y).parent()\n Free Dendriform algebra on 2 generators ['x', 'y'] over Rational Field\n "
if (x in self.basis().keys()):
return self.monomial(x)
try:
P = x.parent()
if isinstance(P, FreeDendriformAlgebra):
if (P is self):
return x
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
raise TypeError('not able to coerce this in this algebra')
def _coerce_map_from_(self, R):
"\n Return ``True`` if there is a coercion from ``R`` into ``self``\n and ``False`` otherwise.\n\n The things that coerce into ``self`` are\n\n - free dendriform algebras in a subset of variables of ``self``\n over a base with a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: F = algebras.FreeDendriform(GF(7), 'xyz'); F\n Free Dendriform algebra on 3 generators ['x', 'y', 'z']\n over Finite Field of size 7\n\n Elements of the free dendriform algebra canonically coerce in::\n\n sage: x, y, z = F.gens()\n sage: F.coerce(x+y) == x+y\n True\n\n The free dendriform algebra over `\\ZZ` on `x, y, z` coerces in, since\n `\\ZZ` coerces to `\\GF{7}`::\n\n sage: G = algebras.FreeDendriform(ZZ, 'xyz')\n sage: Gx,Gy,Gz = G.gens()\n sage: z = F.coerce(Gx+Gy); z\n B[x[., .]] + B[y[., .]]\n sage: z.parent() is F\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so the free dendriform\n algebra over `\\GF{7}` does not coerce to the one over `\\ZZ`::\n\n sage: G.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Free Dendriform algebra\n on 3 generators ['x', 'y', 'z'] over Finite Field of size\n 7 to Free Dendriform algebra on 3 generators ['x', 'y', 'z']\n over Integer Ring\n\n TESTS::\n\n sage: F = algebras.FreeDendriform(ZZ, 'xyz')\n sage: G = algebras.FreeDendriform(QQ, 'xyz')\n sage: H = algebras.FreeDendriform(ZZ, 'y')\n sage: F._coerce_map_from_(G)\n False\n sage: G._coerce_map_from_(F)\n True\n sage: F._coerce_map_from_(H)\n True\n sage: F._coerce_map_from_(QQ)\n False\n sage: G._coerce_map_from_(QQ)\n False\n sage: F.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n "
if isinstance(R, FreeDendriformAlgebra):
if all(((x in self.variable_names()) for x in R.variable_names())):
if self.base_ring().has_coerce_map_from(R.base_ring()):
return True
return False
def construction(self):
"\n Return a pair ``(F, R)``, where ``F`` is a :class:`DendriformFunctor`\n and `R` is a ring, such that ``F(R)`` returns ``self``.\n\n EXAMPLES::\n\n sage: P = algebras.FreeDendriform(ZZ, 'x,y')\n sage: x,y = P.gens()\n sage: F, R = P.construction()\n sage: F\n Dendriform[x,y]\n sage: R\n Integer Ring\n sage: F(ZZ) is P\n True\n sage: F(QQ)\n Free Dendriform algebra on 2 generators ['x', 'y'] over Rational Field\n "
return (DendriformFunctor(self.variable_names()), self.base_ring())
|
class DendriformFunctor(ConstructionFunctor):
"\n A constructor for dendriform algebras.\n\n EXAMPLES::\n\n sage: P = algebras.FreeDendriform(ZZ, 'x,y')\n sage: x,y = P.gens()\n sage: F = P.construction()[0]; F\n Dendriform[x,y]\n\n sage: A = GF(5)['a,b']\n sage: a, b = A.gens()\n sage: F(A)\n Free Dendriform algebra on 2 generators ['x', 'y']\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n\n sage: f = A.hom([a+b,a-b],A)\n sage: F(f)\n Generic endomorphism of Free Dendriform algebra on 2 generators ['x', 'y']\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n\n sage: F(f)(a * F(A)(x))\n (a+b)*B[x[., .]]\n "
rank = 9
def __init__(self, vars):
"\n EXAMPLES::\n\n sage: F = sage.combinat.free_dendriform_algebra.DendriformFunctor(['x','y'])\n sage: F\n Dendriform[x,y]\n sage: F(ZZ)\n Free Dendriform algebra on 2 generators ['x', 'y'] over Integer Ring\n "
Functor.__init__(self, Rings(), Rings())
self.vars = vars
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n EXAMPLES::\n\n sage: R = algebras.FreeDendriform(ZZ, 'x,y,z')\n sage: F = R.construction()[0]; F\n Dendriform[x,y,z]\n sage: type(F)\n <class 'sage.combinat.free_dendriform_algebra.DendriformFunctor'>\n sage: F(ZZ) # indirect doctest\n Free Dendriform algebra on 3 generators ['x', 'y', 'z'] over Integer Ring\n "
return FreeDendriformAlgebra(R, self.vars)
def _apply_functor_to_morphism(self, f):
"\n Apply the functor ``self`` to the ring morphism `f`.\n\n TESTS::\n\n sage: R = algebras.FreeDendriform(ZZ, 'x').construction()[0]\n sage: R(ZZ.hom(GF(3))) # indirect doctest\n Generic morphism:\n From: Free Dendriform algebra on one generator ['x'] over Integer Ring\n To: Free Dendriform algebra on one generator ['x'] over Finite Field of size 3\n "
dom = self(f.domain())
codom = self(f.codomain())
def action(x):
return codom._from_dict({a: f(b) for (a, b) in x.monomial_coefficients().items()})
return dom.module_morphism(function=action, codomain=codom)
def __eq__(self, other):
"\n EXAMPLES::\n\n sage: F = algebras.FreeDendriform(ZZ, 'x,y,z').construction()[0]\n sage: G = algebras.FreeDendriform(QQ, 'x,y,z').construction()[0]\n sage: F == G\n True\n sage: G == loads(dumps(G))\n True\n sage: G = algebras.FreeDendriform(QQ, 'x,y').construction()[0]\n sage: F == G\n False\n "
if (not isinstance(other, DendriformFunctor)):
return False
return (self.vars == other.vars)
def __ne__(self, other):
"\n EXAMPLES::\n\n sage: F = algebras.FreeDendriform(ZZ, 'x,y,z').construction()[0]\n sage: G = algebras.FreeDendriform(QQ, 'x,y,z').construction()[0]\n sage: F != G\n False\n sage: G != loads(dumps(G))\n False\n sage: G = algebras.FreeDendriform(QQ, 'x,y').construction()[0]\n sage: F != G\n True\n "
return (not (self == other))
def __mul__(self, other):
"\n If two Dendriform functors are given in a row, form a single Dendriform functor\n with all of the variables.\n\n EXAMPLES::\n\n sage: F = sage.combinat.free_dendriform_algebra.DendriformFunctor(['x','y'])\n sage: G = sage.combinat.free_dendriform_algebra.DendriformFunctor(['t'])\n sage: G * F\n Dendriform[x,y,t]\n "
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, DendriformFunctor):
if set(self.vars).intersection(other.vars):
raise CoercionException(('Overlapping variables (%s,%s)' % (self.vars, other.vars)))
return DendriformFunctor((other.vars + self.vars))
elif (isinstance(other, CompositeConstructionFunctor) and isinstance(other.all[(- 1)], DendriformFunctor)):
return CompositeConstructionFunctor(other.all[:(- 1)], (self * other.all[(- 1)]))
else:
return CompositeConstructionFunctor(other, self)
def merge(self, other):
"\n Merge ``self`` with another construction functor, or return ``None``.\n\n EXAMPLES::\n\n sage: F = sage.combinat.free_dendriform_algebra.DendriformFunctor(['x','y'])\n sage: G = sage.combinat.free_dendriform_algebra.DendriformFunctor(['t'])\n sage: F.merge(G)\n Dendriform[x,y,t]\n sage: F.merge(F)\n Dendriform[x,y]\n\n Now some actual use cases::\n\n sage: R = algebras.FreeDendriform(ZZ, 'x,y,z')\n sage: x,y,z = R.gens()\n sage: 1/2 * x\n 1/2*B[x[., .]]\n sage: parent(1/2 * x)\n Free Dendriform algebra on 3 generators ['x', 'y', 'z'] over Rational Field\n\n sage: S = algebras.FreeDendriform(QQ, 'zt')\n sage: z,t = S.gens()\n sage: x + t\n B[t[., .]] + B[x[., .]]\n sage: parent(x + t)\n Free Dendriform algebra on 4 generators ['z', 't', 'x', 'y'] over Rational Field\n "
if isinstance(other, DendriformFunctor):
if (self.vars == other.vars):
return self
ret = list(self.vars)
cur_vars = set(ret)
for v in other.vars:
if (v not in cur_vars):
ret.append(v)
return DendriformFunctor(Alphabet(ret))
else:
return None
def _repr_(self):
"\n TESTS::\n\n sage: algebras.FreeDendriform(QQ,'x,y,z,t').construction()[0]\n Dendriform[x,y,z,t]\n "
return ('Dendriform[%s]' % ','.join(self.vars))
|
class CombinatorialFreeModule(UniqueRepresentation, Module, IndexedGenerators):
'\n Class for free modules with a named basis\n\n INPUT:\n\n - ``R`` - base ring\n\n - ``basis_keys`` - list, tuple, family, set, etc. defining the\n indexing set for the basis of this module\n\n - ``element_class`` - the class of which elements of this module\n should be instances (optional, default None, in which case the\n elements are instances of\n :class:`~sage.modules.with_basis.indexed_element.IndexedFreeModuleElement`)\n\n - ``category`` - the category in which this module lies (optional,\n default None, in which case use the "category of modules with\n basis" over the base ring ``R``); this should be a subcategory\n of :class:`ModulesWithBasis`\n\n For the options controlling the printing of elements, see\n :class:`~sage.structure.indexed_generators.IndexedGenerators`.\n\n .. NOTE::\n\n These print options may also be accessed and modified using the\n :meth:`print_options` method, after the module has been defined.\n\n EXAMPLES:\n\n We construct a free module whose basis is indexed by the letters a, b, c::\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\',\'c\'])\n sage: F\n Free module generated by {\'a\', \'b\', \'c\'} over Rational Field\n\n Its basis is a family, indexed by a, b, c::\n\n sage: e = F.basis()\n sage: e\n Finite family {\'a\': B[\'a\'], \'b\': B[\'b\'], \'c\': B[\'c\']}\n\n ::\n\n sage: [x for x in e]\n [B[\'a\'], B[\'b\'], B[\'c\']]\n sage: [k for k in e.keys()]\n [\'a\', \'b\', \'c\']\n\n Let us construct some elements, and compute with them::\n\n sage: e[\'a\']\n B[\'a\']\n sage: 2*e[\'a\']\n 2*B[\'a\']\n sage: e[\'a\'] + 3*e[\'b\']\n B[\'a\'] + 3*B[\'b\']\n\n Some uses of\n :meth:`sage.categories.commutative_additive_semigroups.CommutativeAdditiveSemigroups.ParentMethods.summation`\n and :meth:`sum`::\n\n sage: F = CombinatorialFreeModule(QQ, [1,2,3,4])\n sage: F.summation(F.monomial(1), F.monomial(3))\n B[1] + B[3]\n\n sage: F = CombinatorialFreeModule(QQ, [1,2,3,4])\n sage: F.sum(F.monomial(i) for i in [1,2,3])\n B[1] + B[2] + B[3]\n\n Note that free modules with a given basis and parameters are unique::\n\n sage: F1 = CombinatorialFreeModule(QQ, (1,2,3,4))\n sage: F1 is F\n True\n\n The identity of the constructed free module depends on the order of the\n basis and on the other parameters, like the prefix. Note that :class:`CombinatorialFreeModule` is\n a :class:`~sage.structure.unique_representation.UniqueRepresentation`. Hence,\n two combinatorial free modules evaluate equal if and only if they are\n identical::\n\n sage: F1 = CombinatorialFreeModule(QQ, (1,2,3,4))\n sage: F1 is F\n True\n sage: F1 = CombinatorialFreeModule(QQ, [4,3,2,1])\n sage: F1 == F\n False\n sage: F2 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix=\'F\')\n sage: F2 == F\n False\n\n Because of this, if you create a free module with certain parameters and\n then modify its prefix or other print options, this affects all modules\n which were defined using the same parameters.\n ::\n\n sage: F2.print_options(prefix=\'x\')\n sage: F2.prefix()\n \'x\'\n sage: F3 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix=\'F\')\n sage: F3 is F2 # F3 was defined just like F2\n True\n sage: F3.prefix()\n \'x\'\n sage: F4 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix=\'F\', bracket=True)\n sage: F4 == F2 # F4 was NOT defined just like F2\n False\n sage: F4.prefix()\n \'F\'\n\n sage: F2.print_options(prefix=\'F\') #reset for following doctests\n\n The constructed module is in the category of modules with basis\n over the base ring::\n\n sage: CombinatorialFreeModule(QQ, Partitions()).category() # needs sage.combinat\n Category of vector spaces with basis over Rational Field\n\n If furthermore the index set is finite (i.e. in the category\n ``Sets().Finite()``), then the module is declared as being finite\n dimensional::\n\n sage: CombinatorialFreeModule(QQ, [1,2,3,4]).category()\n Category of finite dimensional vector spaces with basis over Rational Field\n sage: CombinatorialFreeModule(QQ, Partitions(3), # needs sage.combinat\n ....: category=Algebras(QQ).WithBasis()).category()\n Category of finite dimensional algebras with basis over Rational Field\n\n See :mod:`sage.categories.examples.algebras_with_basis` and\n :mod:`sage.categories.examples.hopf_algebras_with_basis` for\n illustrations of the use of the ``category`` keyword, and see\n :class:`sage.combinat.root_system.weight_space.WeightSpace` for an\n example of the use of ``element_class``.\n\n Customizing print and LaTeX representations of elements::\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\'], prefix=\'x\')\n sage: original_print_options = F.print_options()\n sage: sorted(original_print_options.items())\n [(\'bracket\', None),\n (\'iterate_key\', False),\n (\'latex_bracket\', False), (\'latex_names\', None),\n (\'latex_prefix\', None), (\'latex_scalar_mult\', None),\n (\'names\', None), (\'prefix\', \'x\'),\n (\'scalar_mult\', \'*\'),\n (\'sorting_key\', <function ...<lambda> at ...>),\n (\'sorting_reverse\', False), (\'string_quotes\', True),\n (\'tensor_symbol\', None)]\n\n sage: e = F.basis()\n sage: e[\'a\'] - 3 * e[\'b\']\n x[\'a\'] - 3*x[\'b\']\n\n sage: F.print_options(prefix=\'x\', scalar_mult=\' \', bracket=\'{\')\n sage: e[\'a\'] - 3 * e[\'b\']\n x{\'a\'} - 3 x{\'b\'}\n sage: latex(e[\'a\'] - 3 * e[\'b\'])\n x_{a} - 3 x_{b}\n\n sage: F.print_options(latex_prefix=\'y\')\n sage: latex(e[\'a\'] - 3 * e[\'b\'])\n y_{a} - 3 y_{b}\n\n sage: F.print_options(sorting_reverse=True)\n sage: e[\'a\'] - 3 * e[\'b\']\n -3 x{\'b\'} + x{\'a\'}\n sage: F.print_options(**original_print_options) # reset print options\n\n sage: F = CombinatorialFreeModule(QQ, [(1,2), (3,4)])\n sage: e = F.basis()\n sage: e[(1,2)] - 3 * e[(3,4)]\n B[(1, 2)] - 3*B[(3, 4)]\n\n sage: F.print_options(bracket=[\'_{\', \'}\'])\n sage: e[(1,2)] - 3 * e[(3,4)]\n B_{(1, 2)} - 3*B_{(3, 4)}\n\n sage: F.print_options(prefix=\'\', bracket=False)\n sage: e[(1,2)] - 3 * e[(3,4)]\n (1, 2) - 3*(3, 4)\n\n TESTS:\n\n Before :trac:`14054`, combinatorial free modules violated the unique\n parent condition. That caused a problem. The tensor product construction\n involves maps, but maps check that their domain and the parent of a\n to-be-mapped element are identical (not just equal). However, the tensor\n product was cached by a :class:`~sage.misc.cachefunc.cached_method`, which\n involves comparison by equality (not identity). Hence, the last line of\n the following example used to fail with an assertion error::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix="F")\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix="G")\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: tensor([f, g])\n 2*F[1] # G[3] + F[1] # G[4] + 4*F[2] # G[3] + 2*F[2] # G[4]\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix=\'x\')\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix=\'y\')\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: tensor([f, g])\n 2*x[1] # y[3] + x[1] # y[4] + 4*x[2] # y[3] + 2*x[2] # y[4]\n\n We check that we can use the shorthand ``C.<a,b,...> = ...``::\n\n sage: C.<x,y,z> = CombinatorialFreeModule(QQ)\n sage: C\n Free module generated by {\'x\', \'y\', \'z\'} over Rational Field\n sage: a = x - y + 4*z; a\n x - y + 4*z\n sage: a.parent() is C\n True\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: XQ = SchubertPolynomialRing(QQ)\n sage: XZ = SchubertPolynomialRing(ZZ)\n sage: XQ == XZ\n False\n sage: XQ == XQ\n True\n\n We check that issue :trac:`28681` is fixed::\n\n sage: F = CombinatorialFreeModule(ZZ, ZZ); F.rename("F")\n sage: FF = tensor((F,F))\n sage: cartesian_product((FF,FF))\n F # F (+) F # F\n '
@staticmethod
def __classcall_private__(cls, base_ring, basis_keys=None, category=None, prefix=None, names=None, **keywords):
"\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: G = CombinatorialFreeModule(QQ, ('a','b','c'))\n sage: F is G\n True\n\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'], latex_bracket=['LEFT', 'RIGHT'])\n sage: F.print_options()['latex_bracket']\n ('LEFT', 'RIGHT')\n\n sage: F is G\n False\n\n We check that the category is properly straightened::\n\n sage: F = CombinatorialFreeModule(QQ, ['a','b'])\n sage: F1 = CombinatorialFreeModule(QQ, ['a','b'], category=ModulesWithBasis(QQ))\n sage: F2 = CombinatorialFreeModule(QQ, ['a','b'], category=[ModulesWithBasis(QQ)])\n sage: F3 = CombinatorialFreeModule(QQ, ['a','b'], category=(ModulesWithBasis(QQ),))\n sage: F4 = CombinatorialFreeModule(QQ, ['a','b'], category=(ModulesWithBasis(QQ),CommutativeAdditiveSemigroups()))\n sage: F5 = CombinatorialFreeModule(QQ, ['a','b'], category=(ModulesWithBasis(QQ),Category.join((LeftModules(QQ), RightModules(QQ)))))\n sage: F6 = CombinatorialFreeModule(QQ, ['a','b'], category=ModulesWithBasis(QQ).FiniteDimensional())\n sage: F1 is F, F2 is F, F3 is F, F4 is F, F5 is F, F6 is F\n (True, True, True, True, True, True)\n\n sage: G = CombinatorialFreeModule(QQ, ['a','b'], category=AlgebrasWithBasis(QQ))\n sage: F is G\n False\n "
if isinstance(basis_keys, range):
basis_keys = tuple(basis_keys)
if isinstance(basis_keys, (list, tuple)):
basis_keys = FiniteEnumeratedSet(basis_keys)
category = ModulesWithBasis(base_ring).or_subcategory(category)
if (basis_keys in Sets().Finite()):
category = category.FiniteDimensional()
bracket = keywords.get('bracket', None)
if isinstance(bracket, list):
keywords['bracket'] = tuple(bracket)
latex_bracket = keywords.get('latex_bracket', None)
if isinstance(latex_bracket, list):
keywords['latex_bracket'] = tuple(latex_bracket)
(names, basis_keys, prefix) = parse_indices_names(names, basis_keys, prefix, keywords)
if (prefix is None):
prefix = 'B'
if (keywords.get('latex_names', None) is not None):
latex_names = keywords['latex_names']
if isinstance(latex_names, str):
latex_names = latex_names.split(',')
latex_names = tuple(latex_names)
keywords['latex_names'] = latex_names
return super().__classcall__(cls, base_ring, basis_keys, category=category, prefix=prefix, names=names, **keywords)
Element = IndexedFreeModuleElement
@lazy_attribute
def element_class(self):
"\n The (default) class for the elements of this parent\n\n Overrides :meth:`Parent.element_class` to force the\n construction of Python class. This is currently needed to\n inherit really all the features from categories, and in\n particular the initialization of ``_mul_`` in\n :meth:`Magmas.ParentMethods.__init_extra__`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: A = Algebras(QQ).WithBasis().example(); A\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: A.element_class.mro()\n [<class 'sage.categories.examples.algebras_with_basis.FreeAlgebra_with_category.element_class'>,\n <class 'sage.modules.with_basis.indexed_element.IndexedFreeModuleElement'>,\n ...]\n sage: a,b,c = A.algebra_generators()\n sage: a * b\n B[word: ab]\n\n TESTS::\n\n sage: A.__class__.element_class.__module__ # needs sage.combinat\n 'sage.combinat.free_module'\n "
return self.__make_element_class__(self.Element, name=('%s.element_class' % self.__class__.__name__), module=self.__class__.__module__, inherit=True)
def __init__(self, R, basis_keys=None, element_class=None, category=None, prefix=None, names=None, **kwds):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\',\'c\'])\n\n sage: F.category()\n Category of finite dimensional vector spaces with basis over Rational Field\n\n One may specify the category this module belongs to::\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\',\'c\'], category=AlgebrasWithBasis(QQ))\n sage: F.category()\n Category of finite dimensional algebras with basis over Rational Field\n\n sage: F = CombinatorialFreeModule(GF(3), [\'a\',\'b\',\'c\'], # needs sage.rings.finite_rings\n ....: category=(Modules(GF(3)).WithBasis(), Semigroups()))\n sage: F.category() # needs sage.rings.finite_rings\n Join of Category of finite semigroups\n and Category of finite dimensional vector spaces with basis over Finite Field of size 3\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\',\'c\'], category=FiniteDimensionalModulesWithBasis(QQ))\n sage: F.basis()\n Finite family {\'a\': B[\'a\'], \'b\': B[\'b\'], \'c\': B[\'c\']}\n sage: F.category()\n Category of finite dimensional vector spaces with basis over Rational Field\n\n sage: TestSuite(F).run()\n\n TESTS:\n\n Regression test for :trac:`10127`: ``self._indices`` needs to be\n set early enough, in case the initialization of the categories\n use ``self.basis().keys()``. This occurred on several occasions\n in non trivial constructions. In the following example,\n :class:`AlgebrasWithBasis` constructs ``Homset(self,self)`` to\n extend by bilinearity method ``product_on_basis``, which in\n turn triggers ``self._repr_()``::\n\n sage: class MyAlgebra(CombinatorialFreeModule):\n ....: def _repr_(self):\n ....: return "MyAlgebra on %s" % (self.basis().keys())\n ....: def product_on_basis(self, i, j):\n ....: pass\n sage: MyAlgebra(ZZ, ZZ, category=AlgebrasWithBasis(QQ))\n MyAlgebra on Integer Ring\n\n A simpler example would be welcome!\n\n We check that unknown options are caught::\n\n sage: CombinatorialFreeModule(ZZ, [1,2,3], keyy=2)\n Traceback (most recent call last):\n ...\n ValueError: keyy is not a valid print option.\n '
from sage.categories.rings import Rings
if (R not in Rings()):
raise TypeError('argument R must be a ring')
if (element_class is not None):
self.Element = element_class
basis_keys = Sets()(basis_keys, enumerated_set=True)
(names, basis_keys, prefix) = parse_indices_names(names, basis_keys, prefix, kwds)
if (prefix is None):
prefix = 'B'
kwds.pop('key', None)
if ('monomial_key' in kwds):
kwds['sorting_key'] = kwds.pop('monomial_key')
if ('monomial_reverse' in kwds):
kwds['sorting_reverse'] = kwds.pop('monomial_reverse')
IndexedGenerators.__init__(self, basis_keys, prefix, names=names, **kwds)
if (category is None):
category = ModulesWithBasis(R)
elif isinstance(category, tuple):
category = Category.join(category)
if (basis_keys in Sets().Finite()):
category = category.FiniteDimensional()
Parent.__init__(self, base=R, category=category, names=names)
self._order = None
def construction(self):
"\n The construction functor and base ring for self.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'], category=AlgebrasWithBasis(QQ))\n sage: F.construction()\n (VectorFunctor, Rational Field)\n "
c = super().construction()
if (c is not None):
return c
if (self.__class__.__base__ != CombinatorialFreeModule):
return None
from sage.categories.pushout import VectorFunctor
return (VectorFunctor(None, True, None, with_basis='standard', basis_keys=self.basis().keys()), self.base_ring())
def change_ring(self, R):
"\n Return the base change of ``self`` to `R`.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, ['a','b','c']); F\n Free module generated by {'a', 'b', 'c'} over Integer Ring\n sage: F_QQ = F.change_ring(QQ); F_QQ\n Free module generated by {'a', 'b', 'c'} over Rational Field\n sage: F_QQ.change_ring(ZZ) == F\n True\n "
if (R is self.base_ring()):
return self
construction = self.construction()
if (construction is not None):
(functor, _) = construction
from sage.categories.pushout import VectorFunctor
if isinstance(functor, VectorFunctor):
return functor(R)
raise NotImplementedError('the method change_ring() has not yet been implemented')
_repr_term = IndexedGenerators._repr_generator
_latex_term = IndexedGenerators._latex_generator
def _ascii_art_term(self, m):
'\n Return an ascii art representation of the term indexed by ``m``.\n\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R() # needs sage.combinat\n sage: ascii_art(R.one()) # indirect doctest # needs sage.combinat\n 1\n '
try:
if (m == self.one_basis()):
return AsciiArt(['1'])
except Exception:
pass
return IndexedGenerators._ascii_art_generator(self, m)
def _unicode_art_term(self, m):
'\n Return an unicode art representation of the term indexed by ``m``.\n\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R() # needs sage.combinat\n sage: unicode_art(R.one()) # indirect doctest # needs sage.combinat\n 1\n '
try:
if (m == self.one_basis()):
return UnicodeArt(['1'])
except Exception:
pass
return IndexedGenerators._unicode_art_generator(self, m)
@lazy_attribute
def _element_class(self):
"\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: F._element_class\n <class 'sage.combinat.free_module.CombinatorialFreeModule_with_category.element_class'>\n "
return self.element_class
def _an_element_(self):
'\n EXAMPLES::\n\n sage: CombinatorialFreeModule(QQ, ("a", "b", "c")).an_element()\n 2*B[\'a\'] + 2*B[\'b\'] + 3*B[\'c\']\n sage: CombinatorialFreeModule(QQ, ("a", "b", "c"))._an_element_()\n 2*B[\'a\'] + 2*B[\'b\'] + 3*B[\'c\']\n sage: CombinatorialFreeModule(QQ, ()).an_element()\n 0\n sage: CombinatorialFreeModule(QQ, ZZ).an_element()\n 3*B[-1] + B[0] + 3*B[1]\n sage: CombinatorialFreeModule(QQ, RR).an_element()\n B[1.00000000000000]\n '
x = self.zero()
I = self.basis().keys()
R = self.base_ring()
try:
x = (x + self.monomial(I.an_element()))
except Exception:
pass
try:
g = iter(self.basis().keys())
for c in range(1, 4):
x = (x + self.term(next(g), R(c)))
except Exception:
pass
return x
def __contains__(self, x):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ,["a", "b"])\n sage: G = CombinatorialFreeModule(ZZ,["a", "b"])\n sage: F.monomial("a") in F\n True\n sage: G.monomial("a") in F\n False\n sage: "a" in F\n False\n sage: 5/3 in F\n False\n '
return (parent(x) == self)
def _element_constructor_(self, x):
'\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ["a", "b"])\n sage: F(F.monomial("a")) # indirect doctest\n B[\'a\']\n\n Do not rely on the following feature which may be removed in the future::\n\n sage: QS3 = SymmetricGroupAlgebra(QQ,3) # needs sage.combinat\n sage: QS3([2,3,1]) # indirect doctest # needs sage.combinat\n [2, 3, 1]\n\n instead, use::\n\n sage: P = QS3.basis().keys() # needs sage.combinat\n sage: QS3.monomial(P([2,3,1])) # indirect doctest # needs sage.combinat\n [2, 3, 1]\n\n or::\n\n sage: B = QS3.basis() # needs sage.combinat\n sage: B[P([2,3,1])] # needs sage.combinat\n [2, 3, 1]\n\n TODO: The symmetric group algebra (and in general,\n combinatorial free modules on word-like object could instead\n provide an appropriate short-hand syntax QS3[2,3,1]).\n\n Rationale: this conversion is ambiguous in situations like::\n\n sage: F = CombinatorialFreeModule(QQ,[0,1])\n\n Is ``0`` the zero of the base ring, or the index of a basis\n element? I.e. should the result be ``0`` or ``B[0]``?\n\n sage: F = CombinatorialFreeModule(QQ,[0,1])\n sage: F(0) # this feature may eventually disappear\n 0\n sage: F(1)\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= 1) an element of Free module generated by ... over Rational Field\n\n It is preferable not to rely either on the above, and instead, use::\n\n sage: F.zero()\n 0\n\n Note that, on the other hand, conversions from the ground ring\n are systematically defined (and mathematically meaningful) for\n algebras.\n\n A coercion between free modules with the same indices exists\n whenever a coercion map is defined between their base rings::\n\n sage: F = CombinatorialFreeModule(ZZ, ["a", "b"]); F.rename("F")\n sage: G = CombinatorialFreeModule(QQ, ["a", "b"]); G.rename("G")\n sage: G(F.monomial("a"))\n B[\'a\']\n sage: G(-3*F.monomial("a"))\n -3*B[\'a\']\n\n Otherwise, there is no conversion between distinct free modules::\n\n sage: H = CombinatorialFreeModule(ZZ, ["a", "b", "c"]); H.rename("H")\n sage: H(F.monomial("a"))\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= B[\'a\']) an element of self (=H)\n\n Here is a real life example illustrating that this yielded\n mathematically wrong results::\n\n sage: # needs sage.combinat\n sage: S = SymmetricFunctions(QQ)\n sage: s = S.s(); p = S.p()\n sage: ss = tensor([s,s]); pp = tensor([p,p])\n sage: a = tensor((s[2],s[2]))\n\n The following originally used to yield ``p[[2]] # p[[2]]``, and if\n there was no natural coercion between ``s`` and ``p``, this would\n raise a :class:`NotImplementedError`.\n Since :trac:`15305`, this takes the\n coercion between ``s`` and ``p`` and lifts it to the tensor product. ::\n\n sage: pp(a) # needs sage.combinat\n 1/4*p[1, 1] # p[1, 1] + 1/4*p[1, 1] # p[2] + 1/4*p[2] # p[1, 1] + 1/4*p[2] # p[2]\n\n General extensions of the ground ring should probably be reintroduced\n at some point, but via coercions, and with stronger sanity\n checks (ensuring that the codomain is really obtained by\n extending the scalar of the domain; checking that they share\n the same class is not sufficient).\n\n\n TESTS:\n\n Conversion from the ground ring is implemented for algebras::\n\n sage: QS3 = SymmetricGroupAlgebra(QQ,3) # needs sage.combinat\n sage: QS3(2) # needs sage.combinat\n 2*[1, 2, 3]\n '
R = self.base_ring()
if isinstance(x, int):
x = Integer(x)
if (x in R):
if (x == 0):
return self.zero()
else:
raise TypeError(('do not know how to make x (= %s) an element of %s' % (x, self)))
elif ((hasattr(self._indices, 'element_class') and isinstance(self._indices.element_class, type) and isinstance(x, self._indices.element_class)) or (parent(x) == self._indices)):
return self.monomial(x)
elif (x in self._indices):
return self.monomial(self._indices(x))
else:
if hasattr(self, '_coerce_end'):
try:
return self._coerce_end(x)
except TypeError:
pass
raise TypeError(('do not know how to make x (= %s) an element of self (=%s)' % (x, self)))
def _convert_map_from_(self, S):
'\n Implement the conversion from formal sums.\n\n EXAMPLES::\n\n sage: E = CombinatorialFreeModule(QQ, ["a", "b", "c"])\n sage: f = FormalSum([[2, "a"], [3, "b"]]); f\n 2*a + 3*b\n sage: E._convert_map_from_(f.parent())\n Generic morphism:\n From: Abelian Group of all Formal Finite Sums over Integer Ring\n To: Free module generated by {\'a\', \'b\', \'c\'} over Rational Field\n sage: E(f)\n 2*B[\'a\'] + 3*B[\'b\']\n\n sage: E._convert_map_from_(ZZ)\n '
from sage.structure.formal_sum import FormalSums
K = self.base_ring()
if (isinstance(S, FormalSums) and K.has_coerce_map_from(S.base_ring())):
G = self.basis().keys()
return SetMorphism(S.Hom(self, category=(self.category() | S.category())), (lambda x: self.sum_of_terms(((G(g), K(c)) for (c, g) in x))))
def _first_ngens(self, n):
'\n Used by the preparser for ``F.<x> = ...``.\n\n EXAMPLES::\n\n sage: C = CombinatorialFreeModule(QQ, ZZ)\n sage: C._first_ngens(3)\n (B[0], B[1], B[-1])\n\n sage: R.<x,y> = FreeAlgebra(QQ, 2) # needs sage.combinat\n sage: x,y # needs sage.combinat\n (x, y)\n '
try:
return tuple(self.gens())[:n]
except (AttributeError, ValueError, TypeError):
pass
B = self.basis()
it = iter(self._indices)
return tuple((B[next(it)] for i in range(n)))
def _coerce_map_from_(self, R):
'\n Return ``True`` if there is a coercion map from ``R`` into ``self``.\n\n There exists a coercion map from:\n\n - a free module whose base ring coerces into the base ring of\n ``self``, and which has the same indices as ``self``\n\n EXAMPLES::\n\n sage: C = CombinatorialFreeModule(ZZ, Set([1,2]))\n sage: CQ = CombinatorialFreeModule(QQ, Set([1,2]))\n sage: CQ.has_coerce_map_from(C)\n True\n sage: c = C.monomial(2)\n sage: cq = CQ(c); cq\n B[2]\n sage: cq.leading_coefficient().parent()\n Rational Field\n sage: C.has_coerce_map_from(CQ)\n False\n\n sage: # needs sage.rings.finite_rings\n sage: CF2 = CombinatorialFreeModule(GF(2), Set([1,2]))\n sage: CF2.has_coerce_map_from(C)\n True\n sage: c = C.monomial(1)\n sage: CF2(2*c)\n 0\n sage: CF2(3*c)\n B[1]\n '
if isinstance(R, CombinatorialFreeModule):
try:
CR = R.base_extend(self.base_ring())
except (NotImplementedError, TypeError):
pass
else:
if (CR == self):
return (lambda parent, x: self._from_dict(x._monomial_coefficients, coerce=True, remove_zeros=True))
return super()._coerce_map_from_(R)
def dimension(self):
"\n Return the dimension of the free module (which is given\n by the number of elements in the basis).\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F.dimension()\n 3\n sage: F.basis().cardinality()\n 3\n sage: F.basis().keys().cardinality()\n 3\n\n Rank is available as a synonym::\n\n sage: F.rank()\n 3\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat\n sage: s.dimension() # needs sage.combinat\n +Infinity\n "
return self._indices.cardinality()
rank = dimension
def is_exact(self):
'\n Return ``True`` if elements of ``self`` have exact representations,\n which is true of ``self`` if and only if it is true of\n ``self.basis().keys()`` and ``self.base_ring()``.\n\n EXAMPLES::\n\n sage: GroupAlgebra(GL(3, GF(7))).is_exact() # needs sage.groups sage.rings.finite_rings\n True\n sage: GroupAlgebra(GL(3, GF(7)), RR).is_exact() # needs sage.groups sage.rings.finite_rings\n False\n sage: GroupAlgebra(GL(3, pAdicRing(7))).is_exact() # not implemented, needs sage.groups sage.rings.padics\n False\n '
try:
if (not self.basis().keys().is_exact()):
return False
except AttributeError:
pass
return self.base_ring().is_exact()
def set_order(self, order):
"\n Set the order of the elements of the basis.\n\n If :meth:`set_order` has not been called, then the ordering is\n the one used in the generation of the elements of self's\n associated enumerated set.\n\n .. WARNING::\n\n Many cached methods depend on this order, in\n particular for constructing subspaces and quotients.\n Changing the order after some computations have been\n cached does not invalidate the cache, and is likely to\n introduce inconsistencies.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: QS2 = SymmetricGroupAlgebra(QQ,2)\n sage: b = list(QS2.basis().keys())\n sage: b.reverse()\n sage: QS2.set_order(b)\n sage: QS2.get_order()\n [[2, 1], [1, 2]]\n "
self._order = order
from sage.combinat.ranker import rank_from_list
self._rank_basis = rank_from_list(self._order)
@cached_method
def get_order(self):
'\n Return the order of the elements in the basis.\n\n EXAMPLES::\n\n sage: QS2 = SymmetricGroupAlgebra(QQ,2) # needs sage.combinat\n sage: QS2.get_order() # note: order changed on 2009-03-13 # needs sage.combinat\n [[2, 1], [1, 2]]\n '
if (self._order is None):
self.set_order(self.basis().keys().list())
return self._order
def get_order_key(self):
"\n Return a comparison key on the basis indices that is\n compatible with the current term order.\n\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()\n sage: A.set_order(['x', 'y', 'a', 'b'])\n sage: Akey = A.get_order_key()\n sage: sorted(A.basis().keys(), key=Akey)\n ['x', 'y', 'a', 'b']\n sage: A.set_order(list(reversed(A.basis().keys())))\n sage: Akey = A.get_order_key()\n sage: sorted(A.basis().keys(), key=Akey)\n ['b', 'a', 'y', 'x']\n "
self.get_order()
return self._order_key
def _order_key(self, x):
"\n Return a key for `x` compatible with the term order.\n\n INPUT:\n\n - ``x`` -- indices of the basis of ``self``\n\n EXAMPLES::\n\n sage: A = CombinatorialFreeModule(QQ, ['x','y','a','b'])\n sage: A.set_order(['x', 'y', 'a', 'b'])\n sage: A._order_key('x')\n 0\n sage: A._order_key('y')\n 1\n sage: A._order_key('a')\n 2\n "
return self._rank_basis(x)
def from_vector(self, vector, order=None, coerce=True):
'\n Build an element of ``self`` from a (sparse) vector.\n\n .. SEEALSO:: :meth:`get_order`, :meth:`CombinatorialFreeModule.Element._vector_`\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: QS3 = SymmetricGroupAlgebra(QQ, 3)\n sage: b = QS3.from_vector(vector((2, 0, 0, 0, 0, 4))); b\n 2*[1, 2, 3] + 4*[3, 2, 1]\n sage: a = 2*QS3([1,2,3]) + 4*QS3([3,2,1])\n sage: a == b\n True\n '
if (order is None):
order = self.get_order()
if ((not coerce) or (vector.base_ring() is self.base_ring())):
return self._from_dict({order[i]: c for (i, c) in vector.items()}, coerce=False)
R = self.base_ring()
return self._from_dict({order[i]: R(c) for (i, c) in vector.items() if R(c)}, coerce=False, remove_zeros=False)
def sum(self, iter_of_elements):
'\n Return the sum of all elements in ``iter_of_elements``.\n\n Overrides method inherited from commutative additive monoid as it\n is much faster on dicts directly.\n\n INPUT:\n\n - ``iter_of_elements`` -- iterator of elements of ``self``\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ,[1,2])\n sage: f = F.an_element(); f\n 2*B[1] + 2*B[2]\n sage: F.sum( f for _ in range(5) )\n 10*B[1] + 10*B[2]\n '
D = blas.sum((element._monomial_coefficients for element in iter_of_elements))
return self._from_dict(D, remove_zeros=False)
def linear_combination(self, iter_of_elements_coeff, factor_on_left=True):
'\n Return the linear combination `\\lambda_1 v_1 + \\cdots +\n \\lambda_k v_k` (resp. the linear combination `v_1 \\lambda_1 +\n \\cdots + v_k \\lambda_k`) where ``iter_of_elements_coeff`` iterates\n through the sequence `((v_1, \\lambda_1), ..., (v_k, \\lambda_k))`.\n\n INPUT:\n\n - ``iter_of_elements_coeff`` -- iterator of pairs ``(element, coeff)``\n with ``element`` in ``self`` and ``coeff`` in ``self.base_ring()``\n\n - ``factor_on_left`` -- (optional) if ``True``, the coefficients are\n multiplied from the left if ``False``, the coefficients are\n multiplied from the right\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, [1,2])\n sage: f = F.an_element(); f\n 2*B[1] + 2*B[2]\n sage: F.linear_combination( (f,i) for i in range(5) )\n 20*B[1] + 20*B[2]\n '
return self._from_dict(blas.linear_combination(((element._monomial_coefficients, coeff) for (element, coeff) in iter_of_elements_coeff), factor_on_left=factor_on_left), remove_zeros=False)
def term(self, index, coeff=None):
"\n Construct a term in ``self``.\n\n INPUT:\n\n - ``index`` -- the index of a basis element\n - ``coeff`` -- an element of the coefficient ring (default: one)\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F.term('a',3)\n 3*B['a']\n sage: F.term('a')\n B['a']\n\n Design: should this do coercion on the coefficient ring?\n "
if (coeff is None):
coeff = self.base_ring().one()
return self._from_dict({index: coeff})
def _monomial(self, index):
"\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F._monomial('a')\n B['a']\n "
return self._from_dict({index: self.base_ring().one()}, remove_zeros=False)
@lazy_attribute
def monomial(self):
"\n Return the basis element indexed by ``i``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F.monomial('a')\n B['a']\n\n ``F.monomial`` is in fact (almost) a map::\n\n sage: F.monomial\n Term map from {'a', 'b', 'c'} to Free module generated by {'a', 'b', 'c'} over Rational Field\n "
from sage.categories.poor_man_map import PoorManMap
return PoorManMap(self._monomial, domain=self._indices, codomain=self, name='Term map')
def _sum_of_monomials(self, indices):
"\n TESTS::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F._sum_of_monomials(['a', 'b', 'b'])\n B['a'] + 2*B['b']\n sage: F = CombinatorialFreeModule(GF(3), ['a', 'b', 'c']) # needs sage.rings.finite_rings\n sage: F._sum_of_monomials(['a', 'b', 'b', 'b']) # needs sage.rings.finite_rings\n B['a']\n "
R = self.base_ring()
ret = blas.sum_of_monomials(indices, R.one())
return self.element_class(self, ret)
def sum_of_terms(self, terms, distinct=False):
"\n Construct a sum of terms of ``self``.\n\n INPUT:\n\n - ``terms`` -- a list (or iterable) of pairs ``(index, coeff)``\n - ``distinct`` -- (default: ``False``) whether the indices are\n guaranteed to be distinct\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F.sum_of_terms([('a',2), ('c',3)])\n 2*B['a'] + 3*B['c']\n\n If ``distinct`` is True, then the construction is optimized::\n\n sage: F.sum_of_terms([('a',2), ('c',3)], distinct = True)\n 2*B['a'] + 3*B['c']\n\n .. WARNING::\n\n Use ``distinct=True`` only if you are sure that the\n indices are indeed distinct::\n\n sage: F.sum_of_terms([('a',2), ('a',3)], distinct = True)\n 3*B['a']\n\n Extreme case::\n\n sage: F.sum_of_terms([])\n 0\n "
if distinct:
return self._from_dict(dict(terms))
return self._from_dict(blas.sum_of_terms(terms), remove_zeros=False)
@cached_method
def zero(self):
"\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])\n sage: F.zero()\n 0\n "
return self._from_dict({}, remove_zeros=False)
def _from_dict(self, d, coerce=False, remove_zeros=True):
'\n Construct an element of ``self`` from an ``{index: coefficient}``\n dictionary.\n\n INPUT:\n\n - ``d`` -- a dictionary ``{index: coeff}`` where each ``index`` is\n the index of a basis element and each ``coeff`` belongs to the\n coefficient ring ``self.base_ring()``\n\n - ``coerce`` -- a boolean (default: ``False``), whether to coerce\n the coefficients ``coeff`` to the coefficient ring\n\n - ``remove_zeros`` -- a boolean (default: ``True``), if some\n coefficients ``coeff`` may be zero and should therefore be removed\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: e = SymmetricFunctions(QQ).elementary()\n sage: s = SymmetricFunctions(QQ).schur()\n sage: a = e([2,1]) + e([1,1,1]); a\n e[1, 1, 1] + e[2, 1]\n sage: s._from_dict(a.monomial_coefficients())\n s[1, 1, 1] + s[2, 1]\n\n If the optional argument ``coerce`` is ``True``, then the\n coefficients are coerced into the base ring of ``self``::\n\n sage: # needs sage.combinat\n sage: part = Partition([2,1])\n sage: d = {part: 1}\n sage: a = s._from_dict(d, coerce=True); a\n s[2, 1]\n sage: a.coefficient(part).parent()\n Rational Field\n\n With ``remove_zeros=True``, zero coefficients are removed::\n\n sage: s._from_dict({part: 0}) # needs sage.combinat\n 0\n\n .. WARNING::\n\n With ``remove_zeros=True``, it is assumed that no\n coefficient of the dictionary is zero. Otherwise, this may\n lead to illegal results::\n\n sage: list(s._from_dict({part: 0}, remove_zeros=False)) # needs sage.combinat\n [([2, 1], 0)]\n '
assert isinstance(d, dict)
if coerce:
R = self.base_ring()
d = {key: R(coeff) for (key, coeff) in d.items()}
if remove_zeros:
d = {key: coeff for (key, coeff) in d.items() if coeff}
return self.element_class(self, d)
|
class CombinatorialFreeModule_Tensor(CombinatorialFreeModule):
'\n Tensor Product of Free Modules\n\n EXAMPLES:\n\n We construct two free modules, assign them short names, and construct their tensor product::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [3,4]); G.rename("G")\n sage: T = tensor([F, G]); T\n F # G\n\n sage: T.category()\n Category of tensor products of\n finite dimensional modules with basis over Integer Ring\n\n sage: T.construction() # todo: not implemented\n [tensor, ]\n\n T is a free module, with same base ring as F and G::\n\n sage: T.base_ring()\n Integer Ring\n\n The basis of T is indexed by tuples of basis indices of F and G::\n\n sage: T.basis().keys()\n Image of Cartesian product of {1, 2}, {3, 4}\n by The map <class \'tuple\'> from Cartesian product of {1, 2}, {3, 4}\n sage: T.basis().keys().list()\n [(1, 3), (1, 4), (2, 3), (2, 4)]\n\n FIXME: Should elements of a CartesianProduct be tuples (making them hashable)?\n\n Here are the basis elements themselves::\n\n sage: T.basis().cardinality()\n 4\n sage: list(T.basis())\n [B[1] # B[3], B[1] # B[4], B[2] # B[3], B[2] # B[4]]\n\n The tensor product is associative and flattens sub tensor products::\n\n sage: H = CombinatorialFreeModule(ZZ, [5,6]); H.rename("H")\n sage: tensor([F, tensor([G, H])])\n F # G # H\n sage: tensor([tensor([F, G]), H])\n F # G # H\n sage: tensor([F, G, H])\n F # G # H\n\n We now compute the tensor product of elements of free modules::\n\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: h = H.monomial(5) + H.monomial(6)\n sage: tensor([f, g])\n 2*B[1] # B[3] + B[1] # B[4] + 4*B[2] # B[3] + 2*B[2] # B[4]\n\n Again, the tensor product is associative on elements::\n\n sage: tensor([f, tensor([g, h])]) == tensor([f, g, h])\n True\n sage: tensor([tensor([f, g]), h]) == tensor([f, g, h])\n True\n\n Note further that the tensor product spaces need not preexist::\n\n sage: t = tensor([f, g, h])\n sage: t.parent()\n F # G # H\n\n\n TESTS::\n\n sage: tensor([tensor([F, G]), H]) == tensor([F, G, H])\n True\n sage: tensor([F, tensor([G, H])]) == tensor([F, G, H])\n True\n '
@staticmethod
def __classcall_private__(cls, modules, **options):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2])\n sage: G = CombinatorialFreeModule(ZZ, [3,4])\n sage: H = CombinatorialFreeModule(ZZ, [4])\n sage: tensor([tensor([F, G]), H]) == tensor([F, G, H])\n True\n sage: tensor([F, tensor([G, H])]) == tensor([F, G, H])\n True\n\n Check that :trac:`19608` is fixed::\n\n sage: T = tensor([F, G, H])\n sage: T in Modules(ZZ).FiniteDimensional()\n True\n '
assert (len(modules) > 0)
R = modules[0].base_ring()
assert (all((module in ModulesWithBasis(R))) for module in modules)
modules = sum([(module._sets if isinstance(module, CombinatorialFreeModule_Tensor) else (module,)) for module in modules], ())
if all((('FiniteDimensional' in M.category().axioms()) for M in modules)):
options['category'] = options['category'].FiniteDimensional()
return super(CombinatorialFreeModule.Tensor, cls).__classcall__(cls, modules, **options)
def __init__(self, modules, **options):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2]); F\n F\n '
self._sets = modules
indices = CartesianProduct_iters(*[module.basis().keys() for module in modules]).map(tuple)
CombinatorialFreeModule.__init__(self, modules[0].base_ring(), indices, **options)
if ('tensor_symbol' in options):
self._print_options['tensor_symbol'] = options['tensor_symbol']
def _repr_(self):
'\n This is customizable by setting\n ``self.print_options(\'tensor_symbol\'=...)``.\n\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3])\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,8])\n sage: F.rename("F")\n sage: G.rename("G")\n sage: T = tensor([F, G])\n sage: T # indirect doctest\n F # G\n sage: T.print_options(tensor_symbol=\' @ \') # note the spaces\n sage: T # indirect doctest\n F @ G\n\n To avoid a side\\--effect on another doctest, we revert the change::\n\n sage: T.print_options(tensor_symbol=\' # \')\n '
from sage.categories.tensor import tensor
if hasattr(self, '_print_options'):
symb = self._print_options['tensor_symbol']
if (symb is None):
symb = tensor.symbol
else:
symb = tensor.symbol
return symb.join((('%s' % module) for module in self._sets))
def tensor_factors(self):
'\n Return the tensor factors of this tensor product.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2])\n sage: F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [3,4])\n sage: G.rename("G")\n sage: T = tensor([F, G]); T\n F # G\n sage: T.tensor_factors()\n (F, G)\n '
return self._sets
def _ascii_art_(self, term):
'\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R() # needs sage.combinat\n sage: Partitions.options(diagram_str="#", convention="french") # needs sage.combinat\n sage: s = ascii_art(tensor((R[1,2], R[3,1,2]))); s # needs sage.combinat\n R # R\n # ###\n ## #\n ##\n\n Check that the breakpoints are correct (:trac:`29202`)::\n\n sage: s._breakpoints # needs sage.combinat\n [6]\n '
if hasattr(self, '_print_options'):
symb = self._print_options['tensor_symbol']
if (symb is None):
symb = tensor.symbol
else:
symb = tensor.symbol
return ascii_art(*(module._ascii_art_term(t) for (module, t) in zip(self._sets, term)), sep=AsciiArt([symb], breakpoints=[len(symb)]))
_ascii_art_term = _ascii_art_
def _unicode_art_(self, term):
'\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R() # needs sage.combinat\n sage: Partitions.options(diagram_str="#", convention="french") # needs sage.combinat\n sage: s = unicode_art(tensor((R[1,2], R[3,1,2]))); s # needs sage.combinat\n R ⊗ R\n ┌┐ ┌┬┬┐\n ├┼┐ └┴┼┤\n └┴┘ ├┼┐\n └┴┘\n\n Check that the breakpoints are correct (:trac:`29202`)::\n\n sage: s._breakpoints # needs sage.combinat\n [7]\n '
if hasattr(self, '_print_options'):
symb = self._print_options['tensor_symbol']
if (symb is None):
symb = tensor.unicode_symbol
else:
symb = tensor.unicode_symbol
return unicode_art(*(module._unicode_art_term(t) for (module, t) in zip(self._sets, term)), sep=UnicodeArt([symb], breakpoints=[len(symb)]))
_unicode_art_term = _unicode_art_
def _latex_(self):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3])\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,8])\n sage: F.rename("F")\n sage: G.rename("G")\n sage: latex(tensor([F, F, G])) # indirect doctest\n \\text{\\texttt{F}} \\otimes \\text{\\texttt{F}} \\otimes \\text{\\texttt{G}}\n sage: F._latex_ = lambda : "F"\n sage: G._latex_ = lambda : "G"\n sage: latex(tensor([F, F, G])) # indirect doctest\n F \\otimes F \\otimes G\n '
from sage.misc.latex import latex
symb = ' \\otimes '
return symb.join((('%s' % latex(module)) for module in self._sets))
def _repr_term(self, term):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix="F")\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix="G")\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: tensor([f, g]) # indirect doctest\n 2*F[1] # G[3] + F[1] # G[4] + 4*F[2] # G[3] + 2*F[2] # G[4]\n '
if hasattr(self, '_print_options'):
symb = self._print_options['tensor_symbol']
if (symb is None):
symb = tensor.symbol
else:
symb = tensor.symbol
return symb.join((module._repr_term(t) for (module, t) in zip(self._sets, term)))
def _latex_term(self, term):
"\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix='x')\n sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix='y')\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: latex(tensor([f, g])) # indirect doctest\n 2 x_{1} \\otimes y_{3} + x_{1} \\otimes y_{4} + 4 x_{2} \\otimes y_{3} + 2 x_{2} \\otimes y_{4}\n "
symb = ' \\otimes '
return symb.join((module._latex_term(t) for (module, t) in zip(self._sets, term)))
@cached_method
def tensor_constructor(self, modules):
'\n INPUT:\n\n - ``modules`` -- a tuple `(F_1,\\dots,F_n)` of\n free modules whose tensor product is self\n\n Returns the canonical multilinear morphism from\n `F_1 \\times \\dots \\times F_n` to `F_1 \\otimes \\dots \\otimes F_n`\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [3,4]); G.rename("G")\n sage: H = CombinatorialFreeModule(ZZ, [5,6]); H.rename("H")\n\n sage: f = F.monomial(1) + 2*F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: h = H.monomial(5) + H.monomial(6)\n sage: FG = tensor([F, G])\n sage: phi_fg = FG.tensor_constructor((F, G))\n sage: phi_fg(f, g)\n 2*B[1] # B[3] + B[1] # B[4] + 4*B[2] # B[3] + 2*B[2] # B[4]\n\n sage: FGH = tensor([F, G, H])\n sage: phi_fgh = FGH.tensor_constructor((F, G, H))\n sage: phi_fgh(f, g, h)\n 2*B[1] # B[3] # B[5] + 2*B[1] # B[3] # B[6] + B[1] # B[4] # B[5]\n + B[1] # B[4] # B[6] + 4*B[2] # B[3] # B[5] + 4*B[2] # B[3] # B[6]\n + 2*B[2] # B[4] # B[5] + 2*B[2] # B[4] # B[6]\n\n sage: phi_fg_h = FGH.tensor_constructor((FG, H))\n sage: phi_fg_h(phi_fg(f, g), h)\n 2*B[1] # B[3] # B[5] + 2*B[1] # B[3] # B[6] + B[1] # B[4] # B[5]\n + B[1] # B[4] # B[6] + 4*B[2] # B[3] # B[5] + 4*B[2] # B[3] # B[6]\n + 2*B[2] # B[4] # B[5] + 2*B[2] # B[4] # B[6]\n '
assert ((module in ModulesWithBasis(self.base_ring())) for module in modules)
assert (tensor(modules) == self)
is_tensor = [isinstance(module, CombinatorialFreeModule_Tensor) for module in modules]
result = (self.monomial * CartesianProductWithFlattening(is_tensor))
for i in range(len(modules)):
result = modules[i]._module_morphism(result, position=i, codomain=self)
return result
def _tensor_of_elements(self, elements):
'\n Returns the tensor product of the specified elements.\n The result should be in ``self``.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [1,2]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [3,4]); G.rename("G")\n sage: H = CombinatorialFreeModule(ZZ, [5,6]); H.rename("H")\n\n sage: f = F.monomial(1) + 2 * F.monomial(2)\n sage: g = 2*G.monomial(3) + G.monomial(4)\n sage: h = H.monomial(5) + H.monomial(6)\n\n sage: GH = tensor([G, H])\n sage: gh = GH._tensor_of_elements([g, h]); gh\n 2*B[3] # B[5] + 2*B[3] # B[6] + B[4] # B[5] + B[4] # B[6]\n\n sage: FGH = tensor([F, G, H])\n sage: FGH._tensor_of_elements([f, g, h])\n 2*B[1] # B[3] # B[5] + 2*B[1] # B[3] # B[6] + B[1] # B[4] # B[5] + B[1] # B[4] # B[6] + 4*B[2] # B[3] # B[5] + 4*B[2] # B[3] # B[6] + 2*B[2] # B[4] # B[5] + 2*B[2] # B[4] # B[6]\n\n sage: FGH._tensor_of_elements([f, gh])\n 2*B[1] # B[3] # B[5] + 2*B[1] # B[3] # B[6] + B[1] # B[4] # B[5] + B[1] # B[4] # B[6] + 4*B[2] # B[3] # B[5] + 4*B[2] # B[3] # B[6] + 2*B[2] # B[4] # B[5] + 2*B[2] # B[4] # B[6]\n '
return self.tensor_constructor(tuple((element.parent() for element in elements)))(*elements)
def _coerce_map_from_(self, R):
'\n Return ``True`` if there is a coercion from ``R`` into ``self`` and\n ``False`` otherwise. The things that coerce into ``self`` are:\n\n - Anything with a coercion into ``self.base_ring()``.\n\n - A tensor algebra whose factors have a coercion into the\n corresponding factors of ``self``.\n\n TESTS::\n\n sage: C = CombinatorialFreeModule(ZZ, ZZ)\n sage: C2 = CombinatorialFreeModule(ZZ, NN)\n sage: M = C.module_morphism(lambda x: C2.monomial(abs(x)), codomain=C2)\n sage: M.register_as_coercion()\n sage: C2(C.basis()[3])\n B[3]\n sage: C2(C.basis()[3] + C.basis()[-3])\n 2*B[3]\n sage: S = C.tensor(C)\n sage: S2 = C2.tensor(C2)\n sage: S2.has_coerce_map_from(S)\n True\n sage: S.has_coerce_map_from(S2)\n False\n sage: S.an_element()\n 3*B[0] # B[-1] + 2*B[0] # B[0] + 2*B[0] # B[1]\n sage: S2(S.an_element())\n 2*B[0] # B[0] + 5*B[0] # B[1]\n\n ::\n\n sage: C = CombinatorialFreeModule(ZZ, Set([1,2]))\n sage: D = CombinatorialFreeModule(ZZ, Set([2,4]))\n sage: f = C.module_morphism(on_basis=lambda x: D.monomial(2*x), codomain=D)\n sage: f.register_as_coercion()\n sage: T = tensor((C,C))\n sage: p = D.an_element()\n sage: T(tensor((p,p)))\n Traceback (most recent call last):\n ...\n NotImplementedError\n sage: T = tensor((D,D))\n sage: p = C.an_element()\n sage: T(tensor((p,p)))\n 4*B[2] # B[2] + 4*B[2] # B[4] + 4*B[4] # B[2] + 4*B[4] # B[4]\n '
if (((R in ModulesWithBasis(self.base_ring()).TensorProducts()) or (R in GradedAlgebrasWithBasis(self.base_ring()).SignedTensorProducts())) and isinstance(R, CombinatorialFreeModule_Tensor) and (len(R._sets) == len(self._sets)) and all((self._sets[i].has_coerce_map_from(M) for (i, M) in enumerate(R._sets)))):
modules = R._sets
vector_map = [self._sets[i]._internal_coerce_map_from(M) for (i, M) in enumerate(modules)]
return R.module_morphism((lambda x: self._tensor_of_elements([vector_map[i](M.monomial(x[i])) for (i, M) in enumerate(modules)])), codomain=self)
return super()._coerce_map_from_(R)
|
class CartesianProductWithFlattening():
'\n A class for Cartesian product constructor, with partial flattening\n '
def __init__(self, flatten):
'\n INPUT:\n\n - ``flatten`` -- a tuple of booleans\n\n This constructs a callable which accepts ``len(flatten)``\n arguments, and builds a tuple out them. When ``flatten[i]``,\n the i-th argument itself should be a tuple which is flattened\n in the result.\n\n sage: from sage.combinat.free_module import CartesianProductWithFlattening\n sage: CartesianProductWithFlattening([True, False, True, True])\n <sage.combinat.free_module.CartesianProductWithFlattening object at ...>\n\n '
self._flatten = flatten
def __call__(self, *indices):
'\n EXAMPLES::\n\n sage: from sage.combinat.free_module import CartesianProductWithFlattening\n sage: cp = CartesianProductWithFlattening([True, False, True, True])\n sage: cp((1,2), (3,4), (5,6), (7,8))\n (1, 2, (3, 4), 5, 6, 7, 8)\n sage: cp((1,2,3), 4, (5,6), (7,8))\n (1, 2, 3, 4, 5, 6, 7, 8)\n\n '
return sum(((i if flatten else (i,)) for (i, flatten) in zip(indices, self._flatten)), ())
|
class CombinatorialFreeModule_CartesianProduct(CombinatorialFreeModule):
'\n An implementation of Cartesian products of modules with basis\n\n EXAMPLES:\n\n We construct two free modules, assign them short names, and construct their Cartesian product::\n\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: H = CombinatorialFreeModule(ZZ, [4,7]); H.rename("H")\n sage: S = cartesian_product([F, G])\n sage: S\n F (+) G\n sage: S.basis()\n Lazy family (Term map\n from Disjoint union of Family ({4, 5}, {4, 6})\n to F (+) G(i))_{i in Disjoint union of Family ({4, 5}, {4, 6})}\n\n Note that the indices of the basis elements of F and G intersect non\n trivially. This is handled by forcing the union to be disjoint::\n\n sage: list(S.basis())\n [B[(0, 4)], B[(0, 5)], B[(1, 4)], B[(1, 6)]]\n\n We now compute the Cartesian product of elements of free modules::\n\n sage: f = F.monomial(4) + 2*F.monomial(5)\n sage: g = 2*G.monomial(4) + G.monomial(6)\n sage: h = H.monomial(4) + H.monomial(7)\n sage: cartesian_product([f, g])\n B[(0, 4)] + 2*B[(0, 5)] + 2*B[(1, 4)] + B[(1, 6)]\n sage: cartesian_product([f, g, h])\n B[(0, 4)] + 2*B[(0, 5)] + 2*B[(1, 4)] + B[(1, 6)] + B[(2, 4)] + B[(2, 7)]\n sage: cartesian_product([f, g, h]).parent()\n F (+) G (+) H\n\n TODO: choose an appropriate semantic for Cartesian products of Cartesian products (associativity?)::\n\n sage: S = cartesian_product([cartesian_product([F, G]), H]) # todo: not implemented\n F (+) G (+) H\n '
def __init__(self, modules, **options):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [2,4,5])\n sage: G = CombinatorialFreeModule(ZZ, [2,4,7])\n sage: C = cartesian_product([F, G]) ; C\n Free module generated by {2, 4, 5} over Integer Ring (+) Free module generated by {2, 4, 7} over Integer Ring\n sage: TestSuite(C).run()\n '
assert len(modules)
R = modules[0].base_ring()
assert (all((module in ModulesWithBasis(R))) for module in modules)
self._sets = modules
CombinatorialFreeModule.__init__(self, R, DisjointUnionEnumeratedSets([module.basis().keys() for module in modules], keepkey=True), **options)
def _sets_keys(self):
'\n In waiting for self._sets.keys()\n\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [2,4,5])\n sage: G = CombinatorialFreeModule(ZZ, [2,4,7])\n sage: CP = cartesian_product([F, G])\n sage: CP._sets_keys()\n [0, 1]\n '
return list(range(len(self._sets)))
def _repr_(self):
'\n TESTS::\n\n sage: F = CombinatorialFreeModule(ZZ, [2,4,5])\n sage: CP = cartesian_product([F, F]); CP # indirect doctest\n Free module generated by {2, 4, 5} over Integer Ring (+) Free module generated by {2, 4, 5} over Integer Ring\n sage: F.rename("F"); CP\n F (+) F\n '
from sage.categories.cartesian_product import cartesian_product
return cartesian_product.symbol.join((('%s' % module) for module in self._sets))
@cached_method
def cartesian_embedding(self, i):
'\n Return the natural embedding morphism of the ``i``-th\n Cartesian factor (summand) of ``self`` into ``self``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: S = cartesian_product([F, G])\n sage: phi = S.cartesian_embedding(0)\n sage: phi(F.monomial(4) + 2 * F.monomial(5))\n B[(0, 4)] + 2*B[(0, 5)]\n sage: phi(F.monomial(4) + 2 * F.monomial(6)).parent() == S\n True\n\n TESTS::\n\n sage: phi(G.monomial(4))\n Traceback (most recent call last):\n ...\n AssertionError\n '
assert (i in self._sets_keys())
return self._sets[i]._module_morphism((lambda t: self.monomial((i, t))), codomain=self)
summand_embedding = cartesian_embedding
@cached_method
def cartesian_projection(self, i):
'\n Return the natural projection onto the `i`-th Cartesian factor\n (summand) of ``self``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: S = cartesian_product([F, G])\n sage: x = S.monomial((0,4)) + 2 * S.monomial((0,5)) + 3 * S.monomial((1,6))\n sage: S.cartesian_projection(0)(x)\n B[4] + 2*B[5]\n sage: S.cartesian_projection(1)(x)\n 3*B[6]\n sage: S.cartesian_projection(0)(x).parent() == F\n True\n sage: S.cartesian_projection(1)(x).parent() == G\n True\n '
assert (i in self._sets_keys())
module = self._sets[i]
return self._module_morphism((lambda j_t: (module.monomial(j_t[1]) if (i == j_t[0]) else module.zero())), codomain=module)
summand_projection = cartesian_projection
def _cartesian_product_of_elements(self, elements):
'\n Return the Cartesian product of the elements.\n\n INPUT:\n\n - ``elements`` -- an iterable (e.g. tuple, list) with one element of\n each Cartesian factor of ``self``\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: S = cartesian_product([F, G])\n sage: f = F.monomial(4) + 2*F.monomial(5)\n sage: g = 2*G.monomial(4) + G.monomial(6)\n sage: S._cartesian_product_of_elements([f, g])\n B[(0, 4)] + 2*B[(0, 5)] + 2*B[(1, 4)] + B[(1, 6)]\n sage: S._cartesian_product_of_elements([f, g]).parent() == S\n True\n\n TESTS:\n\n The ``elements`` can be a generator as in :trac:`31453`::\n\n sage: from sage.categories.magmatic_algebras import (\n ....: MagmaticAlgebras)\n sage: class TrivialCFM(CombinatorialFreeModule):\n ....: def __init__(self):\n ....: c = MagmaticAlgebras(QQ).WithBasis().Unital()\n ....: super().__init__(QQ,[1],category=c)\n ....: def one(self):\n ....: return self.monomial(0)\n sage: c1 = TrivialCFM()\n sage: c1.one()\n B[0]\n sage: CP = cartesian_product([c1,c1])\n sage: CP.one()\n B[(0, 0)] + B[(1, 0)]\n '
return self.sum((self.summand_embedding(i)(element_i) for (i, element_i) in zip(self._sets_keys(), elements)))
def cartesian_factors(self):
'\n Return the factors of the Cartesian product.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: S = cartesian_product([F, G])\n sage: S.cartesian_factors()\n (F, G)\n '
return self._sets
class Element(CombinatorialFreeModule.Element):
pass
|
class FreePreLieAlgebra(CombinatorialFreeModule):
'\n The free pre-Lie algebra.\n\n Pre-Lie algebras are non-associative algebras, where the product `*`\n satisfies\n\n .. MATH::\n\n (x * y) * z - x * (y * z) = (x * z) * y - x * (z * y).\n\n We use here the convention where the associator\n\n .. MATH::\n\n (x, y, z) := (x * y) * z - x * (y * z)\n\n is symmetric in its two rightmost arguments. This is sometimes called\n a right pre-Lie algebra.\n\n They have appeared in numerical analysis and deformation theory.\n\n The free Pre-Lie algebra on a given set `E` has an explicit\n description using rooted trees, just as the free associative algebra\n can be described using words. The underlying vector space has a basis\n indexed by finite rooted trees endowed with a map from their vertices\n to `E`. In this basis, the product of two (decorated) rooted trees `S\n * T` is the sum over vertices of `S` of the rooted tree obtained by\n adding one edge from the root of `T` to the given vertex of `S`. The\n root of these trees is taken to be the root of `S`. The free pre-Lie\n algebra can also be considered as the free algebra over the PreLie operad.\n\n .. WARNING::\n\n The usual binary operator ``*`` can be used for the pre-Lie product.\n Beware that it but must be parenthesized properly, as the pre-Lie\n product is not associative. By default, a multiple product will be\n taken with left parentheses.\n\n EXAMPLES::\n\n sage: F = algebras.FreePreLie(ZZ, \'xyz\')\n sage: x,y,z = F.gens()\n sage: (x * y) * z\n B[x[y[z[]]]] + B[x[y[], z[]]]\n sage: (x * y) * z - x * (y * z) == (x * z) * y - x * (z * y)\n True\n\n The free pre-Lie algebra is non-associative::\n\n sage: x * (y * z) == (x * y) * z\n False\n\n The default product is with left parentheses::\n\n sage: x * y * z == (x * y) * z\n True\n sage: x * y * z * x == ((x * y) * z) * x\n True\n\n The NAP product as defined in [Liv2006]_ is also implemented on the same\n vector space::\n\n sage: N = F.nap_product\n sage: N(x*y,z*z)\n B[x[y[], z[z[]]]]\n\n When ``None`` is given as input, unlabelled trees are used instead::\n\n sage: F1 = algebras.FreePreLie(QQ, None)\n sage: w = F1.gen(0); w\n B[[]]\n sage: w * w * w * w\n B[[[[[]]]]] + B[[[[], []]]] + 3*B[[[], [[]]]] + B[[[], [], []]]\n\n However, it is equally possible to use labelled trees instead::\n\n sage: F1 = algebras.FreePreLie(QQ, \'q\')\n sage: w = F1.gen(0); w\n B[q[]]\n sage: w * w * w * w\n B[q[q[q[q[]]]]] + B[q[q[q[], q[]]]] + 3*B[q[q[], q[q[]]]] + B[q[q[], q[], q[]]]\n\n The set `E` can be infinite::\n\n sage: F = algebras.FreePreLie(QQ, ZZ)\n sage: w = F.gen(1); w\n B[1[]]\n sage: x = F.gen(2); x\n B[-1[]]\n sage: y = F.gen(3); y\n B[2[]]\n sage: w*x\n B[1[-1[]]]\n sage: (w*x)*y\n B[1[-1[2[]]]] + B[1[-1[], 2[]]]\n sage: w*(x*y)\n B[1[-1[2[]]]]\n\n Elements of a free pre-Lie algebra can be lifted to the universal\n enveloping algebra of the associated Lie algebra. The universal\n enveloping algebra is the Grossman-Larson Hopf algebra::\n\n sage: F = algebras.FreePreLie(QQ,\'abc\')\n sage: a,b,c = F.gens()\n sage: (a*b+b*c).lift()\n B[#[a[b[]]]] + B[#[b[c[]]]]\n\n .. NOTE::\n\n Variables names can be ``None``, a list of strings, a string\n or an integer. When ``None`` is given, unlabelled rooted\n trees are used. When a single string is given, each letter is taken\n as a variable. See\n :func:`sage.combinat.words.alphabet.build_alphabet`.\n\n .. WARNING::\n\n Beware that the underlying combinatorial free module is based\n either on ``RootedTrees`` or on ``LabelledRootedTrees``, with no\n restriction on the labellings. This means that all code calling\n the :meth:`basis` method would not give meaningful results, since\n :meth:`basis` returns many "chaff" elements that do not belong to\n the algebra.\n\n REFERENCES:\n\n - [ChLi]_\n\n - [Liv2006]_\n '
@staticmethod
def __classcall_private__(cls, R, names=None):
"\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: F1 = algebras.FreePreLie(QQ, 'xyz')\n sage: F2 = algebras.FreePreLie(QQ, 'x,y,z')\n sage: F3 = algebras.FreePreLie(QQ, ['x','y','z'])\n sage: F4 = algebras.FreePreLie(QQ, Alphabet('xyz'))\n sage: F1 is F2 and F1 is F3 and F1 is F4\n True\n "
if (names is not None):
if (isinstance(names, str) and (',' in names)):
names = [u for u in names if (u != ',')]
names = Alphabet(names)
if (R not in Rings()):
raise TypeError('argument R must be a ring')
return super().__classcall__(cls, R, names)
def __init__(self, R, names=None):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: A = algebras.FreePreLie(QQ, '@'); A\n Free PreLie algebra on one generator ['@'] over Rational Field\n sage: TestSuite(A).run()\n\n sage: A = algebras.FreePreLie(QQ, None); A\n Free PreLie algebra on one generator ['o'] over Rational Field\n\n sage: F = algebras.FreePreLie(QQ, 'xy')\n sage: TestSuite(F).run() # long time\n "
if (names is None):
Trees = RootedTrees()
key = RootedTree.sort_key
self._alphabet = Alphabet(['o'])
else:
Trees = LabelledRootedTrees()
key = LabelledRootedTree.sort_key
self._alphabet = names
cat = (MagmaticAlgebras(R).WithBasis().Graded() & LieAlgebras(R).WithBasis().Graded())
CombinatorialFreeModule.__init__(self, R, Trees, latex_prefix='', sorting_key=key, category=cat)
def variable_names(self):
"\n Return the names of the variables.\n\n EXAMPLES::\n\n sage: R = algebras.FreePreLie(QQ, 'xy')\n sage: R.variable_names()\n {'x', 'y'}\n\n sage: R = algebras.FreePreLie(QQ, None)\n sage: R.variable_names()\n {'o'}\n "
return self._alphabet
def _repr_(self):
"\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.FreePreLie(QQ, '@') # indirect doctest\n Free PreLie algebra on one generator ['@'] over Rational Field\n\n sage: algebras.FreePreLie(QQ, ZZ) # indirect doctest\n Free PreLie algebra on generators indexed by Integer Ring\n over Rational Field\n\n sage: enum = EnumeratedSets().Infinite().example()\n sage: algebras.FreePreLie(QQ, enum) # indirect doctest\n Free PreLie algebra on generators indexed by An example of an\n infinite enumerated set: the non negative integers\n over Rational Field\n "
n = self.algebra_generators().cardinality()
finite = bool((n < Infinity))
if (not finite):
gen = 'generators indexed by'
elif (n == 1):
gen = 'one generator'
else:
gen = '{} generators'.format(n)
s = 'Free PreLie algebra on {} {} over {}'
if finite:
try:
return s.format(gen, self._alphabet.list(), self.base_ring())
except NotImplementedError:
return s.format(gen, self._alphabet, self.base_ring())
else:
return s.format(gen, self._alphabet, self.base_ring())
def gen(self, i):
"\n Return the ``i``-th generator of the algebra.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: F = algebras.FreePreLie(ZZ, 'xyz')\n sage: F.gen(0)\n B[x[]]\n\n sage: F.gen(4)\n Traceback (most recent call last):\n ...\n IndexError: argument i (= 4) must be between 0 and 2\n "
G = self.algebra_generators()
n = G.cardinality()
if ((i < 0) or (not (i < n))):
m = 'argument i (= {}) must be between 0 and {}'.format(i, (n - 1))
raise IndexError(m)
return G[G.keys().unrank(i)]
@cached_method
def algebra_generators(self):
"\n Return the generators of this algebra.\n\n These are the rooted trees with just one vertex.\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(ZZ, 'fgh'); A\n Free PreLie algebra on 3 generators ['f', 'g', 'h']\n over Integer Ring\n sage: list(A.algebra_generators())\n [B[f[]], B[g[]], B[h[]]]\n\n sage: A = algebras.FreePreLie(QQ, ['x1','x2'])\n sage: list(A.algebra_generators())\n [B[x1[]], B[x2[]]]\n "
Trees = self.basis().keys()
return Family(self._alphabet, (lambda a: self.monomial(Trees([], a))))
def change_ring(self, R):
"\n Return the free pre-Lie algebra in the same variables over `R`.\n\n INPUT:\n\n - `R` -- a ring\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(ZZ, 'fgh')\n sage: A.change_ring(QQ)\n Free PreLie algebra on 3 generators ['f', 'g', 'h'] over\n Rational Field\n "
return FreePreLieAlgebra(R, names=self.variable_names())
def gens(self):
"\n Return the generators of ``self`` (as an algebra).\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(ZZ, 'fgh')\n sage: A.gens()\n (B[f[]], B[g[]], B[h[]])\n "
return tuple(self.algebra_generators())
def degree_on_basis(self, t):
'\n Return the degree of a rooted tree in the free Pre-Lie algebra.\n\n This is the number of vertices.\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: A.degree_on_basis(RT([RT([])]))\n 2\n '
return t.node_number()
@cached_method
def an_element(self):
"\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, 'xy')\n sage: A.an_element()\n B[x[x[x[x[]]]]] + B[x[x[], x[x[]]]]\n "
o = self.gen(0)
return ((o * o) * (o * o))
def some_elements(self):
"\n Return some elements of the free pre-Lie algebra.\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: A.some_elements()\n [B[[]], B[[[]]], B[[[[[]]]]] + B[[[], [[]]]], B[[[[]]]] + B[[[], []]], B[[[]]]]\n\n With several generators::\n\n sage: A = algebras.FreePreLie(QQ, 'xy')\n sage: A.some_elements()\n [B[x[]],\n B[x[x[]]],\n B[x[x[x[x[]]]]] + B[x[x[], x[x[]]]],\n B[x[x[x[]]]] + B[x[x[], x[]]],\n B[x[x[y[]]]] + B[x[x[], y[]]]]\n "
o = self.gen(0)
x = (o * o)
y = o
G = self.algebra_generators()
if (G.cardinality() < 3):
for w in G:
y = (y * w)
else:
K = G.keys()
for i in range(3):
y = (y * G[K.unrank(i)])
return [o, x, (x * x), (x * o), y]
def product_on_basis(self, x, y):
'\n Return the pre-Lie product of two trees.\n\n This is the sum over all graftings of the root of `y` over a vertex\n of `x`. The root of the resulting trees is the root of `x`.\n\n .. SEEALSO::\n\n :meth:`pre_Lie_product`\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = RT([RT([])])\n sage: A.product_on_basis(x, x)\n B[[[[[]]]]] + B[[[], [[]]]]\n '
return self.sum((self.basis()[u] for u in x.graft_list(y)))
pre_Lie_product_on_basis = product_on_basis
@lazy_attribute
def pre_Lie_product(self):
'\n Return the pre-Lie product.\n\n .. SEEALSO::\n\n :meth:`pre_Lie_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = A(RT([RT([])]))\n sage: A.pre_Lie_product(x, x)\n B[[[[[]]]]] + B[[[], [[]]]]\n '
plb = self.pre_Lie_product_on_basis
return self._module_morphism(self._module_morphism(plb, position=0, codomain=self), position=1)
def bracket_on_basis(self, x, y):
'\n Return the Lie bracket of two trees.\n\n This is the commutator `[x, y] = x * y - y * x` of the pre-Lie product.\n\n .. SEEALSO::\n\n :meth:`pre_Lie_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = RT([RT([])])\n sage: y = RT([x])\n sage: A.bracket_on_basis(x, y)\n -B[[[[], [[]]]]] + B[[[], [[[]]]]] - B[[[[]], [[]]]]\n '
return (self.product_on_basis(x, y) - self.product_on_basis(y, x))
def nap_product_on_basis(self, x, y):
'\n Return the NAP product of two trees.\n\n This is the grafting of the root of `y` over the root\n of `x`. The root of the resulting tree is the root of `x`.\n\n .. SEEALSO::\n\n :meth:`nap_product`\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = RT([RT([])])\n sage: A.nap_product_on_basis(x, x)\n B[[[], [[]]]]\n '
return self.basis()[x.graft_on_root(y)]
@lazy_attribute
def nap_product(self):
'\n Return the NAP product.\n\n .. SEEALSO::\n\n :meth:`nap_product_on_basis`\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = A(RT([RT([])]))\n sage: A.nap_product(x, x)\n B[[[], [[]]]]\n '
npb = self.nap_product_on_basis
return self._module_morphism(self._module_morphism(npb, position=0, codomain=self), position=1)
def corolla(self, x, y, n, N):
"\n Return the corolla obtained with ``x`` as root and ``y`` as leaves.\n\n INPUT:\n\n - ``x``, ``y`` -- two elements\n - ``n`` -- integer; width of the corolla\n - ``N`` -- integer; truncation order (up to order ``N`` included)\n\n OUTPUT:\n\n the sum over all possible ways to graft ``n`` copies of ``y``\n on top of ``x`` (with at most ``N`` vertices in total)\n\n This operation can be defined by induction starting from the\n pre-Lie product.\n\n EXAMPLES::\n\n sage: A = algebras.FreePreLie(QQ)\n sage: a = A.gen(0)\n sage: b = A.corolla(a,a,1,4); b\n B[[[]]]\n sage: A.corolla(b,b,2,7)\n B[[[[[]], [[]]]]] + 2*B[[[[]], [[[]]]]] + B[[[], [[]], [[]]]]\n\n sage: A = algebras.FreePreLie(QQ, 'o')\n sage: a = A.gen(0)\n sage: b = A.corolla(a,a,1,4)\n\n sage: A = algebras.FreePreLie(QQ,'ab')\n sage: a, b = A.gens()\n sage: A.corolla(a,b,1,4)\n B[a[b[]]]\n sage: A.corolla(b,a,3,4)\n B[b[a[], a[], a[]]]\n\n sage: A.corolla(a+b,a+b,2,4)\n B[a[a[], a[]]] + 2*B[a[a[], b[]]] + B[a[b[], b[]]] + B[b[a[], a[]]] +\n 2*B[b[a[], b[]]] + B[b[b[], b[]]]\n\n TESTS::\n\n sage: A = algebras.FreePreLie(QQ,'ab')\n sage: a, b = A.gens()\n sage: A.corolla(a,A.zero(),2,2)\n 0\n "
if ((not x) or (not y)):
return self.zero()
basering = self.base_ring()
vx = x.valuation()
vy = y.valuation()
min_deg = ((vy * n) + vx)
if (min_deg > N):
return self.zero()
try:
self.gen(0).support()[0].label()
labels = True
except AttributeError:
labels = False
deg_x = x.maximal_degree()
deg_y = y.maximal_degree()
max_x = min(deg_x, (N - (n * vy)))
max_y = min(deg_y, ((N - vx) - ((n - 1) * vy)))
xx = x.truncate((max_x + 1))
yy = y.truncate((max_y + 1))
y_homog = {i: list(yy.homogeneous_component(i)) for i in range(vy, (max_y + 1))}
resu = self.zero()
for k in range(min_deg, (N + 1)):
for (mx, coef_x) in xx:
dx = mx.node_number()
step = self.zero()
for pi in IntegerVectors((k - dx), n, min_part=vy, max_part=max_y):
for ly in product(*[y_homog[part] for part in pi]):
coef_y = basering.prod((mc[1] for mc in ly))
arbres_y = [mc[0] for mc in ly]
step += (coef_y * self.sum((self(t) for t in corolla_gen(mx, arbres_y, labels))))
resu += (coef_x * step)
return resu
def group_product(self, x, y, n, N=10):
"\n Return the truncated group product of ``x`` and ``y``.\n\n This is a weighted sum of all corollas with up to ``n`` leaves, with\n ``x`` as root and ``y`` as leaves.\n\n The result is computed up to order ``N`` (included).\n\n When considered with infinitely many terms and infinite precision,\n this is an analogue of the Baker-Campbell-Hausdorff formula: it\n defines an associative product on the completed free pre-Lie algebra.\n\n INPUT:\n\n - ``x``, ``y`` -- two elements\n - ``n`` -- integer; the maximal width of corollas\n - ``N`` -- integer (default: 10); truncation order\n\n EXAMPLES:\n\n In the free pre-Lie algebra with one generator::\n\n sage: PL = algebras.FreePreLie(QQ)\n sage: a = PL.gen(0)\n sage: PL.group_product(a, a, 3, 3)\n B[[]] + B[[[]]] + 1/2*B[[[], []]]\n\n In the free pre-Lie algebra with several generators::\n\n sage: PL = algebras.FreePreLie(QQ,'@O')\n sage: a, b = PL.gens()\n sage: PL.group_product(a, b, 3, 3)\n B[@[]] + B[@[O[]]] + 1/2*B[@[O[], O[]]]\n sage: PL.group_product(a, b, 3, 10)\n B[@[]] + B[@[O[]]] + 1/2*B[@[O[], O[]]] + 1/6*B[@[O[], O[], O[]]]\n "
br = self.base_ring()
return (x + self.sum(((self.corolla(x, y, i, N) * (~ br(factorial(i)))) for i in range(1, (n + 1)))))
def _element_constructor_(self, x):
"\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.FreePreLie(QQ, 'xy')\n sage: x, y = R.gens()\n sage: R(x)\n B[x[]]\n sage: R(x+4*y)\n B[x[]] + 4*B[y[]]\n\n sage: Trees = R.basis().keys()\n sage: R(Trees([],'x'))\n B[x[]]\n sage: D = algebras.FreePreLie(ZZ, 'xy')\n sage: X, Y = D.gens()\n sage: R(X-Y).parent()\n Free PreLie algebra on 2 generators ['x', 'y'] over Rational Field\n\n TESTS::\n\n sage: R.<x,y> = algebras.FreePreLie(QQ)\n sage: S.<z> = algebras.FreePreLie(GF(3))\n sage: R(z)\n Traceback (most recent call last):\n ...\n TypeError: not able to convert this to this algebra\n "
if (isinstance(x, (RootedTree, LabelledRootedTree)) and (x in self.basis().keys())):
return self.monomial(x)
try:
P = x.parent()
if isinstance(P, FreePreLieAlgebra):
if (P is self):
return x
if self._coerce_map_from_(P):
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
raise TypeError('not able to convert this to this algebra')
else:
raise TypeError('not able to convert this to this algebra')
def _coerce_map_from_(self, R):
"\n Return ``True`` if there is a coercion from ``R`` into ``self``\n and ``False`` otherwise.\n\n The things that coerce into ``self`` are\n\n - free pre-Lie algebras whose set `E` of labels is\n a subset of the corresponding self of ``set`, and whose base\n ring has a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: F = algebras.FreePreLie(GF(7), 'xyz'); F\n Free PreLie algebra on 3 generators ['x', 'y', 'z']\n over Finite Field of size 7\n\n Elements of the free pre-Lie algebra canonically coerce in::\n\n sage: x, y, z = F.gens()\n sage: F.coerce(x+y) == x+y\n True\n\n The free pre-Lie algebra over `\\ZZ` on `x, y, z` coerces in, since\n `\\ZZ` coerces to `\\GF{7}`::\n\n sage: G = algebras.FreePreLie(ZZ, 'xyz')\n sage: Gx,Gy,Gz = G.gens()\n sage: z = F.coerce(Gx+Gy); z\n B[x[]] + B[y[]]\n sage: z.parent() is F\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so the free pre-Lie\n algebra over `\\GF{7}` does not coerce to the one over `\\ZZ`::\n\n sage: G.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Free PreLie algebra\n on 3 generators ['x', 'y', 'z'] over Finite Field of size\n 7 to Free PreLie algebra on 3 generators ['x', 'y', 'z']\n over Integer Ring\n\n TESTS::\n\n sage: F = algebras.FreePreLie(ZZ, 'xyz')\n sage: G = algebras.FreePreLie(QQ, 'xyz')\n sage: H = algebras.FreePreLie(ZZ, 'y')\n sage: F._coerce_map_from_(G)\n False\n sage: G._coerce_map_from_(F)\n True\n sage: F._coerce_map_from_(H)\n True\n sage: F._coerce_map_from_(QQ)\n False\n sage: G._coerce_map_from_(QQ)\n False\n sage: F.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n "
if isinstance(R, FreePreLieAlgebra):
if all(((x in self.variable_names()) for x in R.variable_names())):
if self.base_ring().has_coerce_map_from(R.base_ring()):
return True
return False
def _construct_UEA(self):
"\n Build the universal enveloping algebra.\n\n This is a Grossman-Larson Hopf algebra, based on forests of rooted\n trees.\n\n EXAMPLES::\n\n sage: S = algebras.FreePreLie(QQ, 'zt')\n sage: S._construct_UEA()\n Grossman-Larson Hopf algebra on 2 generators ['z', 't']\n over Rational Field\n "
return GrossmanLarsonAlgebra(self.base_ring(), self.variable_names())
def construction(self):
"\n Return a pair ``(F, R)``, where ``F`` is a :class:`PreLieFunctor`\n and `R` is a ring, such that ``F(R)`` returns ``self``.\n\n EXAMPLES::\n\n sage: P = algebras.FreePreLie(ZZ, 'x,y')\n sage: x,y = P.gens()\n sage: F, R = P.construction()\n sage: F\n PreLie[x,y]\n sage: R\n Integer Ring\n sage: F(ZZ) is P\n True\n sage: F(QQ)\n Free PreLie algebra on 2 generators ['x', 'y'] over Rational Field\n "
return (PreLieFunctor(self.variable_names()), self.base_ring())
class Element(CombinatorialFreeModule.Element):
def lift(self):
"\n Lift element to the Grossman-Larson algebra.\n\n EXAMPLES::\n\n sage: F = algebras.FreePreLie(QQ,'abc')\n sage: elt = F.an_element().lift(); elt\n B[#[a[a[a[a[]]]]]] + B[#[a[a[], a[a[]]]]]\n sage: parent(elt)\n Grossman-Larson Hopf algebra on 3 generators ['a', 'b', 'c']\n over Rational Field\n "
UEA = self.parent()._construct_UEA()
LRT = UEA.basis().keys()
data = {LRT([x], ROOT): cf for (x, cf) in self.monomial_coefficients(copy=False).items()}
return UEA.element_class(UEA, data)
def valuation(self):
"\n Return the valuation of ``self``.\n\n EXAMPLES::\n\n sage: a = algebras.FreePreLie(QQ).gen(0)\n sage: a.valuation()\n 1\n sage: (a*a).valuation()\n 2\n\n sage: a, b = algebras.FreePreLie(QQ,'ab').gens()\n sage: (a+b).valuation()\n 1\n sage: (a*b).valuation()\n 2\n sage: (a*b+a).valuation()\n 1\n\n TESTS::\n\n sage: z = algebras.FreePreLie(QQ).zero()\n sage: z.valuation()\n +Infinity\n "
if (self == self.parent().zero()):
return Infinity
i = 0
while True:
i += 1
if self.homogeneous_component(i):
return i
|
class PreLieFunctor(ConstructionFunctor):
"\n A constructor for pre-Lie algebras.\n\n EXAMPLES::\n\n sage: P = algebras.FreePreLie(ZZ, 'x,y')\n sage: x,y = P.gens()\n sage: F = P.construction()[0]; F\n PreLie[x,y]\n\n sage: A = GF(5)['a,b']\n sage: a, b = A.gens()\n sage: F(A)\n Free PreLie algebra on 2 generators ['x', 'y'] over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n\n sage: f = A.hom([a+b,a-b],A)\n sage: F(f)\n Generic endomorphism of Free PreLie algebra on 2 generators ['x', 'y']\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n\n sage: F(f)(a * F(A)(x))\n (a+b)*B[x[]]\n "
rank = 9
def __init__(self, vars):
"\n EXAMPLES::\n\n sage: F = sage.combinat.free_prelie_algebra.PreLieFunctor(['x','y'])\n sage: F\n PreLie[x,y]\n sage: F(ZZ)\n Free PreLie algebra on 2 generators ['x', 'y'] over Integer Ring\n "
Functor.__init__(self, Rings(), Magmas())
self.vars = vars
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n EXAMPLES::\n\n sage: R = algebras.FreePreLie(ZZ, 'x,y,z')\n sage: F = R.construction()[0]; F\n PreLie[x,y,z]\n sage: type(F)\n <class 'sage.combinat.free_prelie_algebra.PreLieFunctor'>\n sage: F(ZZ) # indirect doctest\n Free PreLie algebra on 3 generators ['x', 'y', 'z'] over Integer Ring\n "
return FreePreLieAlgebra(R, self.vars)
def _apply_functor_to_morphism(self, f):
"\n Apply the functor ``self`` to the ring morphism `f`.\n\n TESTS::\n\n sage: R = algebras.FreePreLie(ZZ, 'x').construction()[0]\n sage: R(ZZ.hom(GF(3))) # indirect doctest\n Generic morphism:\n From: Free PreLie algebra on one generator ['x'] over Integer Ring\n To: Free PreLie algebra on one generator ['x'] over Finite Field of size 3\n "
dom = self(f.domain())
codom = self(f.codomain())
def action(x):
return codom._from_dict({a: f(b) for (a, b) in x.monomial_coefficients().items()})
return dom.module_morphism(function=action, codomain=codom)
def __eq__(self, other):
"\n EXAMPLES::\n\n sage: F = algebras.FreePreLie(ZZ, 'x,y,z').construction()[0]\n sage: G = algebras.FreePreLie(QQ, 'x,y,z').construction()[0]\n sage: F == G\n True\n sage: G == loads(dumps(G))\n True\n sage: G = algebras.FreePreLie(QQ, 'x,y').construction()[0]\n sage: F == G\n False\n "
if (not isinstance(other, PreLieFunctor)):
return False
return (self.vars == other.vars)
def __mul__(self, other):
"\n If two PreLie functors are given in a row, form a single PreLie functor\n with all of the variables.\n\n EXAMPLES::\n\n sage: F = sage.combinat.free_prelie_algebra.PreLieFunctor(['x','y'])\n sage: G = sage.combinat.free_prelie_algebra.PreLieFunctor(['t'])\n sage: G * F\n PreLie[x,y,t]\n "
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, PreLieFunctor):
if set(self.vars).intersection(other.vars):
raise CoercionException(('Overlapping variables (%s,%s)' % (self.vars, other.vars)))
return PreLieFunctor((other.vars + self.vars))
elif (isinstance(other, CompositeConstructionFunctor) and isinstance(other.all[(- 1)], PreLieFunctor)):
return CompositeConstructionFunctor(other.all[:(- 1)], (self * other.all[(- 1)]))
else:
return CompositeConstructionFunctor(other, self)
def merge(self, other):
"\n Merge ``self`` with another construction functor, or return None.\n\n EXAMPLES::\n\n sage: F = sage.combinat.free_prelie_algebra.PreLieFunctor(['x','y'])\n sage: G = sage.combinat.free_prelie_algebra.PreLieFunctor(['t'])\n sage: F.merge(G)\n PreLie[x,y,t]\n sage: F.merge(F)\n PreLie[x,y]\n\n Now some actual use cases::\n\n sage: R = algebras.FreePreLie(ZZ, 'xyz')\n sage: x,y,z = R.gens()\n sage: 1/2 * x\n 1/2*B[x[]]\n sage: parent(1/2 * x)\n Free PreLie algebra on 3 generators ['x', 'y', 'z'] over Rational Field\n\n sage: S = algebras.FreePreLie(QQ, 'zt')\n sage: z,t = S.gens()\n sage: x + t\n B[t[]] + B[x[]]\n sage: parent(x + t)\n Free PreLie algebra on 4 generators ['z', 't', 'x', 'y'] over Rational Field\n "
if isinstance(other, PreLieFunctor):
if (self.vars == other.vars):
return self
ret = list(self.vars)
cur_vars = set(ret)
for v in other.vars:
if (v not in cur_vars):
ret.append(v)
return PreLieFunctor(Alphabet(ret))
else:
return None
def _repr_(self):
"\n TESTS::\n\n sage: algebras.FreePreLie(QQ,'x,y,z,t').construction()[0]\n PreLie[x,y,z,t]\n "
return ('PreLie[%s]' % ','.join(self.vars))
|
def tree_from_sortkey(ch, labels=True):
"\n Transform a list of ``(valence, label)`` into a tree and a remainder.\n\n This is like an inverse of the ``sort_key`` method.\n\n INPUT:\n\n - ``ch`` -- a list of pairs ``(integer, label)``\n - ``labels`` -- (default ``True``) whether to use labelled trees\n\n OUTPUT:\n\n a pair ``(tree, remainder of the input)``\n\n EXAMPLES::\n\n sage: from sage.combinat.free_prelie_algebra import tree_from_sortkey\n sage: a = algebras.FreePreLie(QQ).gen(0)\n sage: t = (a*a*a*a).support()\n sage: all(tree_from_sortkey(u.sort_key(), False)[0] == u for u in t)\n True\n\n sage: a, b = algebras.FreePreLie(QQ,'ab').gens()\n sage: t = (a*b*a*b).support()\n sage: all(tree_from_sortkey(u.sort_key())[0] == u for u in t)\n True\n "
if labels:
Trees = LabelledRootedTrees()
(width, label) = ch[0]
else:
Trees = RootedTrees()
width = ch[0]
remainder = ch[1:]
if (width == 0):
if labels:
return (Trees([], label), remainder)
return (Trees([]), remainder)
branches = {}
for i in range(width):
(tree, remainder) = tree_from_sortkey(remainder, labels=labels)
branches[i] = tree
if labels:
return (Trees(branches.values(), label), remainder)
return (Trees(branches.values()), remainder)
|
def corolla_gen(tx, list_ty, labels=True):
"\n Yield the terms in the corolla with given bottom tree and top trees.\n\n These are the possible terms in the simultaneous grafting of the\n top trees on vertices of the bottom tree.\n\n INPUT:\n\n - ``tx`` -- a tree\n - ``list_ty`` -- a list of trees\n\n EXAMPLES::\n\n sage: from sage.combinat.free_prelie_algebra import corolla_gen\n sage: a = algebras.FreePreLie(QQ).gen(0)\n sage: ta = a.support()[0]\n sage: list(corolla_gen(ta,[ta],False))\n [[[]]]\n\n sage: a, b = algebras.FreePreLie(QQ,'ab').gens()\n sage: ta = a.support()[0]\n sage: tb = b.support()[0]\n sage: ab = (a*b).support()[0]\n sage: list(corolla_gen(ta,[tb]))\n [a[b[]]]\n sage: list(corolla_gen(tb,[ta,ta]))\n [b[a[], a[]]]\n sage: list(corolla_gen(ab,[ab,ta]))\n [a[a[], b[], a[b[]]], a[a[b[]], b[a[]]], a[a[], b[a[b[]]]],\n a[b[a[], a[b[]]]]]\n "
n = len(list_ty)
zx = tx.sort_key()
nx = len(zx)
liste_zy = [t.sort_key() for t in list_ty]
for list_pos in product(range(nx), repeat=n):
new_zx = tuple(zx)
data = zip(list_pos, liste_zy)
sorted_data = sorted(data, reverse=True)
for pos_t in sorted_data:
if labels:
(idx, lbl) = new_zx[pos_t[0]]
new_zx = (((new_zx[:pos_t[0]] + (((idx + 1), lbl),)) + pos_t[1]) + new_zx[(pos_t[0] + 1):])
else:
idx = new_zx[pos_t[0]]
new_zx = (((new_zx[:pos_t[0]] + ((idx + 1),)) + pos_t[1]) + new_zx[(pos_t[0] + 1):])
(yield tree_from_sortkey(new_zx, labels=labels)[0])
|
class FullyCommutativeElement(NormalizedClonableList):
'\n A fully commutative (FC) element in a Coxeter system.\n\n An element `w` in a Coxeter system (W,S) is fully commutative (FC) if every\n two reduced word of w can be related by a sequence of only commutation\n relations, i.e., relations of the form `st=ts` where `s,t` are commuting\n generators in `S`.\n\n Every FC element has a canonical reduced word called its Cartier--Foata\n form. See [Gre2006]_. We will normalize each FC element to this form.\n '
def group_element(self):
"\n Get the actual element of the Coxeter group associated with\n ``self.parent()`` corresponding to ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A', 3])\n sage: FC = W.fully_commutative_elements()\n sage: x = FC([1, 2])\n sage: x.group_element()\n [ 0 -1 1]\n [ 1 -1 1]\n [ 0 0 1]\n sage: x.group_element() in W\n True\n "
return self.parent().coxeter_group().from_reduced_word(self)
def check(self):
"\n Called automatically when an element is created.\n\n EXAMPLES::\n\n sage: CoxeterGroup(['A', 3]).fully_commutative_elements()([1, 2]) # indirect doctest\n [1, 2]\n sage: CoxeterGroup(['A', 3]).fully_commutative_elements()([1, 2, 1]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the input is not a reduced word of a fully commutative element\n "
if (not self.is_fully_commutative()):
raise ValueError('the input is not a reduced word of a fully commutative element')
def normalize(self):
"\n Mutate ``self`` into Cartier-Foata normal form.\n\n EXAMPLES:\n\n The following reduced words express the same FC elements in `B_5`::\n\n sage: FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n sage: FC([1, 4, 3, 5, 2, 4, 3]) # indirect doctest\n [1, 4, 3, 5, 2, 4, 3]\n sage: FC([4, 1, 3, 5, 2, 4, 3]) # indirect doctest\n [1, 4, 3, 5, 2, 4, 3]\n sage: FC([4, 3, 1, 5, 4, 2, 3]) # indirect doctest\n [1, 4, 3, 5, 2, 4, 3]\n\n .. NOTE::\n\n The Cartier--Foata form of a reduced word of an FC element `w` can\n be found recursively by repeatedly moving left descents of\n elements to the left and ordering the left descents from small to\n large. In the above example, the left descents of the element are\n 4 and 1, therefore the Cartier--Foata form of the element is the\n concatenation of [1,4] with the Cartier--Foata form of the\n remaining part of the word. See [Gre2006]_.\n\n .. SEEALSO:: :func:`descents`\n "
self._require_mutable()
out_word = []
while self:
fronts = self.descents()
out_word.extend(sorted(fronts))
for s in fronts:
self.remove(s)
self._set_list(out_word)
def is_fully_commutative(self):
"\n Check if ``self`` is the reduced word of an FC element.\n\n To check if `self` is FC, we use the well-known characterization that an\n element `w` in a Coxeter system `(W,S)` is FC if and only if for every\n pair of generators `s,t \\in S` for which `m(s,t)>2`, no reduced word of\n `w` contains the 'braid' word `sts...` of length `m(s,t)` as a\n contiguous subword. See [Ste1996]_.\n\n :func:`check` is an alias of this method, and is called automatically\n when an element is created.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['A', 3]).fully_commutative_elements()\n sage: x = FC([1, 2]); x.is_fully_commutative()\n True\n sage: x = FC.element_class(FC, [1, 2, 1], check=False); x.is_fully_commutative()\n False\n "
word = list(self)
from sage.combinat.root_system.braid_orbit import is_fully_commutative as is_fully_comm
group = self.parent().coxeter_group()
braid_rels = group.braid_relations()
I = group.index_set()
from sage.rings.integer_ring import ZZ
be_careful = any(((i not in ZZ) for i in I))
if be_careful:
Iinv = {i: j for (j, i) in enumerate(I)}
word = [Iinv[i] for i in word]
braid_rels = [[[Iinv[i] for i in l], [Iinv[i] for i in r]] for (l, r) in braid_rels]
return is_fully_comm(word, braid_rels)
def heap(self, **kargs):
"\n Create the heap poset of ``self``.\n\n The heap of an FC element `w` is a labeled poset that can be defined\n from any reduced word of `w`. Different reduced words yield isomorphic\n labeled posets, so the heap is well defined.\n\n Heaps are very useful for visualizing and studying FC elements; see, for\n example, [Ste1996]_ and [GX2020]_.\n\n INPUT:\n\n - ``self`` -- list, a reduced word `w=s_0... s_{k-1}` of an FC element\n\n - ``one_index`` -- boolean (default: False). Setting the value to True\n will change the underlying set of the poset to `\\{1, 2, \\dots, n\\}`\n\n - ``display_labeling`` -- boolean (default: False). Setting the value to\n True will display the label `s_i` for each element `i` of the poset\n\n OUTPUT:\n\n A labeled poset where the underlying set is `\\{0,1,...,k-1\\}`\n and where each element `i` carries `s_i` as its label. The partial order\n `\\prec` on the poset is defined by declaring `i\\prec j` if `i<j` and\n `m(s_i,s_j)\\neq 2`.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['A', 5]).fully_commutative_elements()\n sage: FC([1, 4, 3, 5, 2, 4]).heap().cover_relations()\n [[1, 2], [1, 3], [2, 5], [2, 4], [3, 5], [0, 4]]\n sage: FC([1, 4, 3, 5, 4, 2]).heap(one_index=True).cover_relations()\n [[2, 3], [2, 4], [3, 6], [3, 5], [4, 6], [1, 5]]\n "
m = self.parent().coxeter_group().coxeter_matrix()
one_index = kargs.get('one_index', False)
display_labeling = kargs.get('display_labeling', False)
elements = (list(range(1, (len(self) + 1))) if one_index else list(range(len(self))))
def letter(index):
return (self[(index - 1)] if one_index else self[index])
relations = [(i, j) for i in elements for j in elements if ((i < j) and (m[(letter(i), letter(j))] != 2))]
p = Poset((elements, relations))
if (not display_labeling):
return p
else:
return p.relabel((lambda i: (i, letter(i))))
def plot_heap(self):
"\n Display the Hasse diagram of the heap of ``self``.\n\n The Hasse diagram is rendered in the lattice `S \\times \\NN`, with\n every element `i` in the poset drawn as a point labelled by its label\n `s_i`. Every point is placed in the column for its label at a certain\n level. The levels start at 0 and the level k of an element `i` is the\n maximal number `k` such that the heap contains a chain `i_0\\prec\n i_1\\prec ... \\prec i_k` where `i_k=i`. See [Ste1996]_ and [GX2020]_.\n\n OUTPUT: GraphicsObject\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n sage: FC([3,2,4,3,1]).plot_heap() # needs sage.plot\n Graphics object consisting of 15 graphics primitives\n\n .. PLOT::\n :width: 400 px\n\n FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n g = FC([3,2,4,3,1]).plot_heap()\n sphinx_plot(g)\n "
import sage.plot.all as plot
m = self.parent().coxeter_group().coxeter_matrix()
letters = self.parent().coxeter_group().index_set()
graphics = []
h = self.heap()
levels = h.level_sets()
letters_at_level = [set((self[i] for i in level)) for level in levels]
for (level_zero_index, members) in enumerate(levels):
level = (level_zero_index + 1)
for i in members:
x = self[i]
graphics.append(plot.circle((x, level), 0.1, fill=True, facecolor='white', edgecolor='blue', zorder=1))
graphics.append(plot.text(str(x), (x, level), color='blue', zorder=2))
neighbors = {z for z in letters if (m[(x, z)] >= 3)}
for other in neighbors:
highest_level = max(((j + 1) for j in range(level_zero_index) if (other in letters_at_level[j])), default=None)
if highest_level:
graphics.append(plot.line([(other, highest_level), (x, level)], color='black', zorder=0))
g = sum(graphics)
g.axes(False)
return g
def n_value(self):
"\n Calculate the n-value of ``self``.\n\n The *n-value* of a fully commutative element is the *width* (length of\n any longest antichain) of its heap. The n-value is important as it\n coincides with Lusztig's a-value for FC elements in all Weyl and affine\n Weyl groups as well as so-called star-reducible groups; see [GX2020]_.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['A', 5]).fully_commutative_elements()\n sage: FC([1,3]).n_value()\n 2\n sage: FC([1,2,3]).n_value()\n 1\n sage: FC([1,3,2]).n_value()\n 2\n sage: FC([1,3,2,5]).n_value()\n 3\n "
return self.heap().width()
def find_descent(self, s, side='left'):
"\n Check if ``s`` is a descent of ``self`` and find its position if so.\n\n A generator `s` is called a left or right descent of an element `w` if\n `l(sw)` or `l(ws)` is smaller than `l(w)`, respectively. If `w` is FC,\n then `s` is a left descent of `w` if and only if `s` appears to in the\n word and every generator to the left of the leftmost `s` in the word\n commutes with `s`. A similar characterization exists for right descents\n of FC elements.\n\n INPUT:\n\n - ``s`` -- integer representing a generator of the Coxeter system\n\n - ``side`` -- string (default: ``'left'``); if the argument is set to\n 'right', the function checks if ``s`` is a right descent of ``self``\n and finds the index of the rightmost occurrence of ``s`` if so\n\n OUTPUT:\n\n Determine if the generator ``s`` is a left descent of ``self``; return\n the index of the leftmost occurrence of ``s`` in ``self`` if so and\n return ``None`` if not.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n sage: w = FC([1, 4, 3, 5, 2, 4, 3])\n sage: w.find_descent(1)\n 0\n sage: w.find_descent(1, side='right')\n <BLANKLINE>\n sage: w.find_descent(4)\n 1\n sage: w.find_descent(4, side='right')\n <BLANKLINE>\n sage: w.find_descent(3)\n <BLANKLINE>\n "
m = self.parent().coxeter_group().coxeter_matrix()
view = (list(self) if (side == 'left') else self[::(- 1)])
for (i, t) in enumerate(view):
if ((t == s) and (not any(((m[(x, t)] > 2) for x in view[:i])))):
return i
return None
def has_descent(self, s, side='left'):
"\n Determine if ``s`` is a descent on the appropriate side of ``self``.\n\n INPUT:\n\n - ``side`` -- string (default: ``'left'``); if set to 'right', determine\n if ``self`` has ``s`` as a right descent\n\n OUTPUT: a boolean value\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n sage: w = FC([1, 4, 3, 5, 2, 4, 3])\n sage: w.has_descent(1)\n True\n sage: w.has_descent(1, side='right')\n False\n sage: w.has_descent(4)\n True\n sage: w.has_descent(4, side='right')\n False\n\n .. SEEALSO:: :func:`find_descent`\n "
return (self.find_descent(s, side=side) is not None)
def descents(self, side='left'):
"\n Obtain the set of descents on the appropriate side of ``self``.\n\n INPUT:\n\n - ``side`` -- string (default: ``'left'``); if set to 'right', find the\n right descents\n\n A generator `s` is called a left or right descent of an element `w` if\n `l(sw)` or `l(ws)` is smaller than `l(w)`, respectively. If `w` is FC,\n then `s` is a left descent of `w` if and only if `s` appears to in the\n word and every generator to the left of the leftmost `s` in the word\n commutes with `s`. A similar characterization exists for right descents\n of FC elements.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup(['B', 5]).fully_commutative_elements()\n sage: w = FC([1, 4, 3, 5, 2, 4, 3])\n sage: sorted(w.descents())\n [1, 4]\n sage: w.descents(side='right')\n {3}\n sage: FC = CoxeterGroup(['A', 5]).fully_commutative_elements()\n sage: sorted(FC([1, 4, 3, 5, 2, 4, 3]).descents())\n [1, 4]\n\n .. SEEALSO:: :func:`find_descent`\n "
view = (list(self) if (side == 'left') else self[::(- 1)])
m = self.parent().coxeter_group().coxeter_matrix()
out = set()
for (i, t) in enumerate(view):
if (not any(((m[(x, t)] > 2) for x in view[:i]))):
out.add(t)
return out
def coset_decomposition(self, J, side='left'):
'\n Return the coset decomposition of ``self`` with respect to the parabolic\n subgroup generated by ``J``.\n\n INPUT:\n\n - ``J`` -- subset of the generating set `S` of the Coxeter system\n\n - ``side`` -- string (default: ``\'left\'``); if the value is set to\n \'right\', then the function returns the tuple `(w\'^J, w\'_J)` from the\n coset decomposition `w = w\'^J \\cdot w\'_J` of `w` with respect to `J`\n\n OUTPUT:\n\n The tuple of elements `(w_J, w^J)` such that `w=w_J \\cdot w^J`, `w_J` is\n generated by the elements in `J`, and `w^J` has no left descent from\n `J`. This tuple is unique and satisfies the equation `\\ell(w) =\n \\ell(w_J) + \\ell(w^J)`, where `\\ell` denotes Coxeter length, by general\n theory; see Proposition 2.4.4 of [BB2005]_.\n\n EXAMPLES::\n\n sage: FC = CoxeterGroup([\'B\', 6]).fully_commutative_elements()\n sage: w = FC([1, 6, 2, 5, 4, 6, 5])\n sage: w.coset_decomposition({1})\n ([1], [6, 2, 5, 4, 6, 5])\n sage: w.coset_decomposition({1}, side = \'right\')\n ([1, 6, 2, 5, 4, 6, 5], [])\n sage: w.coset_decomposition({5, 6})\n ([6, 5, 6], [1, 2, 4, 5])\n sage: w.coset_decomposition({5, 6}, side=\'right\')\n ([1, 6, 2, 5, 4], [6, 5])\n\n .. NOTE::\n\n The factor `w_J` of the coset decomposition `w = w_J \\cdot\n w^J` can be obtained by greedily "pulling left descents of `w` that\n are in `J` to the left"; see the proof of [BB2005]_. This greedy\n algorithm works for all elements in Coxeter group, but it becomes\n especially simple for FC elements because descents are easier to\n find for FC elements.\n '
string = []
remaining = self.clone()
if (side == 'right'):
remaining._set_list(remaining[::(- 1)])
while True:
x = next((x for x in J if remaining.has_descent(x, side='left')), None)
if (x is not None):
string.append(x)
remaining.remove(x)
else:
break
if (side == 'right'):
remaining._set_list(remaining[::(- 1)])
string = string[::(- 1)]
string = self.parent().element_class(self.parent(), string, check=False)
remaining.set_immutable()
return ((string, remaining) if (side == 'left') else (remaining, string))
def _still_reduced_fc_after_prepending(self, s):
"\n Determine if ``self`` prepended with ``s`` is still a reduced word of an\n FC element in the Coxeter system.\n\n INPUT:\n\n - ``s`` -- integer representing a generator of the Coxeter system\n - ``self`` -- a reduced word of an FC element\n\n EXAMPLES:\n\n Consider the FC element `w = 12` in the group `B_3`::\n\n sage: FCB3 = CoxeterGroup(['B', 3]).fully_commutative_elements()\n sage: w = FCB3([1,2])\n\n When `s=1`, `sw` is 112, which is not reduced::\n\n sage: w._still_reduced_fc_after_prepending(1)\n False\n\n\n When `s=2`, `sw` is 212, which is reduced but not FC::\n\n sage: w._still_reduced_fc_after_prepending(2)\n False\n\n When `s=31, `sw` is 312, which is reduced and FC::\n\n sage: w._still_reduced_fc_after_prepending(3)\n True\n\n More examples::\n\n sage: u = FCB3([3,1,2])\n sage: u._still_reduced_fc_after_prepending(1)\n False\n sage: u._still_reduced_fc_after_prepending(2)\n True\n sage: u._still_reduced_fc_after_prepending(3)\n False\n\n sage: FCA5 = CoxeterGroup(['A', 5]).fully_commutative_elements()\n sage: w = FCA5([2,4,1,3,2,5])\n sage: w._still_reduced_fc_after_prepending(5)\n False\n\n .. NOTE::\n\n If `w` is a reduced word of an element, then the concatenation\n `sw` is still a reduced word if and only if `s` is not a left\n descent of `w` by general Coxeter group theory. So now assume `w`\n is a reduced word of an FC element and `s` is not a left descent\n `w`. In this case, Lemma 4.1 of [Ste1996]_ implies that `sw` is\n not a reduced word of an FC element if and only if some letter in\n `w` does not commute with `s` and the following conditions hold\n simultaneously for the leftmost such letter `t`:\n\n (1) `t` is left descent of the word `u_1` obtained by removing\n all letters to the left of the aforementioned `t` from `w`;\n (this condition is automatically true by definition of `u_1`)\n\n (2) `s` is left descent of the word `u_2` obtained by\n removing the leftmost `t` from `u_1`;\n\n (3) `t` is left descent of the word `u_3` obtained by\n removing the leftmost `s` from `u_2`;\n\n ...\n\n (m-1) the appropriate element in `\\{s, t\\}` is a left descent\n of the word `u_{m-1}` obtained by removing the leftmost letter\n required to be a descent in Condition (m-2) from `u_{m-2}`.\n\n In the last example above, we have `s=5`, `t=4`, Condition (1)\n holds, but Condition (2) fails, therefore `5w` is still a\n reduced word of an FC element.\n\n Note that the conditions (1)--(m-1) are equivalent to the\n condition that the parabolic factor `u_J` from the coset\n decomposition `u_1 = u_J \\cdot u^J` of `u_1` with respect to\n `J := \\{s, t\\}` is the element `tst...` of length `m(s,t)-1`.\n\n REFERENCES:\n\n See Lemma 4.1 of [Ste1996]_.\n "
m = self.parent().coxeter_group().coxeter_matrix()
if self.has_descent(s):
return False
try:
(j, t) = next(((i, x) for (i, x) in enumerate(self) if (m[(s, x)] >= 3)))
except StopIteration:
return True
u = self.clone()
u._set_list(self[j:])
(x, _) = u.coset_decomposition({s, t})
return (len(x) != (m[(s, t)] - 1))
def star_operation(self, J, direction, side='left'):
"\n Apply a star operation on ``self`` relative to two noncommuting\n generators.\n\n Star operations were first defined on elements of Coxeter groups by\n Kazhdan and Lusztig in [KL1979]_ with respect to pair of generators\n `s,t` such that `m(s,t)=3`. Later, Lusztig generalized the definition in\n [Lus1985]_, via coset decompositions, to allow star operations with\n respect to any pair of generators `s,t` such that `m(s,t)\\ge 3`. Given\n such a pair, we can potentially perform four types of star operations\n corresponding to all combinations of a 'direction' and a 'side': upper\n left, lower left, upper right and lower right; see [Gre2006]_.\n\n Let `w` be an element in `W` and let `J` be any pair `\\{s, t\\}` of\n noncommuting generators in `S`. Consider the coset decomposition `w =\n w_J \\cdot {}^J w` of `w` relative to `J`. Then an upper left star\n operation is defined on `w` if and only if `1 \\le l(w_J) \\le m(s,t)-2`;\n when this is the case, the operation returns `x\\cdot w_J\\cdot w^J` where\n `x` is the letter `J` different from the leftmost letter of `w_J`. A\n lower left star operation is defined on `w` if and only if `2 \\le l(w_J)\n \\le m(s,t)-1`; when this is the case, the operation removes the leftmost\n letter of `w_J` from `w`. Similar facts hold for right star operations.\n See [Gre2006]_.\n\n The facts of the previous paragraph hold in general, even if `w` is not\n FC. Note that if `f` is a star operation of any kind, then for every\n element `w \\in W`, the elements `w` and `f(w)` are either both FC or\n both not FC.\n\n INPUT:\n\n - ``J`` -- a set of two integers representing two noncommuting\n generators of the Coxeter system\n\n - ``direction`` -- string, ``'upper'`` or ``'lower'``; the function\n performs an upper or lower star operation according to ``direction``\n\n - ``side`` -- string (default: ``'left'``); if this is set to 'right',\n the function performs a right star operation\n\n OUTPUT:\n\n The Cartier--Foata form of the result of the star operation if the\n operation is defined on ``self``, ``None`` otherwise.\n\n EXAMPLES:\n\n We will compute all star operations on the following FC element in type\n `B_6` relative to `J = \\{5, 6\\}`::\n\n sage: FC = CoxeterGroup(['B', 6]).fully_commutative_elements()\n sage: w = FC([1, 6, 2, 5, 4, 6, 5])\n\n Whether and how a left star operations can be applied depend on the\n coset decomposition `w = w_J \\cdot w^J`::\n\n sage: w.coset_decomposition({5, 6})\n ([6, 5, 6], [1, 2, 4, 5])\n\n Only the lower star operation is defined on the left on `w`::\n\n sage: w.star_operation({5,6}, 'upper')\n <BLANKLINE>\n sage: w.star_operation({5,6}, 'lower')\n [1, 5, 2, 4, 6, 5]\n\n Whether and how a right star operations can be applied depend on the\n coset decomposition `w = w^J \\cdot w_J`::\n\n sage: w.coset_decomposition({5, 6}, side='right')\n ([1, 6, 2, 5, 4], [6, 5])\n\n Both types of right star operations on defined for this example::\n\n sage: w.star_operation({5, 6}, 'upper', side='right')\n [1, 6, 2, 5, 4, 6, 5, 6]\n\n sage: w.star_operation({5, 6}, 'lower', side='right')\n [1, 6, 2, 5, 4, 6]\n "
assert (len(J) == 2), 'J needs to contain a pair of generators.'
(s, t) = J
mst = self.parent().coxeter_group().coxeter_matrix()[(s, t)]
if (side == 'left'):
(string, remaining) = self.coset_decomposition(J, side=side)
elif (side == 'right'):
(remaining, string) = self.coset_decomposition(J, side=side)
cur_string = list(string)
if ((direction == 'lower') and (2 <= len(string) <= (mst - 1))):
new_string = (cur_string[1:] if (side == 'left') else cur_string[:(- 1)])
elif ((direction == 'upper') and (1 <= len(string) <= (mst - 2))):
ending_letter = (cur_string[0] if (side == 'left') else cur_string[(- 1)])
other = next((x for x in J if (x != ending_letter)))
new_string = (([other] + cur_string) if (side == 'left') else (cur_string + [other]))
else:
return None
combined_data = ((new_string + list(remaining)) if (side == 'left') else (list(remaining) + new_string))
return self.parent().element_class(self.parent(), combined_data, check=False)
|
class FullyCommutativeElements(UniqueRepresentation, Parent):
"\n Class for the set of fully commutative (FC) elements of a Coxeter system.\n\n Coxeter systems with finitely many FC elements, or *FC-finite* Coxeter\n systems, are classfied by Stembridge in [Ste1996]_. They fall into seven\n families, namely the groups of types `A_n, B_n, D_n, E_n, F_n, H_n` and\n `I_2(m)`.\n\n INPUT:\n\n - ``data`` -- CoxeterMatrix, CartanType, or the usual datum that can is\n taken in the constructors for these classes (see\n :func:`sage.combinat.root_system.coxeter_group.CoxeterGroup`)\n\n OUTPUT:\n\n The class of fully commutative elements in the Coxeter group constructed\n from ``data``. This will belong to the category of enumerated sets. If the\n Coxeter data corresponds to a Cartan type, the category is further refined\n to either finite enumerated sets or infinite enumerated sets depending on i\n whether the Coxeter group is FC-finite; the refinement is not carried out if\n ``data`` is a Coxeter matrix not corresponding to a Cartan type.\n\n .. TODO::\n\n It would be ideal to implement the aforementioned refinement to finite\n and infinite enumerated sets for all possible ``data``, regardless of\n whether it corresponds to a Cartan type. Doing so requires determining\n if an arbitrary Coxeter matrix corresponds to a Cartan type. It may be\n best to address this issue in ``sage.combinat.root_system``. On the other\n hand, the refinement in the general case may be unnecessary in light of\n the fact that Stembridge's classification of FC-finite groups contains\n a very small number of easily-recognizable families.\n\n EXAMPLES:\n\n Create the enumerate set of fully commutative elements in `B_3`::\n\n sage: FC = CoxeterGroup(['B', 3]).fully_commutative_elements(); FC\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2 with a = 1.414213562373095? with Coxeter matrix:\n [1 3 2]\n [3 1 4]\n [2 4 1]\n\n Construct elements::\n\n sage: FC([])\n []\n sage: FC([1,2])\n [1, 2]\n sage: FC([2,3,2])\n [2, 3, 2]\n sage: FC([3,2,3])\n [3, 2, 3]\n\n Elements are normalized to Cartier--Foata normal form upon construction::\n\n sage: FC([3,1])\n [1, 3]\n sage: FC([2,3,1])\n [2, 1, 3]\n sage: FC([1,3]) == FC([3,1])\n True\n\n Attempting to create an element from an input that is not the reduced word\n of a fully commutative element throws a :class:`ValueError`::\n\n sage: FC([1,2,1])\n Traceback (most recent call last):\n ...\n ValueError: the input is not a reduced word of a fully commutative element\n sage: FC([2,3,2,3])\n Traceback (most recent call last):\n ...\n ValueError: the input is not a reduced word of a fully commutative element\n\n Enumerate the FC elements in `A_3`::\n\n sage: FCA3 = CoxeterGroup(['A', 3]).fully_commutative_elements()\n sage: FCA3.category()\n Category of finite enumerated sets\n sage: FCA3.list()\n [[],\n [1],\n [2],\n [3],\n [2, 1],\n [1, 3],\n [1, 2],\n [3, 2],\n [2, 3],\n [3, 2, 1],\n [2, 1, 3],\n [1, 3, 2],\n [1, 2, 3],\n [2, 1, 3, 2]]\n\n Count the FC elements in `B_8`::\n\n sage: FCB8 = CoxeterGroup(['B', 8]).fully_commutative_elements()\n sage: len(FCB8) # long time (7 seconds)\n 14299\n\n Iterate through the FC elements of length up to 2 in the non-FC-finite group\n affine `A_2`::\n\n sage: FCAffineA2 = CoxeterGroup(['A', 2, 1]).fully_commutative_elements()\n sage: FCAffineA2.category()\n Category of infinite enumerated sets\n sage: list(FCAffineA2.iterate_to_length(2))\n [[], [0], [1], [2], [1, 0], [2, 0], [0, 1], [2, 1], [0, 2], [1, 2]]\n\n The cardinality of the set is determined from the classification of\n FC-finite Coxeter groups::\n\n sage: CoxeterGroup('A2').fully_commutative_elements().category()\n Category of finite enumerated sets\n sage: CoxeterGroup('B7').fully_commutative_elements().category()\n Category of finite enumerated sets\n sage: CoxeterGroup('A3~').fully_commutative_elements().category()\n Category of infinite enumerated sets\n sage: CoxeterGroup('F4~').fully_commutative_elements().category()\n Category of finite enumerated sets\n sage: CoxeterGroup('E8~').fully_commutative_elements().category()\n Category of finite enumerated sets\n sage: CoxeterGroup('F4~xE8~').fully_commutative_elements().category()\n Category of finite enumerated sets\n sage: CoxeterGroup('B4~xE8~').fully_commutative_elements().category()\n Category of infinite enumerated sets\n "
@staticmethod
def __classcall_private__(cls, data):
"\n EXAMPLES::\n\n sage: from sage.combinat.fully_commutative_elements import FullyCommutativeElements\n sage: x1 = FullyCommutativeElements(CoxeterGroup(['B', 3])); x1\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2 with a = 1.414213562373095? with Coxeter matrix:\n [1 3 2]\n [3 1 4]\n [2 4 1]\n sage: x2 = FullyCommutativeElements(['B', 3]); x2\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2 with a = 1.414213562373095? with Coxeter matrix:\n [1 3 2]\n [3 1 4]\n [2 4 1]\n sage: x3 = FullyCommutativeElements(CoxeterMatrix([[1, 3, 2], [3, 1, 4], [2, 4, 1]])); x3\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2 with a = 1.414213562373095? with Coxeter matrix:\n [1 3 2]\n [3 1 4]\n [2 4 1]\n sage: x1 is x2 is x3\n True\n sage: FullyCommutativeElements(CartanType(['B', 3]).relabel({1: 3, 2: 2, 3: 1}))\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2 with a = 1.414213562373095? with Coxeter matrix:\n [1 4 2]\n [4 1 3]\n [2 3 1]\n sage: m = CoxeterMatrix([(1, 5, 2, 2, 2), (5, 1, 3, 2, 2), (2, 3, 1, 3, 2), (2, 2, 3, 1, 3), (2, 2, 2, 3, 1)]); FullyCommutativeElements(m)\n Fully commutative elements of Coxeter group over Universal Cyclotomic Field with Coxeter matrix:\n [1 5 2 2 2]\n [5 1 3 2 2]\n [2 3 1 3 2]\n [2 2 3 1 3]\n [2 2 2 3 1]\n "
if (data in CoxeterGroups()):
group = data
else:
group = CoxeterGroup(data)
return super().__classcall__(cls, group)
def __init__(self, coxeter_group):
"\n EXAMPLES::\n\n sage: from sage.combinat.fully_commutative_elements import FullyCommutativeElements\n sage: FC = FullyCommutativeElements(CoxeterGroup(['H', 4]))\n sage: TestSuite(FC).run()\n "
self._coxeter_group = coxeter_group
category = EnumeratedSets()
coxeter_type = self._coxeter_group.coxeter_type()
if (not isinstance(coxeter_type, CoxeterMatrix)):
ctypes = ([coxeter_type] if coxeter_type.is_irreducible() else coxeter_type.component_types())
is_finite = True
for ctype in ctypes:
(family, rank) = (ctype.type(), ctype.rank())
if (not (ctype.is_finite() or ((family == 'F') and (rank == 5)) or ((family == 'E') and (rank == 9)))):
is_finite = False
break
if is_finite:
category = category.Finite()
else:
category = category.Infinite()
else:
pass
Parent.__init__(self, category=category)
def _repr_(self):
"\n EXAMPLES::\n\n sage: CoxeterGroup(['H', 4]).fully_commutative_elements()\n Fully commutative elements of Finite Coxeter group over Number Field in a with defining polynomial x^2 - 5 with a = 2.236067977499790? with Coxeter matrix:\n [1 3 2 2]\n [3 1 3 2]\n [2 3 1 5]\n [2 2 5 1]\n "
return 'Fully commutative elements of {}'.format(str(self.coxeter_group()))
def _element_constructor_(self, lst):
"\n TESTS::\n\n sage: FC = CoxeterGroup(['A', 3]).fully_commutative_elements()\n sage: FC([1, 2]) # indirect doctest\n [1, 2]\n "
return self.element_class(self, lst)
Element = FullyCommutativeElement
def coxeter_group(self):
"\n Obtain the Coxeter group associated with ``self``.\n\n EXAMPLES::\n\n sage: FCA3 = CoxeterGroup(['A', 3]).fully_commutative_elements()\n sage: FCA3.coxeter_group()\n Finite Coxeter group over Integer Ring with Coxeter matrix:\n [1 3 2]\n [3 1 3]\n [2 3 1]\n "
return self._coxeter_group
def __iter__(self):
"\n Enumerate the elements of this set by length, starting with the empty\n word and, if the group is FC-finite, ending with the longest fully\n commutative element.\n\n TESTS::\n\n sage: FC = CoxeterGroup(['A', 10]).fully_commutative_elements()\n sage: next(iter(FC)) # indirect doctest\n []\n "
empty_word = self.element_class(self, [], check=False)
letters = self.coxeter_group().index_set()
recent_words = {empty_word: True}
(yield empty_word)
while recent_words:
new_words = {}
for w in recent_words:
for s in letters:
if w._still_reduced_fc_after_prepending(s):
sw = self.element_class(self, ([s] + list(w)), check=False)
new_words[sw] = True
for w in new_words:
(yield w)
recent_words = new_words
def iterate_to_length(self, length):
"\n Iterate through the elements of this class up to a maximum length.\n\n INPUT:\n\n - ``length`` -- integer; maximum length of element to generate\n\n OUTPUT: generator for elements of ``self`` of length up to ``length``\n\n EXAMPLES:\n\n The following example produces all FC elements of length up to 2 in the\n group `A_3`::\n\n sage: FCA3 = CoxeterGroup(['A', 3]).fully_commutative_elements()\n sage: list(FCA3.iterate_to_length(2))\n [[], [1], [2], [3], [2, 1], [1, 3], [1, 2], [3, 2], [2, 3]]\n\n The lists for length 4 and 5 are the same since 4 is the maximum length\n of an FC element in `A_3`::\n\n sage: list(FCA3.iterate_to_length(4))\n [[], [1], [2], [3], [2, 1], [1, 3], [1, 2], [3, 2], [2, 3],\n [3, 2, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3], [2, 1, 3, 2]]\n sage: list(FCA3.iterate_to_length(5))\n [[], [1], [2], [3], [2, 1], [1, 3], [1, 2], [3, 2], [2, 3],\n [3, 2, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3], [2, 1, 3, 2]]\n sage: list(FCA3.iterate_to_length(4)) == list(FCA3)\n True\n\n The following example produces all FC elements of length up to 4 in the\n affine Weyl group `\\tilde A_2`::\n\n sage: FCAffineA2 = CoxeterGroup(['A', 2, 1]).fully_commutative_elements()\n sage: FCAffineA2.category()\n Category of infinite enumerated sets\n sage: list(FCAffineA2.iterate_to_length(4))\n [[], [0], [1], [2], [1, 0], [2, 0], [0, 1], [2, 1], [0, 2],\n [1, 2], [2, 1, 0], [1, 2, 0], [2, 0, 1], [0, 2, 1], [1, 0, 2],\n [0, 1, 2], [0, 2, 1, 0], [0, 1, 2, 0], [1, 2, 0, 1],\n [1, 0, 2, 1], [2, 1, 0, 2], [2, 0, 1, 2]]\n "
for w in self:
if (len(w) > length):
break
(yield w)
|
def _make_color_list(n, colors=None, color_map=None, randomize=False):
"\n TESTS::\n\n sage: from sage.combinat.fully_packed_loop import _make_color_list\n sage: _make_color_list(5)\n sage: _make_color_list(5, ['blue', 'red'])\n ['blue', 'red', 'blue', 'red', 'blue']\n sage: _make_color_list(5, color_map='summer')\n [(0.0, 0.5, 0.4),\n (0.25098039215686274, 0.6254901960784314, 0.4),\n (0.5019607843137255, 0.7509803921568627, 0.4),\n (0.7529411764705882, 0.8764705882352941, 0.4),\n (1.0, 1.0, 0.4)]\n sage: l = _make_color_list(8, ['blue', 'red'], randomize=True)\n sage: len(l)\n 8\n sage: l.count('blue')\n 4\n sage: l.count('red')\n 4\n "
if colors:
dim = len(colors)
colors = [colors[(i % dim)] for i in range(n)]
elif color_map:
from matplotlib import cm
if (color_map not in cm.datad):
raise ValueError(('unknown color map %s' % color_map))
cmap = cm.__dict__[color_map]
colors = [cmap((i / float((n - 1))))[:3] for i in range(n)]
if (colors and randomize):
from sage.misc.prandom import shuffle
shuffle(colors)
return colors
|
class FullyPackedLoop(Element, metaclass=InheritComparisonClasscallMetaclass):
"\n A class for fully packed loops.\n\n A fully packed loop is a collection of non-intersecting lattice paths on a square\n grid such that every vertex is part of some path, and the paths are either closed\n internal loops or have endpoints corresponding to alternate points on the\n boundary [Pro2001]_. They are known to be in bijection with alternating sign\n matrices.\n\n .. SEEALSO::\n\n :class:`AlternatingSignMatrix`\n\n To each fully packed loop, we assign a link pattern, which is the non-crossing\n matching attained by seeing which points on the boundary are connected\n by open paths in the fully packed loop.\n\n We can create a fully packed loop using the corresponding alternating sign\n matrix and also extract the link pattern::\n\n sage: A = AlternatingSignMatrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl.link_pattern()\n [(1, 4), (2, 3), (5, 6)]\n sage: fpl\n | |\n | |\n + -- + +\n | |\n | |\n -- + + + --\n | |\n | |\n + + -- +\n | |\n | |\n sage: B = AlternatingSignMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n sage: fplb = FullyPackedLoop(B)\n sage: fplb.link_pattern()\n [(1, 6), (2, 5), (3, 4)]\n sage: fplb\n | |\n | |\n + + -- +\n | |\n | |\n -- + + + --\n | |\n | |\n + -- + +\n | |\n | |\n\n The class also has a plot method::\n\n sage: fpl.plot() # needs sage.plot\n Graphics object consisting of 3 graphics primitives\n\n which gives:\n\n .. PLOT::\n :width: 200 px\n\n A = AlternatingSignMatrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n fpl = FullyPackedLoop(A)\n p = fpl.plot()\n sphinx_plot(p)\n\n Note that we can also create a fully packed loop from a six vertex model configuration::\n\n sage: S = SixVertexModel(3, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: S\n ^ ^ ^\n | | |\n --> # -> # -> # <--\n ^ ^ |\n | | V\n --> # -> # <- # <--\n ^ | |\n | V V\n --> # <- # <- # <--\n | | |\n V V V\n sage: fpl = FullyPackedLoop(S)\n sage: fpl\n | |\n | |\n + -- + +\n | |\n | |\n -- + + + --\n | |\n | |\n + + -- +\n | |\n | |\n\n Once we have a fully packed loop we can obtain the corresponding alternating sign matrix::\n\n sage: fpl.to_alternating_sign_matrix()\n [0 0 1]\n [0 1 0]\n [1 0 0]\n\n Here are some more examples using bigger ASMs::\n\n sage: A = AlternatingSignMatrix([[0,1,0,0],[0,0,1,0],[1,-1,0,1],[0,1,0,0]])\n sage: S = SixVertexModel(4, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: fpl = FullyPackedLoop(S)\n sage: fpl.link_pattern()\n [(1, 2), (3, 6), (4, 5), (7, 8)]\n sage: fpl\n | |\n | |\n + -- + -- + + --\n |\n |\n -- + + -- + -- +\n | |\n | |\n + + + -- + --\n | | |\n | | |\n -- + + + -- +\n | |\n | |\n\n sage: m = AlternatingSignMatrix([[0,0,1,0,0,0],\n ....: [1,0,-1,0,1,0],\n ....: [0,0,0,1,0,0],\n ....: [0,1,0,0,-1,1],\n ....: [0,0,0,0,1,0],\n ....: [0,0,1,0,0,0]])\n sage: fpl = FullyPackedLoop(m)\n sage: fpl.link_pattern()\n [(1, 12), (2, 7), (3, 4), (5, 6), (8, 9), (10, 11)]\n sage: fpl\n | | |\n | | |\n + -- + + + -- + + --\n | | | |\n | | | |\n -- + -- + + + -- + -- +\n |\n |\n + -- + + -- + -- + + --\n | | | |\n | | | |\n -- + + + -- + + +\n | | | | |\n | | | | |\n + -- + + -- + + + --\n | |\n | |\n -- + + -- + -- + + -- +\n | | |\n | | |\n\n sage: m = AlternatingSignMatrix([[0,1,0,0,0,0,0],\n ....: [1,-1,0,0,1,0,0],\n ....: [0,0,0,1,0,0,0],\n ....: [0,1,0,0,-1,1,0],\n ....: [0,0,0,0,1,0,0],\n ....: [0,0,1,0,-1,0,1],\n ....: [0,0,0,0,1,0,0]])\n sage: fpl = FullyPackedLoop(m)\n sage: fpl.link_pattern()\n [(1, 2), (3, 4), (5, 6), (7, 8), (9, 14), (10, 11), (12, 13)]\n sage: fpl\n | | | |\n | | | |\n + -- + -- + + -- + + -- +\n | |\n | |\n -- + -- + -- + + -- + -- + + --\n | |\n | |\n + -- + + -- + -- + + -- +\n | | | |\n | | | |\n -- + + + -- + + + + --\n | | | | | |\n | | | | | |\n + -- + + -- + + + -- +\n | |\n | |\n -- + + -- + -- + + + -- + --\n | | | |\n | | | |\n + -- + + -- + + + -- +\n | | | |\n | | | |\n\n Gyration on an alternating sign matrix/fully packed loop ``fpl``\n of the link pattern corresponding to ``fpl``::\n\n sage: ASMs = AlternatingSignMatrices(3).list()\n sage: ncp = FullyPackedLoop(ASMs[1]).link_pattern() # fpl's gyration orbit size is 2\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(5):\n ....: a,b=a%6+1,b%6+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(ASMs[1].gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: fpl = FullyPackedLoop(ASMs[0])\n sage: ncp = fpl.link_pattern() # fpl's gyration size is 3\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(5):\n ....: a,b=a%6+1,b%6+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(ASMs[0].gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: mat = AlternatingSignMatrix([[0,0,1,0,0,0,0],[1,0,-1,0,1,0,0],\n ....: [0,0,1,0,0,0,0],[0,1,-1,0,0,1,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0],[0,0,0,0,0,0,1]])\n sage: fpl = FullyPackedLoop(mat) # n=7\n sage: ncp = fpl.link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(13):\n ....: a,b=a%14+1,b%14+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(mat.gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: mat = AlternatingSignMatrix([[0,0,0,1,0,0], [0,0,1,-1,1,0],\n ....: [0,1,0,0,-1,1], [1,0,-1,1,0,0], [0,0,1,0,0,0], [0,0,0,0,1,0]])\n sage: fpl = FullyPackedLoop(mat) # n =6\n sage: ncp = fpl.link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(11):\n ....: a,b=a%12+1,b%12+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(mat.gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n More examples:\n\n We can initiate a fully packed loop using an alternating sign matrix::\n\n sage: A = AlternatingSignMatrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl\n | |\n | |\n + -- + +\n | |\n | |\n -- + + + --\n | |\n | |\n + + -- +\n | |\n | |\n sage: FullyPackedLoops(3)(A) == fpl\n True\n\n We can also input a matrix::\n\n sage: FullyPackedLoop([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n | |\n | |\n + -- + +\n | |\n | |\n -- + + + --\n | |\n | |\n + + -- +\n | |\n | |\n sage: FullyPackedLoop([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) ==\\\n ....: FullyPackedLoops(3)([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n True\n\n Otherwise we initiate a fully packed loop using a six vertex model::\n\n sage: S = SixVertexModel(3, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: fpl = FullyPackedLoop(S)\n sage: fpl\n | |\n | |\n + -- + +\n | |\n | |\n -- + + + --\n | |\n | |\n + + -- +\n | |\n | |\n\n sage: FullyPackedLoops(3)(S) == FullyPackedLoop(S)\n True\n\n sage: fpl.six_vertex_model().to_alternating_sign_matrix()\n [0 0 1]\n [0 1 0]\n [1 0 0]\n\n We can also input the matrix associated to a six vertex model::\n\n sage: SixVertexModel(2)([[3,1],[5,3]])\n ^ ^\n | |\n --> # <- # <--\n | ^\n V |\n --> # -> # <--\n | |\n V V\n\n sage: FullyPackedLoop([[3,1],[5,3]])\n |\n |\n + + --\n | |\n | |\n -- + +\n |\n |\n\n sage: FullyPackedLoops(2)([[3,1],[5,3]]) == FullyPackedLoop([[3,1],[5,3]])\n True\n\n Note that the matrix corresponding to a six vertex model without\n the ice boundary condition is not allowed::\n\n sage: SixVertexModel(2)([[3,1],[5,5]])\n ^ ^\n | |\n --> # <- # <--\n | ^\n V V\n --> # -> # -->\n | |\n V V\n\n sage: FullyPackedLoop([[3,1],[5,5]])\n Traceback (most recent call last):\n ...\n ValueError: invalid alternating sign matrix\n\n sage: FullyPackedLoops(2)([[3,1],[5,5]])\n Traceback (most recent call last):\n ...\n ValueError: invalid alternating sign matrix\n\n Note that if anything else is used to generate the fully packed loop an error will occur::\n\n sage: fpl = FullyPackedLoop(5)\n Traceback (most recent call last):\n ...\n ValueError: invalid alternating sign matrix\n\n sage: fpl = FullyPackedLoop((1, 2, 3))\n Traceback (most recent call last):\n ...\n ValueError: the alternating sign matrices must be square\n\n sage: SVM = SixVertexModel(3)[0]\n sage: FullyPackedLoop(SVM)\n Traceback (most recent call last):\n ...\n ValueError: invalid alternating sign matrix\n\n REFERENCES:\n\n - [Pro2001]_\n - [Str2015]_\n "
@staticmethod
def __classcall_private__(cls, generator):
"\n Create a FPL.\n\n EXAMPLES::\n\n sage: A = AlternatingSignMatrix([[1, 0, 0],[0, 1, 0],[0, 0, 1]])\n sage: FullyPackedLoop(A)\n | |\n | |\n + + -- +\n | |\n | |\n -- + + + --\n | |\n | |\n + -- + +\n | |\n | |\n\n sage: SVM = SixVertexModel(4, boundary_conditions='ice')[0]\n sage: FullyPackedLoop(SVM)\n | |\n | |\n + + -- + + --\n | | |\n | | |\n -- + + + -- +\n | |\n | |\n + -- + + + --\n | | |\n | | |\n -- + + -- + +\n | |\n | |\n "
if isinstance(generator, AlternatingSignMatrix):
SVM = generator.to_six_vertex_model()
elif isinstance(generator, SquareIceModel.Element):
SVM = generator
elif isinstance(generator, SixVertexConfiguration):
generator = SixVertexModel(generator.parent()._nrows, boundary_conditions='ice')(generator)
M = generator.to_alternating_sign_matrix().to_matrix()
AlternatingSignMatrix(M)
SVM = generator
else:
try:
SVM = AlternatingSignMatrix(generator).to_six_vertex_model()
except (TypeError, ValueError):
generator = matrix(generator)
generator = SixVertexModel(generator.nrows(), boundary_conditions='ice')(generator)
generator.to_alternating_sign_matrix()
SVM = generator
if (not SVM):
raise TypeError('generator for FullyPackedLoop must either be an AlternatingSignMatrix or a SquareIceModel.Element')
FPLs = FullyPackedLoops(len(SVM))
return FPLs(generator)
def __init__(self, parent, generator):
'\n Initialise object, can take ASM of FPL as generator.\n\n TESTS::\n\n sage: A = AlternatingSignMatrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: TestSuite(fpl).run()\n\n '
if isinstance(generator, AlternatingSignMatrix):
self._six_vertex_model = generator.to_six_vertex_model()
elif isinstance(generator, SquareIceModel.Element):
self._six_vertex_model = generator
Element.__init__(self, parent)
def _repr_(self):
"\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: A = AlternatingSignMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl\n | |\n | |\n + + -- +\n | |\n | |\n -- + + + --\n | |\n | |\n + -- + +\n | |\n | |\n\n sage: A = AlternatingSignMatrix([[0,1,0,0],[0,0,1,0],[1,-1,0,1],[0,1,0,0]])\n sage: S = SixVertexModel(4, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: fpl = FullyPackedLoop(S)\n sage: fpl\n | |\n | |\n + -- + -- + + --\n |\n |\n -- + + -- + -- +\n | |\n | |\n + + + -- + --\n | | |\n | | |\n -- + + + -- +\n | |\n | |\n\n "
n = (len(self._six_vertex_model) - 1)
ascii1 = [[' ', ' -', ' ', '- '], [' | ', ' ', ' ', '- '], [' ', ' ', ' | ', '- '], [' | ', ' ', ' | ', ' '], [' | ', ' -', ' ', ' '], [' ', ' -', ' | ', ' ']]
ascii2 = [[' | ', ' ', ' | ', ' '], [' ', ' -', ' | ', ' '], [' | ', ' -', ' ', ' '], [' ', ' -', ' ', '- '], [' ', ' ', ' | ', '- '], [' | ', ' ', ' ', '- ']]
ret = ' '
for (i, entry) in enumerate(self._six_vertex_model[0]):
if ((i % 2) == 0):
ret += ' | '
else:
ret += ' '
plus_sign = '+'
for (j, row) in enumerate(self._six_vertex_model):
ret += '\n '
for (i, entry) in enumerate(row):
if (((i + j) % 2) == 0):
ret += ascii1[entry][0]
else:
ret += ascii2[entry][0]
ret += '\n'
if ((j % 2) == 0):
ret += ' '
else:
ret += ' -'
for (i, entry) in enumerate(row):
if (((i + j) % 2) == 0):
ret += ((ascii1[entry][3] + plus_sign) + ascii1[entry][1])
else:
ret += ((ascii2[entry][3] + plus_sign) + ascii2[entry][1])
if (((j + n) % 2) == 0):
ret += ' '
else:
ret += '- '
ret += '\n '
for (i, entry) in enumerate(row):
if (((i + j) % 2) == 0):
ret += ascii1[entry][2]
else:
ret += ascii2[entry][2]
ret += '\n '
for (i, entry) in enumerate(self._six_vertex_model[(- 1)]):
if ((((i + n) + 1) % 2) == 0):
ret += ' '
else:
ret += ' | '
return ret
def _richcmp_(self, other, op):
'\n Check equality or inequality.\n\n EXAMPLES::\n\n sage: A = AlternatingSignMatrices(3)\n sage: M = A.random_element()\n sage: FullyPackedLoop(M) == M.to_fully_packed_loop()\n True\n\n sage: FullyPackedLoop(A([[1, 0, 0],[0, 1, 0],[0, 0, 1]])) == ....: FullyPackedLoop(A([[1, 0, 0],[0, 0, 1],[0, 1, 0]]))\n False\n\n sage: FullyPackedLoop(M) == M\n False\n\n sage: M = A.random_element()\n sage: FullyPackedLoop(M) != M.to_fully_packed_loop()\n False\n\n sage: f0 = FullyPackedLoop(A([[1, 0, 0],[0, 1, 0],[0, 0, 1]]))\n sage: f1 = FullyPackedLoop(A([[1, 0, 0],[0, 0, 1],[0, 1, 0]]))\n sage: f0 != f1\n True\n '
return self._six_vertex_model._richcmp_(other._six_vertex_model, op)
def to_alternating_sign_matrix(self):
"\n Return the alternating sign matrix corresponding to this class.\n\n .. SEEALSO::\n\n :class:`AlternatingSignMatrix`\n\n EXAMPLES::\n\n sage: A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n sage: S = SixVertexModel(3, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: fpl = FullyPackedLoop(S)\n sage: fpl.to_alternating_sign_matrix()\n [ 0 1 0]\n [ 1 -1 1]\n [ 0 1 0]\n sage: A = AlternatingSignMatrix([[0,1,0,0],[0,0,1,0],[1,-1,0,1],[0,1,0,0]])\n sage: S = SixVertexModel(4, boundary_conditions='ice').from_alternating_sign_matrix(A)\n sage: fpl = FullyPackedLoop(S)\n sage: fpl.to_alternating_sign_matrix()\n [ 0 1 0 0]\n [ 0 0 1 0]\n [ 1 -1 0 1]\n [ 0 1 0 0]\n "
return self._six_vertex_model.to_alternating_sign_matrix()
@options(link=True, loop=True, loop_fill=False)
def plot(self, **options):
'\n Return a graphical object of the Fully Packed Loop.\n\n Each option can be specified separately for links (the curves that join\n boundary points) and the loops. In order to do so, you need to prefix\n its name with either ``\'link_\'`` or ``\'loop_\'``. As an example, setting\n ``color=\'red\'`` will color both links and loops in red while setting\n ``link_color=\'red\'`` will only apply the color option for the links.\n\n INPUT:\n\n - ``link``, ``loop`` - (boolean, default ``True``) whether to plot the links\n or the loops\n\n - ``color``, ``link_color``, ``loop_color`` - (optional, a string or a\n RGB triple)\n\n - ``colors``, ``link_colors``, ``loop_colors`` - (optional, list) a list of\n colors\n\n - ``color_map``, ``link_color_map``, ``loop_color_map`` - (string,\n optional) a name of a matplotlib color map for the link or the loop\n\n - ``link_color_randomize`` - (boolean, default ``False``) when\n ``link_colors`` or ``link_color_map`` is specified it randomizes\n its order. Setting this option to ``True`` makes it unlikely to\n have two neighboring links with the same color.\n\n - ``loop_fill`` - (boolean, optional) whether to fill the interior of the loops\n\n EXAMPLES:\n\n To plot the fully packed loop associated to the following alternating sign\n matrix\n\n .. MATH::\n\n \\begin{pmatrix} 0&1&1 \\\\ 1&-1&1 \\\\ 0&1&0 \\end{pmatrix}\n\n simply do::\n\n sage: A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl.plot() # needs sage.plot\n Graphics object consisting of 3 graphics primitives\n\n The resulting graphics is as follows\n\n .. PLOT::\n :width: 200 px\n\n A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n fpl = FullyPackedLoop(A)\n p = fpl.plot()\n sphinx_plot(p)\n\n You can also have the three links in different colors with::\n\n sage: A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl.plot(link_color_map=\'rainbow\') # needs sage.plot\n Graphics object consisting of 3 graphics primitives\n\n .. PLOT::\n :width: 200 px\n\n A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n fpl = FullyPackedLoop(A)\n p = fpl.plot(link_color_map=\'rainbow\')\n sphinx_plot(p)\n\n You can plot the 42 fully packed loops of size `4 \\times 4` using::\n\n sage: G = [fpl.plot(link_color_map=\'winter\', loop_color=\'black\') # needs sage.plot\n ....: for fpl in FullyPackedLoops(4)]\n sage: graphics_array(G, 7, 6) # needs sage.plot\n Graphics Array of size 7 x 6\n\n .. PLOT::\n :width: 600 px\n\n G = [fpl.plot(link_color_map=\'winter\', loop_color=\'black\') for fpl in FullyPackedLoops(4)]\n p = graphics_array(G, 7, 6)\n sphinx_plot(p)\n\n Here is an example of a `20 \\times 20` fully packed loop::\n\n sage: s = "00000000000+0000000000000000+00-0+00000000000+00-00+0-+00000\\\n ....: 0000+-00+00-+00000000+00-0000+0000-+00000000+000-0+0-+0-+000\\\n ....: 000+-000+-00+0000000+-+-000+00-+0-000+000+-000+-0+0000000-0+\\\n ....: 0000+0-+0-+00000-+00000+-+0-0+-00+0000000000+-0000+0-00+0000\\\n ....: 000000+0-000+000000000000000+0000-00+00000000+0000-000+00000\\\n ....: 00+0-00+0000000000000000+-0000+000000-+000000+00-0000+-00+00\\\n ....: 00000000+-0000+00000000000000+0000000000"\n sage: a = matrix(20, [{\'0\':0, \'+\':1, \'-\': -1}[i] for i in s])\n sage: fpl = FullyPackedLoop(a)\n sage: fpl.plot(loop_fill=True, loop_color_map=\'rainbow\') # needs sage.plot\n Graphics object consisting of 27 graphics primitives\n\n .. PLOT::\n :width: 400 px\n\n s = "00000000000+0000000000000000+00-0+00000000000+00-00+0-+00000\\\n 0000+-00+00-+00000000+00-0000+0000-+00000000+000-0+0-+0-+000\\\n 000+-000+-00+0000000+-+-000+00-+0-000+000+-000+-0+0000000-0+\\\n 0000+0-+0-+00000-+00000+-+0-0+-00+0000000000+-0000+0-00+0000\\\n 000000+0-000+000000000000000+0000-00+00000000+0000-000+00000\\\n 00+0-00+0000000000000000+-0000+000000-+000000+00-0000+-00+00\\\n 00000000+-0000+00000000000000+0000000000"\n a = matrix(20, [{\'0\':0, \'+\':1, \'-\': -1}[i] for i in s])\n p = FullyPackedLoop(a).plot(loop_fill=True, loop_color_map=\'rainbow\')\n sphinx_plot(p)\n '
from sage.plot.graphics import Graphics
from sage.plot.line import line2d
from sage.plot.polygon import polygon2d
link_options = {}
loop_options = {}
for (k, v) in options.items():
if (k == 'link'):
link = v
elif (k == 'loop'):
loop = v
elif k.startswith('link_'):
link_options[k[5:]] = v
elif k.startswith('loop_'):
loop_options[k[5:]] = v
else:
link_options[k] = v
loop_options[k] = v
sv = self._six_vertex_model
n = len(sv)
rank = self.parent()._boundary_index
unrank = self.parent()._boundary
seen = ([False] * (2 * n))
squares = set(((i, j) for i in range(n) for j in range(n)))
colors = _make_color_list((2 * n), colors=link_options.pop('colors', None), color_map=link_options.pop('color_map', None), randomize=link_options.pop('color_randomize', False))
G = Graphics()
for i in range((2 * n)):
if seen[i]:
continue
orbit = self._link_or_loop_from(unrank(i))
j = rank(orbit[(- 1)])
seen[i] = seen[j] = True
squares.difference_update(orbit)
if link:
if colors:
link_options['color'] = colors.pop()
orbit = [(j, ((n - i) - 1)) for (i, j) in orbit]
G += line2d(orbit, **link_options)
loops = []
while squares:
orbit = self._link_or_loop_from(squares.pop())
loops.append(orbit)
squares.difference_update(orbit)
if loop:
colors = _make_color_list(len(loops), colors=loop_options.pop('colors', None), color_map=loop_options.pop('color_map', None), randomize=loop_options.pop('color_randomize', False))
fill = loop_options.pop('fill')
for orbit in loops:
if colors:
loop_options['color'] = colors.pop()
orbit = [(j, ((n - i) - 1)) for (i, j) in orbit]
if fill:
G += polygon2d(orbit, **loop_options)
else:
G += line2d(orbit, **loop_options)
G.axes(False)
G.set_aspect_ratio(1)
return G
def gyration(self):
'\n Return the fully packed loop obtained by applying gyration\n to the alternating sign matrix in bijection with ``self``.\n\n Gyration was first defined in [Wie2000]_ as an action on\n fully-packed loops.\n\n EXAMPLES::\n\n sage: A = AlternatingSignMatrix([[1, 0, 0],[0, 1, 0],[0, 0, 1]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl.gyration().to_alternating_sign_matrix()\n [0 0 1]\n [0 1 0]\n [1 0 0]\n sage: asm = AlternatingSignMatrix([[0, 0, 1],[1, 0, 0],[0, 1, 0]])\n sage: f = FullyPackedLoop(asm)\n sage: f.gyration().to_alternating_sign_matrix()\n [0 1 0]\n [0 0 1]\n [1 0 0]\n '
return FullyPackedLoop(self.to_alternating_sign_matrix().gyration())
def _link_or_loop_from(self, pos, d0=None):
'\n Return the coordinates of the line passing through ``pos``.\n\n EXAMPLES:\n\n A link::\n\n sage: fpl = FullyPackedLoops(4).first()\n sage: fpl._link_or_loop_from((2,2))\n [(0, 4), (0, 3), (1, 3), (1, 2), (2, 2), (3, 2), (3, 1), (4, 1)]\n sage: fpl._link_or_loop_from((-1, 0))\n [(-1, 0), (0, 0), (1, 0), (1, -1)]\n\n A loop::\n\n sage: a = AlternatingSignMatrix([[0,1,0,0], [0,0,0,1], [1,0,0,0], [0,0,1,0]])\n sage: fpl = FullyPackedLoop(a)\n sage: fpl._link_or_loop_from((1,1))\n [(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)]\n '
global R, L, U, D, FPL_turns, FPL_edges
orbit = [pos]
sv = self._six_vertex_model
n = len(sv)
(i, j) = pos
if ((i < (- 1)) or (i > n) or (j < (- 1)) or (j > n)):
raise ValueError('indices out of range')
if (((i == (- 1)) or (i == n)) and (not ((i + j) % 2))):
raise ValueError('left and right boundary values must have odd sum')
if (((j == (- 1)) or (j == n)) and ((i + j) % 2)):
raise ValueError('up and down boundary values must have even sum')
if (i == (- 1)):
d = R
elif (i == n):
d = L
elif (j == (- 1)):
d = U
elif (j == n):
d = D
elif (d0 is None):
d = FPL_edges[((i + j) % 2)][sv[i][j]][0]
elif (d0 in FPL_edges[((i + j) % 2)][sv[i][j]]):
d = d0
else:
raise ValueError('invalid direction')
while True:
i += d[0]
j += d[1]
orbit.append((i, j))
if (((i, j) == orbit[0]) or (i == (- 1)) or (j == (- 1)) or (i == n) or (j == n)):
break
conf = sv[i][j]
parity = ((i + j) % 2)
d = FPL_turns[parity][conf][d]
if (d is None):
raise RuntimeError
if ((i == (- 1)) or (j == (- 1)) or (i == n) or (j == n)):
(i0, j0) = orbit[0]
if ((d0 is None) and (i0 != (- 1)) and (i0 != n) and (j0 != (- 1)) and (j0 != n)):
(i1, j1) = orbit[1]
d = ((i0 - i1), (j0 - j1))
orbit2 = self._link_or_loop_from(orbit[1], d)
assert ((orbit2[0] == (i1, j1)) and (orbit2[1] == (i0, j0)))
return (orbit2[:1:(- 1)] + orbit)
return orbit
else:
return orbit
def link_pattern(self):
'\n Return a link pattern corresponding to a fully packed loop.\n\n Here we define a link pattern `LP` to be a partition of the list\n `[1, ..., 2k]` into 2-element sets (such a partition is also known as\n a perfect matching) such that the following non-crossing condition holds:\n Let the numbers `1, ..., 2k` be written on the perimeter of a circle.\n For every 2-element set `(a,b)` of the partition `LP`, draw an arc\n linking the two numbers `a` and `b`. We say that `LP` is non-crossing\n if every arc can be drawn so that no two arcs intersect.\n\n Since every endpoint of a fully packed loop `fpl` is connected to a different\n endpoint, there is a natural surjection from the fully packed loops on an\n nxn grid onto the link patterns on the list `[1, \\dots, 2n]`.\n The pairs of connected endpoints of a fully packed loop `fpl` correspond to\n the 2-element tuples of the corresponding link pattern.\n\n .. SEEALSO::\n\n :class:`PerfectMatching`\n\n .. NOTE::\n\n by convention, we choose the top left vertex to be even.\n See [Pro2001]_ and [Str2015]_.\n\n EXAMPLES:\n\n We can extract the underlying link pattern (a non-crossing\n partition) from a fully packed loop::\n\n sage: A = AlternatingSignMatrix([[0, 1, 0], [1, -1, 1], [0, 1, 0]])\n sage: fpl = FullyPackedLoop(A)\n sage: fpl.link_pattern()\n [(1, 2), (3, 6), (4, 5)]\n\n sage: B = AlternatingSignMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n sage: fpl = FullyPackedLoop(B)\n sage: fpl.link_pattern()\n [(1, 6), (2, 5), (3, 4)]\n\n Gyration on an alternating sign matrix/fully packed loop ``fpl``\n corresponds to a rotation (i.e. a becomes a-1 mod 2n)\n of the link pattern corresponding to ``fpl``::\n\n sage: ASMs = AlternatingSignMatrices(3).list()\n sage: ncp = FullyPackedLoop(ASMs[1]).link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(5):\n ....: a,b=a%6+1,b%6+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(ASMs[1].gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: fpl = FullyPackedLoop(ASMs[0])\n sage: ncp = fpl.link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(5):\n ....: a,b=a%6+1,b%6+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(ASMs[0].gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: mat = AlternatingSignMatrix([[0,0,1,0,0,0,0],[1,0,-1,0,1,0,0],[0,0,1,0,0,0,0],\n ....: [0,1,-1,0,0,1,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0],[0,0,0,0,0,0,1]])\n sage: fpl = FullyPackedLoop(mat) # n=7\n sage: ncp = fpl.link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(13):\n ....: a,b=a%14+1,b%14+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(mat.gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n sage: mat = AlternatingSignMatrix([[0,0,0,1,0,0], [0,0,1,-1,1,0], [0,1,0,0,-1,1], [1,0,-1,1,0,0],\n ....: [0,0,1,0,0,0], [0,0,0,0,1,0]])\n sage: fpl = FullyPackedLoop(mat)\n sage: ncp = fpl.link_pattern()\n sage: rotated_ncp=[]\n sage: for (a,b) in ncp:\n ....: for i in range(11):\n ....: a,b=a%12+1,b%12+1;\n ....: rotated_ncp.append((a,b))\n sage: PerfectMatching(mat.gyration().to_fully_packed_loop().link_pattern()) ==\\\n ....: PerfectMatching(rotated_ncp)\n True\n\n TESTS:\n\n We test previous two bugs which showed up when this method is called twice::\n\n sage: A = AlternatingSignMatrices(6)\n sage: B = A.random_element()\n sage: C = FullyPackedLoop(B)\n sage: D = C.link_pattern()\n sage: E = C.link_pattern()\n sage: D == E\n True\n '
global L, R, U, D, FPL_turns
link_pattern = []
n = len(self._six_vertex_model)
seen = ([False] * (2 * n))
unrank = self.parent()._boundary
rank = self.parent()._boundary_index
sv = self._six_vertex_model
for k in range((2 * n)):
if seen[k]:
continue
(i, j) = unrank(k)
if (i == (- 1)):
d = R
elif (i == n):
d = L
elif (j == (- 1)):
d = U
elif (j == n):
d = D
while True:
i += d[0]
j += d[1]
if ((i == (- 1)) or (j == (- 1)) or (i == n) or (j == n)):
break
conf = sv[i][j]
parity = ((i + j) % 2)
d = FPL_turns[parity][conf][d]
l = rank((i, j))
seen[k] = seen[l] = True
link_pattern.append(((k + 1), (l + 1)))
return link_pattern
def six_vertex_model(self):
'\n Return the underlying six vertex model configuration.\n\n EXAMPLES::\n\n sage: B = AlternatingSignMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n sage: fpl = FullyPackedLoop(B)\n sage: fpl\n | |\n | |\n + + -- +\n | |\n | |\n -- + + + --\n | |\n | |\n + -- + +\n | |\n | |\n sage: fpl.six_vertex_model()\n ^ ^ ^\n | | |\n --> # <- # <- # <--\n | ^ ^\n V | |\n --> # -> # <- # <--\n | | ^\n V V |\n --> # -> # -> # <--\n | | |\n V V V\n '
return self._six_vertex_model
|
class FullyPackedLoops(Parent, UniqueRepresentation):
"\n Class of all fully packed loops on an `n \\times n` grid.\n\n They are known to be in bijection with alternating sign matrices.\n\n .. SEEALSO::\n\n :class:`AlternatingSignMatrices`\n\n INPUT:\n\n - ``n`` -- the number of row (and column) or grid\n\n EXAMPLES:\n\n This will create an instance to manipulate the fully packed loops of size 3::\n\n sage: FPLs = FullyPackedLoops(3)\n sage: FPLs\n Fully packed loops on a 3x3 grid\n sage: FPLs.cardinality()\n 7\n\n When using the square ice model, it is known that the number of\n configurations is equal to the number of alternating sign matrices::\n\n sage: M = FullyPackedLoops(1)\n sage: len(M)\n 1\n sage: M = FullyPackedLoops(4)\n sage: len(M)\n 42\n sage: all(len(SixVertexModel(n, boundary_conditions='ice'))\n ....: == FullyPackedLoops(n).cardinality() for n in range(1, 7))\n True\n "
def __init__(self, n):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: FPLs = FullyPackedLoops(3)\n sage: TestSuite(FPLs).run()\n '
self._n = n
Parent.__init__(self, category=FiniteEnumeratedSets())
def __iter__(self):
'\n Iterate through ``self``.\n\n EXAMPLES::\n\n sage: FPLs = FullyPackedLoops(2)\n sage: len(FPLs)\n 2\n '
for X in SixVertexModel(self._n, boundary_conditions='ice'):
(yield self.element_class(self, X))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: FPLs = FullyPackedLoops(4); FPLs\n Fully packed loops on a 4x4 grid\n '
return ('Fully packed loops on a %sx%s grid' % (self._n, self._n))
def __contains__(self, fpl):
'\n Check if ``fpl`` is in ``self``.\n\n TESTS::\n\n sage: FPLs = FullyPackedLoops(3)\n sage: FullyPackedLoop(AlternatingSignMatrix([[0,1,0],[1,0,0],[0,0,1]])) in FPLs\n True\n sage: FullyPackedLoop(AlternatingSignMatrix([[0,1,0],[1,-1,1],[0,1,0]])) in FPLs\n True\n sage: FullyPackedLoop(AlternatingSignMatrix([[0, 1],[1,0]])) in FPLs\n False\n sage: FullyPackedLoop(AlternatingSignMatrix([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])) in FPLs\n False\n sage: [1,2,3] in FPLs\n False\n '
return (parent(fpl) is self)
def _element_constructor_(self, generator):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: FPLs = FullyPackedLoops(4)\n sage: M = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]\n sage: A = AlternatingSignMatrix(M)\n sage: elt = FullyPackedLoop(A)\n sage: FPL = FPLs(elt); FPL\n | |\n | |\n + + -- + + --\n | | |\n | | |\n -- + + + -- +\n | |\n | |\n + -- + + + --\n | | |\n | | |\n -- + + -- + +\n | |\n | |\n\n sage: FPLs(A) == FPL\n True\n\n sage: FPLs(M) == FPL\n True\n\n sage: FPLs(FPL._six_vertex_model) == FPL\n True\n\n sage: FPL.parent() is FPLs\n True\n\n sage: FPL = FullyPackedLoops(2)\n sage: FPL([[3,1],[5,3]])\n |\n |\n + + --\n | |\n | |\n -- + +\n |\n |\n '
if isinstance(generator, AlternatingSignMatrix):
SVM = generator.to_six_vertex_model()
elif (isinstance(generator, SquareIceModel.Element) or isinstance(generator, SixVertexConfiguration)):
SVM = generator
else:
try:
SVM = AlternatingSignMatrix(generator).to_six_vertex_model()
except (TypeError, ValueError):
SVM = SixVertexModel(self._n, boundary_conditions='ice')(generator)
SVM.to_alternating_sign_matrix()
if (len(SVM) != self._n):
raise ValueError('invalid size')
return self.element_class(self, SVM)
Element = FullyPackedLoop
def size(self):
'\n Return the size of the matrices in ``self``.\n\n TESTS::\n\n sage: FPLs = FullyPackedLoops(4)\n sage: FPLs.size()\n 4\n '
return self._n
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n The number of fully packed loops on `n \\times n` grid\n\n .. MATH::\n\n \\prod_{k=0}^{n-1} \\frac{(3k+1)!}{(n+k)!} = \\frac{1! 4! 7! 10!\n \\cdots (3n-2)!}{n! (n+1)! (n+2)! (n+3)! \\cdots (2n-1)!}.\n\n EXAMPLES::\n\n sage: [AlternatingSignMatrices(n).cardinality() for n in range(10)]\n [1, 1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]\n '
return Integer(prod(((factorial(((3 * k) + 1)) / factorial((self._n + k))) for k in range(self._n))))
def _an_element_(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: FPLs = FullyPackedLoops(3)\n sage: FPLs.an_element()\n | |\n | |\n + + -- +\n | |\n | |\n -- + + + --\n | |\n | |\n + -- + +\n | |\n | |\n '
SVM = SixVertexModel(self._n, boundary_conditions='ice').an_element()
return self.element_class(self, SVM)
def _boundary(self, k):
'\n Return the coordinates of the ``k``-th boundary.\n\n TESTS::\n\n sage: F = FullyPackedLoops(5)\n sage: [F._boundary(k) for k in range(10)] == F._boundaries()\n True\n sage: all(F._boundary_index(F._boundary(k)) == k for k in range(10))\n True\n\n sage: F = FullyPackedLoops(6)\n sage: [F._boundary(k) for k in range(12)] == F._boundaries()\n True\n sage: all(F._boundary_index(F._boundary(k)) == k for k in range(12))\n True\n '
n = self._n
n_LR = ((n // 2) if ((n % 2) == 0) else ((n + 1) // 2))
n_TB = ((n // 2) if ((n % 2) == 0) else ((n - 1) // 2))
if (k < n_LR):
return ((- 1), (2 * k))
k -= n_LR
if (k < n_TB):
return (((n % 2) + (2 * k)), n)
k -= n_TB
if (k < n_LR):
return (n, ((n - 1) - (2 * k)))
k -= n_LR
if (k < n_TB):
return ((((n - 1) - (n % 2)) - (2 * k)), (- 1))
def _boundary_index(self, pos):
'\n Return the index of the boundary at position ``pos``.\n\n TESTS::\n\n sage: F = FullyPackedLoops(5)\n sage: [F._boundary_index(b) for b in F._boundaries()]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: all(F._boundary(F._boundary_index(b)) == b for b in F._boundaries())\n True\n\n sage: F = FullyPackedLoops(6)\n sage: [F._boundary_index(b) for b in F._boundaries()]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n sage: all(F._boundary(F._boundary_index(b)) == b for b in F._boundaries())\n True\n '
n = self._n
(i, j) = pos
if (i == (- 1)):
return (j // 2)
elif (j == n):
return (((n + 1) // 2) + (i // 2))
elif (i == n):
return (n + ((n - j) // 2))
elif (j == (- 1)):
return (((3 * n) // 2) + ((n - i) // 2))
def _boundaries(self):
'\n Return the list of coordinates for the link in the boundaries.\n\n TESTS::\n\n sage: FullyPackedLoops(5)._boundaries()\n [(-1, 0), (-1, 2), (-1, 4), (1, 5), (3, 5),\n (5, 4), (5, 2), (5, 0), (3, -1), (1, -1)]\n\n sage: FullyPackedLoops(6)._boundaries()\n [(-1, 0), (-1, 2), (-1, 4), (0, 6), (2, 6), (4, 6),\n (6, 5), (6, 3), (6, 1), (5, -1), (3, -1), (1, -1)]\n '
n = self._n
boundaries = []
boundaries.extend((((- 1), j) for j in range(0, n, 2)))
boundaries.extend(((i, n) for i in range((n % 2), n, 2)))
boundaries.extend(((n, j) for j in range((n - 1), (- 1), (- 2))))
boundaries.extend(((i, (- 1)) for i in range(((n - 1) - (n % 2)), (- 1), (- 2))))
return boundaries
|
class GelfandTsetlinPattern(ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
'\n A Gelfand-Tsetlin (sometimes written as Gelfand-Zetlin or Gelfand-Cetlin)\n pattern. They were originally defined in [GC50]_.\n\n A Gelfand-Tsetlin pattern is a triangular array:\n\n .. MATH::\n\n \\begin{array}{ccccccccc}\n a_{1,1} & & a_{1,2} & & a_{1,3} & & \\cdots & & a_{1,n} \\\\\n & a_{2,2} & & a_{2,3} & & \\cdots & & a_{2,n} \\\\\n & & a_{3,3} & & \\cdots & & a_{3,n} \\\\\n & & & \\ddots \\\\\n & & & & a_{n,n}\n \\end{array}\n\n such that `a_{i,j} \\geq a_{i+1,j+1} \\geq a_{i,j+1}`.\n\n Gelfand-Tsetlin patterns are in bijection with semistandard Young tableaux\n by the following algorithm. Let `G` be a Gelfand-Tsetlin pattern with\n `\\lambda^{(k)}` being the `(n-k+1)`-st row (note that this is a partition).\n The definition of `G` implies\n\n .. MATH::\n\n \\lambda^{(0)} \\subseteq \\lambda^{(1)} \\subseteq \\cdots \\subseteq\n \\lambda^{(n)},\n\n where `\\lambda^{(0)}` is the empty partition, and each skew shape\n `\\lambda^{(k)}/\\lambda^{(k-1)}` is a horizontal strip. Thus define `T(G)`\n by inserting `k` into the squares of the skew shape\n `\\lambda^{(k)}/ \\lambda^{(k-1)}`, for `k=1,\\dots,n`.\n\n To each entry in a Gelfand-Tsetlin pattern, one may attach a decoration of\n a circle or a box (or both or neither). These decorations appear in the\n study of Weyl group multiple Dirichlet series, and are implemented here\n following the exposition in [BBF]_.\n\n .. NOTE::\n\n We use the "right-hand" rule for determining circled and boxed entries.\n\n .. WARNING::\n\n The entries in Sage are 0-based and are thought of as flushed to the\n left in a matrix. In other words, the coordinates of entries in the\n Gelfand-Tsetlin patterns are thought of as the matrix:\n\n .. MATH::\n\n \\begin{bmatrix}\n g_{0,0} & g_{0,1} & g_{0,2} & \\cdots & g_{0,n-2} & g_{n-1,n-1} \\\\\n g_{1,0} & g_{1,1} & g_{1,2} & \\cdots & g_{1,n-2} \\\\\n g_{2,0} & g_{2,1} & g_{2,2} & \\cdots \\\\\n \\vdots & \\vdots & \\vdots \\\\\n g_{n-2,0} & g_{n-2,1} \\\\\n g_{n-1,0}\n \\end{bmatrix}.\n\n However, in the discussions, we will be using the **standard**\n numbering system.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3, 2, 1], [2, 1], [1]]); G\n [[3, 2, 1], [2, 1], [1]]\n sage: G.pp()\n 3 2 1\n 2 1\n 1\n sage: G = GelfandTsetlinPattern([[7, 7, 4, 0], [7, 7, 3], [7, 5], [5]]); G.pp()\n 7 7 4 0\n 7 7 3\n 7 5\n 5\n sage: G.to_tableau().pp()\n 1 1 1 1 1 2 2\n 2 2 2 2 2 3 3\n 3 3 3 4\n '
@staticmethod
def __classcall_private__(self, gt):
'\n Return ``gt`` as a proper element of :class:`GelfandTsetlinPatterns`.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[2,1],[1]])\n sage: G.parent()\n Gelfand-Tsetlin patterns\n sage: TestSuite(G).run()\n '
return GelfandTsetlinPatterns()(gt)
def check(self):
'\n Check that this is a valid Gelfand-Tsetlin pattern.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: G([[3,2,1],[2,1],[1]]).check()\n '
assert all(((self[(i - 1)][j] >= self[i][j] >= self[(i - 1)][(j + 1)]) for i in range(1, len(self)) for j in range(len(self[i]))))
def _hash_(self) -> int:
'\n Return the hash value of ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: gt = G([[3,2,1],[2,1],[1]])\n sage: hash(gt) == hash(gt)\n True\n\n Check that :trac:`14717` is fixed::\n\n sage: GT = GelfandTsetlinPattern([[2, 1, 0], [2, 0], [1]])\n sage: GT in {}\n False\n '
return hash(tuple(map(tuple, self)))
def _repr_diagram(self) -> str:
'\n Return a string representation of ``self`` as a diagram.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: print(G([[3,2,1],[2,1],[1]])._repr_diagram())\n 3 2 1\n 2 1\n 1\n '
ret = ''
for (i, row) in enumerate(self):
if (i != 0):
ret += '\n'
ret += (' ' * i)
ret += ' '.join((('%3s' % val) for val in row))
return ret
def pp(self):
'\n Pretty print ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: G([[3,2,1],[2,1],[1]]).pp()\n 3 2 1\n 2 1\n 1\n '
print(self._repr_diagram())
def _latex_(self) -> str:
'\n Return a `\\LaTeX` representation of ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: latex(G([[3,2,1],[2,1],[1]]))\n \\begin{array}{ccccc}\n 3 & & 2 & & 1 \\\\\n & 2 & & 1 & \\\\\n & & 1 & &\n \\end{array}\n sage: latex(G([]))\n \\emptyset\n '
n = len(self)
if (n == 0):
return '\\emptyset'
ret = (('\\begin{array}{' + ('c' * ((n * 2) - 1))) + '}\n')
for (i, row) in enumerate(self):
if (i > 0):
ret += ' \\\\\n'
ret += ('& ' * i)
ret += ' & & '.join((repr(val) for val in row))
ret += (' &' * i)
return (ret + '\n\\end{array}')
@combinatorial_map(name='to semistandard tableau')
def to_tableau(self):
'\n Return ``self`` as a semistandard Young tableau.\n\n The conversion from a Gelfand-Tsetlin pattern to a semistandard Young\n tableaux is as follows. Let `G` be a Gelfand-Tsetlin pattern with\n `\\lambda^{(k)}` being the `(n-k+1)`-st row (note that this is a\n partition). The definition of `G` implies\n\n .. MATH::\n\n \\lambda^{(0)} \\subseteq \\lambda^{(1)} \\subseteq \\cdots \\subseteq\n \\lambda^{(n)},\n\n where `\\lambda^{(0)}` is the empty partition, and each skew shape\n `\\lambda^{(k)} / \\lambda^{(k-1)}` is a horizontal strip. Thus define\n `T(G)` by inserting `k` into the squares of the skew shape\n `\\lambda^{(k)} / \\lambda^{(k-1)}`, for `k=1,\\dots,n`.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: elt = G([[3,2,1],[2,1],[1]])\n sage: T = elt.to_tableau(); T\n [[1, 2, 3], [2, 3], [3]]\n sage: T.pp()\n 1 2 3\n 2 3\n 3\n sage: G(T) == elt\n True\n '
ret = []
for (i, row) in enumerate(reversed(self)):
for (j, val) in enumerate(row):
if (j >= len(ret)):
if (val == 0):
break
ret.append(([(i + 1)] * val))
else:
ret[j].extend(([(i + 1)] * (val - len(ret[j]))))
S = SemistandardTableaux(max_entry=len(self))
return S(ret)
@cached_method
def boxed_entries(self) -> tuple:
'\n Return the position of the boxed entries of ``self``.\n\n Using the *right-hand* rule, an entry `a_{i,j}` is boxed if\n `a_{i,j} = a_{i-1,j-1}`; i.e., `a_{i,j}` has the same value as its\n neighbor to the northwest.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[1]])\n sage: G.boxed_entries()\n ((1, 0),)\n '
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if (self[i][j] == self[(i - 1)][j]):
ret.append((i, j))
return tuple(ret)
@cached_method
def circled_entries(self) -> tuple:
'\n Return the circled entries of ``self``.\n\n Using the *right-hand* rule, an entry `a_{i,j}` is circled if\n `a_{i,j} = a_{i-1,j}`; i.e., `a_{i,j}` has the same value as its\n neighbor to the northeast.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[1]])\n sage: G.circled_entries()\n ((1, 1), (2, 0))\n '
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if (self[i][j] == self[(i - 1)][(j + 1)]):
ret.append((i, j))
return tuple(ret)
@cached_method
def special_entries(self) -> tuple:
'\n Return the special entries.\n\n An entry `a_{i,j}` is special if `a_{i-1,j-1} > a_{i,j} > a_{i-1,j}`,\n that is to say, the entry is neither boxed nor circled and is **not**\n in the first row. The name was coined by [Tok88]_.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[1]])\n sage: G.special_entries()\n ()\n sage: G = GelfandTsetlinPattern([[4,2,1],[4,1],[2]])\n sage: G.special_entries()\n ((2, 0),)\n '
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if ((self[(i - 1)][j] > self[i][j]) and (self[i][j] > self[(i - 1)][(j + 1)])):
ret.append((i, j))
return tuple(ret)
def number_of_boxes(self) -> int:
'\n Return the number of boxed entries. See :meth:`boxed_entries()`.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[1]])\n sage: G.number_of_boxes()\n 1\n '
return len(self.boxed_entries())
def number_of_circles(self) -> int:
'\n Return the number of boxed entries. See :meth:`circled_entries()`.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[1]])\n sage: G.number_of_circles()\n 2\n '
return len(self.circled_entries())
def number_of_special_entries(self) -> int:
'\n Return the number of special entries. See :meth:`special_entries()`.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[4,2,1],[4,1],[2]])\n sage: G.number_of_special_entries()\n 1\n '
return len(self.special_entries())
def is_strict(self) -> bool:
'\n Return ``True`` if ``self`` is a strict Gelfand-Tsetlin pattern.\n\n A Gelfand-Tsetlin pattern is said to be *strict* if every row is\n strictly decreasing.\n\n EXAMPLES::\n\n sage: GelfandTsetlinPattern([[7,3,1],[6,2],[4]]).is_strict()\n True\n sage: GelfandTsetlinPattern([[3,2,1],[3,1],[1]]).is_strict()\n True\n sage: GelfandTsetlinPattern([[6,0,0],[3,0],[2]]).is_strict()\n False\n '
return (not any(((row[i] == row[(i + 1)]) for row in self for i in range((len(row) - 1)))))
def row_sums(self) -> list:
'\n Return the list of row sums.\n\n For a Gelfand-Tsetlin pattern `G`, the `i`-th row sum `d_i` is\n\n .. MATH::\n\n d_i = d_i(G) = \\sum_{j=i}^{n} a_{i,j}.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[5,3,2,1,0],[4,3,2,0],[4,2,1],[3,2],[3]])\n sage: G.row_sums()\n [11, 9, 7, 5, 3]\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[2]])\n sage: G.row_sums()\n [6, 4, 2]\n '
return [sum((self[i][j] for j in range(len(self[i])))) for i in range(len(self))]
def weight(self) -> tuple:
'\n Return the weight of ``self``.\n\n Define the weight of `G` to be the content of the tableau to which `G`\n corresponds under the bijection between Gelfand-Tsetlin patterns and\n semistandard tableaux. More precisely,\n\n .. MATH::\n\n \\mathrm{wt}(G) = (d_n, d_{n-1}-d_n, \\dots, d_1-d_2),\n\n where the `d_i` are the row sums.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[2,1,0],[1,0],[1]])\n sage: G.weight()\n (1, 0, 2)\n sage: G = GelfandTsetlinPattern([[4,2,1],[3,1],[2]])\n sage: G.weight()\n (2, 2, 3)\n '
wt = ([self.row_sums()[(- 1)]] + [(self.row_sums()[(i - 1)] - self.row_sums()[i]) for i in reversed(range(1, len(self[0])))])
return tuple(wt)
def Tokuyama_coefficient(self, name='t'):
"\n Return the Tokuyama coefficient attached to ``self``.\n\n Following the exposition of [BBF]_, Tokuyama's formula asserts\n\n .. MATH::\n\n \\sum_{G} (t+1)^{s(G)} t^{l(G)}\n z_1^{d_{n+1}} z_2^{d_{n}-d_{n+1}} \\cdots z_{n+1}^{d_1-d_2}\n =\n s_{\\lambda}(z_1,\\dots,z_{n+1}) \\prod_{i<j} (z_j+tz_i),\n\n where the sum is over all strict Gelfand-Tsetlin patterns with fixed\n top row `\\lambda + \\rho`, with `\\lambda` a partition with at most\n `n+1` parts and `\\rho = (n, n-1, \\ldots, 1, 0)`, and `s_\\lambda` is a\n Schur function.\n\n INPUT:\n\n - ``name`` -- (Default: ``'t'``) An alternative name for the\n variable `t`.\n\n EXAMPLES::\n\n sage: P = GelfandTsetlinPattern([[3,2,1],[2,2],[2]])\n sage: P.Tokuyama_coefficient()\n 0\n sage: G = GelfandTsetlinPattern([[3,2,1],[3,1],[2]])\n sage: G.Tokuyama_coefficient()\n t^2 + t\n sage: G = GelfandTsetlinPattern([[2,1,0],[1,1],[1]])\n sage: G.Tokuyama_coefficient()\n 0\n sage: G = GelfandTsetlinPattern([[5,3,2,1,0],[4,3,2,0],[4,2,1],[3,2],[3]])\n sage: G.Tokuyama_coefficient()\n t^8 + 3*t^7 + 3*t^6 + t^5\n "
R = PolynomialRing(ZZ, name)
t = R.gen(0)
if (not self.is_strict()):
return R.zero()
return (((t + 1) ** self.number_of_special_entries()) * (t ** self.number_of_boxes()))
@combinatorial_map(order=2, name='Bender-Knuth involution')
def bender_knuth_involution(self, i) -> GelfandTsetlinPattern:
'\n Return the image of ``self`` under the `i`-th Bender-Knuth involution.\n\n If the triangle ``self`` has size `n` then this is defined for `0 < i < n`.\n\n The entries of ``self`` can take values in any ordered ring. Usually,\n this will be the integers but can also be the rationals or the real numbers.\n\n This implements the construction of the Bender-Knuth involution using toggling\n due to Berenstein-Kirillov.\n\n This agrees with the Bender-Knuth involution on semistandard tableaux.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPattern([[5,3,2,1,0],[4,3,2,0],[4,2,1],[3,2],[3]])\n sage: G.bender_knuth_involution(2)\n [[5, 3, 2, 1, 0], [4, 3, 2, 0], [4, 2, 1], [4, 1], [3]]\n\n sage: G = GelfandTsetlinPattern([[3,2,0],[2.2,0],[2]])\n sage: G.bender_knuth_involution(2)\n [[3, 2, 0], [2.80000000000000, 2], [2]]\n\n TESTS::\n\n sage: all(all( G.bender_knuth_involution(i).to_tableau() == G.to_tableau().bender_knuth_involution(i)\n ....: for i in range(1,len(G)) ) for G in GelfandTsetlinPatterns(top_row=[3,3,3,0,0]))\n True\n\n sage: G = GelfandTsetlinPattern([[2,1,0],[1,0],[0]])\n sage: G.bender_knuth_involution(0)\n Traceback (most recent call last):\n ...\n ValueError: must have 0 < 0 < 3\n sage: G.bender_knuth_involution(3)\n Traceback (most recent call last):\n ...\n ValueError: must have 0 < 3 < 3\n '
n = len(self)
def toggle(i, j):
"\n Return the toggle of entry 'G[i][j]' in a Gelfand-Tsetlin pattern, 'G'.\n "
if (i == (n - 1)):
return ((self[(n - 2)][0] + self[(n - 2)][1]) - self[(n - 1)][0])
if (j == 0):
left = self[(i - 1)][0]
else:
left = min(self[(i - 1)][j], self[(i + 1)][(j - 1)])
if (j == ((n - i) - 1)):
right = self[(i - 1)][(j + 1)]
else:
right = max(self[(i - 1)][(j + 1)], self[(i + 1)][j])
return ((left + right) - self[i][j])
if (not (0 < i < n)):
raise ValueError(f'must have 0 < {i} < {n}')
r = (n - i)
P = self.parent()
data = [list(row) for row in self]
data[r] = [toggle(r, s) for s in range(i)]
return P.element_class(P, data)
|
class GelfandTsetlinPatterns(UniqueRepresentation, Parent):
'\n Gelfand-Tsetlin patterns.\n\n INPUT:\n\n - ``n`` -- The width or depth of the array, also known as the rank\n\n - ``k`` -- (Default: ``None``) If specified, this is the maximum value that\n can occur in the patterns\n\n - ``top_row`` -- (Default: ``None``) If specified, this is the fixed top\n row of all patterns\n\n - ``strict`` -- (Default: ``False``) Set to ``True`` if all patterns are\n strict patterns\n\n TESTS:\n\n Check that the number of Gelfand-Tsetlin patterns is equal to the number\n of semistandard Young tableaux::\n\n sage: G = GelfandTsetlinPatterns(3,3)\n sage: c = 0\n sage: from sage.combinat.crystals.kirillov_reshetikhin import partitions_in_box\n sage: for p in partitions_in_box(3,3):\n ....: S = SemistandardTableaux(p, max_entry=3)\n ....: c += S.cardinality()\n sage: c == G.cardinality()\n True\n\n Note that the top row in reverse of the Gelfand-Tsetlin pattern is the\n shape of the corresponding semistandard Young tableau under the bijection\n described in :meth:`GelfandTsetlinPattern.to_tableau()`::\n\n sage: G = GelfandTsetlinPatterns(top_row=[2,2,1])\n sage: S = SemistandardTableaux([2,2,1], max_entry=3)\n sage: G.cardinality() == S.cardinality()\n True\n '
@staticmethod
def __classcall_private__(cls, n=None, k=None, strict=False, top_row=None):
'\n Return the correct parent based upon the inputs.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: G2 = GelfandTsetlinPatterns()\n sage: G is G2\n True\n sage: G = GelfandTsetlinPatterns(3,4, strict=True)\n sage: G2 = GelfandTsetlinPatterns(int(3),int(4), strict=True)\n sage: G is G2\n True\n sage: G = GelfandTsetlinPatterns(top_row=[3,1,1])\n sage: G2 = GelfandTsetlinPatterns(top_row=(3,1,1))\n sage: G is G2\n True\n '
if (top_row is not None):
top_row = tuple(top_row)
if any(((top_row[i] < top_row[(i + 1)]) for i in range((len(top_row) - 1)))):
raise ValueError('the top row must be weakly decreasing')
if ((n is not None) and (n != len(top_row))):
raise ValueError('n must be the length of the specified top row')
return GelfandTsetlinPatternsTopRow(top_row, strict)
return super().__classcall__(cls, n, k, strict)
def __init__(self, n, k, strict):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: TestSuite(G).run()\n sage: G = GelfandTsetlinPatterns(3)\n sage: TestSuite(G).run()\n sage: G = GelfandTsetlinPatterns(3, 3)\n sage: TestSuite(G).run()\n sage: G = GelfandTsetlinPatterns(3, 3, strict=True)\n sage: TestSuite(G).run()\n '
self._n = n
self._k = k
self._strict = strict
if ((k is not None) and ((n is not None) or strict)):
Parent.__init__(self, category=FiniteEnumeratedSets())
else:
Parent.__init__(self, category=InfiniteEnumeratedSets())
def __contains__(self, gt):
'\n Check to see if ``gt`` is in ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns()\n sage: [[3, 1],[2]] in G\n True\n sage: [[2, 3],[4]] in G\n False\n sage: [[3, 1],[0]] in G\n False\n sage: [] in G\n True\n sage: G = GelfandTsetlinPatterns(3,2)\n sage: [] in G\n False\n sage: [[2,0,0],[1,0],[1]] in G\n True\n sage: [[0,0],[0]] in G\n False\n sage: [[3,0,0],[2,0],[0]] in G\n False\n sage: G = GelfandTsetlinPatterns(3,strict=True)\n sage: [[2,1,0],[2,1],[1]] in G\n True\n sage: [[3,0,0],[3,0],[0]] in G\n False\n '
if (not isinstance(gt, (list, tuple, GelfandTsetlinPattern))):
return False
if ((self._n is not None) and (len(gt) != self._n)):
return False
if ((self._k is not None) and any(((val > self._k) for row in gt for val in row))):
return False
if (not all(((gt[(i - 1)][j] >= gt[i][j] >= gt[(i - 1)][(j + 1)]) for i in range(1, len(gt)) for j in range(len(gt[i]))))):
return False
if (self._strict and any(((gt[i][j] == gt[i][(j - 1)]) for i in range(len(gt)) for j in range(1, len(gt[i]))))):
return False
return True
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: GelfandTsetlinPatterns(4)\n Gelfand-Tsetlin patterns of width 4\n sage: GelfandTsetlinPatterns(4, 3, strict=True)\n Strict Gelfand-Tsetlin patterns of width 4 and max value 3\n sage: G = GelfandTsetlinPatterns(k=3, strict=True); G\n Strict Gelfand-Tsetlin patterns with max value 3\n '
base = 'Gelfand-Tsetlin patterns'
if self._strict:
base = ('Strict ' + base)
if (self._n is not None):
if (self._k is not None):
return (base + (' of width %s and max value %s' % (self._n, self._k)))
return (base + (' of width %s' % self._n))
if (self._k is not None):
return (base + (' with max value %s' % self._k))
return base
def _element_constructor_(self, gt):
'\n Construct an element of ``self`` from ``gt``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(3, 3, strict=True); G\n Strict Gelfand-Tsetlin patterns of width 3 and max value 3\n sage: elt = G([[3,2,1],[2,1],[1]]); elt.pp()\n 3 2 1\n 2 1\n 1\n sage: elt.parent()\n Strict Gelfand-Tsetlin patterns of width 3 and max value 3\n '
if (isinstance(gt, GelfandTsetlinPattern) and (gt.parent() == self)):
return gt
if isinstance(gt, Tableau):
gt = [list(x) for x in reversed(gt.to_chain()[1:])]
n = len(gt)
for i in range(n):
while (len(gt[i]) < (n - i)):
gt[i].append(0)
if (self._n is not None):
if (len(gt) == 0):
gt = [[0]]
while (self._n != len(gt)):
gt.insert(0, (gt[0][:] + [0]))
return self.element_class(self, gt)
return self.element_class(self, list(gt))
Element = GelfandTsetlinPattern
def _coerce_map_from_(self, S):
'\n TESTS::\n\n sage: t = GelfandTsetlinPattern([[1]])\n sage: t == 0\n False\n sage: t == GelfandTsetlinPattern([[1]])\n True\n\n Check that :trac:`25919` is fixed::\n\n sage: t = GelfandTsetlinPattern([[1]])\n sage: u = GelfandTsetlinPatterns()[1]\n sage: v = GelfandTsetlinPatterns(top_row=(1,))[0]\n sage: t == u\n True\n sage: u == t\n True\n sage: t == v\n True\n sage: v == t\n True\n sage: u == v\n True\n sage: v == u\n True\n '
if isinstance(S, GelfandTsetlinPatternsTopRow):
return True
def __iter__(self):
'\n Iterate through ``self`` by using a backtracing algorithm.\n\n EXAMPLES::\n\n sage: L = list(GelfandTsetlinPatterns(3,3))\n sage: c = 0\n sage: from sage.combinat.crystals.kirillov_reshetikhin import partitions_in_box\n sage: for p in partitions_in_box(3,3):\n ....: S = SemistandardTableaux(p, max_entry=3)\n ....: c += S.cardinality()\n sage: c == len(L)\n True\n sage: G = GelfandTsetlinPatterns(3, 3, strict=True)\n sage: all(x.is_strict() for x in G)\n True\n sage: G = GelfandTsetlinPatterns(k=3, strict=True)\n sage: all(x.is_strict() for x in G)\n True\n\n Checking iterator when the set is infinite::\n\n sage: T = GelfandTsetlinPatterns()\n sage: it = T.__iter__()\n sage: [next(it) for i in range(10)]\n [[],\n [[1]],\n [[2]],\n [[1, 1], [1]],\n [[3]],\n [[2, 1], [1]],\n [[2, 1], [2]],\n [[1, 1, 1], [1, 1], [1]],\n [[4]],\n [[3, 1], [1]]]\n sage: T = GelfandTsetlinPatterns(k=1)\n sage: it = T.__iter__()\n sage: [next(it) for i in range(10)]\n [[],\n [[0]],\n [[1]],\n [[0, 0], [0]],\n [[1, 0], [0]],\n [[1, 0], [1]],\n [[1, 1], [1]],\n [[0, 0, 0], [0, 0], [0]],\n [[1, 0, 0], [0, 0], [0]],\n [[1, 0, 0], [1, 0], [0]]]\n\n Check that :trac:`14718` is fixed::\n\n sage: T = GelfandTsetlinPatterns(1,3)\n sage: list(T)\n [[[0]],\n [[1]],\n [[2]],\n [[3]]]\n '
if (self._n is None):
(yield self.element_class(self, []))
if (self._k is None):
n = 1
while True:
if self._strict:
P = Partitions(n, max_slope=(- 1))
else:
P = Partitions(n)
for p in P:
for x in GelfandTsetlinPatterns(top_row=tuple(p), strict=self._strict):
(yield self.element_class(self, list(x)))
n += 1
for x in range((self._k + 1)):
(yield self.element_class(self, [[x]]))
n = 2
while ((not self._strict) or (n <= (self._k + 1))):
for x in self._list_iter(n):
(yield self.element_class(self, x))
n += 1
return
if (self._n < 0):
return
if (self._n == 0):
(yield self.element_class(self, []))
return
if (self._n == 1):
if (self._k is not None):
for x in range((self._k + 1)):
(yield self.element_class(self, [[x]]))
else:
k = 1
while True:
(yield self.element_class(self, [[k]]))
k += 1
return
for x in self._list_iter(self._n):
(yield self.element_class(self, x))
def _list_iter(self, n):
"\n Fast iterator which returns Gelfand-Tsetlin patterns of width ``n`` as\n lists of lists.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(3, 1)\n sage: L = [x for x in G._list_iter(3)]\n sage: len(L) == G.cardinality()\n True\n sage: type(L[0])\n <class 'list'>\n "
iters = ([None] * n)
ret = ([None] * n)
iters[0] = self._top_row_iter(n)
ret[0] = next(iters[0])
min_pos = 0
iters[1] = self._row_iter(ret[0])
pos = 1
while (pos >= min_pos):
try:
ret[pos] = next(iters[pos])
pos += 1
if (pos == n):
(yield ret[:])
pos -= 1
continue
iters[pos] = self._row_iter(ret[(pos - 1)])
except StopIteration:
pos -= 1
def _top_row_iter(self, n):
'\n Helper iterator for the top row.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(3, 1)\n sage: for x in G._top_row_iter(3): x\n [0, 0, 0]\n [1, 0, 0]\n [1, 1, 0]\n [1, 1, 1]\n sage: G = GelfandTsetlinPatterns(3, 2, strict=True)\n sage: for x in G._top_row_iter(3): x\n [2, 1, 0]\n '
row = ([(- 1)] * n)
pos = 0
while (pos >= 0):
if (pos == n):
(yield row[:])
pos -= 1
continue
if (((pos > 0) and ((row[pos] >= row[(pos - 1)]) or (self._strict and (row[pos] == (row[(pos - 1)] - 1))))) or ((self._k is not None) and (row[pos] >= self._k))):
row[pos] = (- 1)
pos -= 1
continue
row[pos] += 1
pos += 1
def _row_iter(self, upper_row):
'\n Helper iterator for any row with a row above it.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(3, 4)\n sage: for x in G._row_iter([4,2,1]): x\n [2, 1]\n [2, 2]\n [3, 1]\n [3, 2]\n [4, 1]\n [4, 2]\n sage: G = GelfandTsetlinPatterns(3, 2, strict=True)\n sage: for x in G._row_iter([2, 1, 0]): x\n [1, 0]\n [2, 0]\n [2, 1]\n '
row = [(x - 1) for x in upper_row[1:]]
row_len = len(row)
pos = 0
while (pos >= 0):
if (pos == row_len):
(yield row[:])
pos -= 1
continue
if (((pos > 0) and ((row[pos] >= row[(pos - 1)]) or (self._strict and (row[pos] == (row[(pos - 1)] - 1))))) or (row[pos] >= upper_row[pos]) or ((self._k is not None) and (row[pos] >= self._k))):
row[pos] = (upper_row[(pos + 1)] - 1)
pos -= 1
continue
row[pos] += 1
pos += 1
def _toggle_markov_chain(self, chain_state, row, col, direction):
'\n Helper for coupling from the past. Advance the Markov chain one step.\n\n INPUT:\n\n - ``chain_state`` -- A GelfandTsetlin pattern represented as a list of lists\n - ``row`` -- The row of the cell being modified\n - ``col`` -- The column of the cell being modified\n - ``direction`` -- The direction to change the cell 1 = increase, 0 = decrease\n\n OUTPUT:\n\n ``chain_state`` is possibly modified.\n\n TESTS:\n\n sage: G = GelfandTsetlinPatterns(3,4)\n sage: state = [[3,2,1],[3,1],[2]]\n sage: G._toggle_markov_chain(state, 0, 0, 1)\n sage: state\n [[4, 2, 1], [3, 1], [2]]\n sage: G._toggle_markov_chain(state, 1, 1, 1)\n sage: state\n [[4, 2, 1], [3, 2], [2]]\n sage: G._toggle_markov_chain(state, 0, 2, 1)\n sage: state\n [[4, 2, 2], [3, 2], [2]]\n sage: G._toggle_markov_chain(state, 0, 2, 1)\n sage: state\n [[4, 2, 2], [3, 2], [2]]\n sage: G._toggle_markov_chain(state, 0, 2, 0)\n sage: state\n [[4, 2, 1], [3, 2], [2]]\n sage: G._toggle_markov_chain(state, 0, 2, 0)\n sage: state\n [[4, 2, 0], [3, 2], [2]]\n sage: G._toggle_markov_chain(state, 0, 2, 0)\n sage: state\n [[4, 2, 0], [3, 2], [2]]\n '
if (direction == 1):
upbound = self._k
if (row != 0):
upbound = min(upbound, chain_state[(row - 1)][col])
if (self._strict and (col > 0)):
upbound = min(upbound, (chain_state[row][(col - 1)] - 1))
if ((row < self._n) and (col > 0)):
upbound = min(upbound, chain_state[(row + 1)][(col - 1)])
if (chain_state[row][col] < upbound):
chain_state[row][col] += 1
else:
lobound = 0
if (row != 0):
lobound = max(lobound, chain_state[(row - 1)][(col + 1)])
if (self._strict and (col < ((self._n - row) - 1))):
lobound = max(lobound, (chain_state[row][(col + 1)] + 1))
if ((row < self._n) and (col < ((self._n - row) - 1))):
lobound = max(lobound, chain_state[(row + 1)][col])
if (chain_state[row][col] > lobound):
chain_state[row][col] -= 1
def _cftp_upper(self):
'\n Return the largest member of the poset of Gelfand-Tsetlin patterns having the given ``n`` and ``k``.\n\n TESTS::\n\n sage: GelfandTsetlinPatterns(3, 5)._cftp_upper()\n [[5, 5, 5], [5, 5], [5]]\n sage: GelfandTsetlinPatterns(3, 5, strict=True)._cftp_upper()\n [[5, 4, 3], [5, 4], [5]]\n '
if self._strict:
return [[(self._k - j) for j in range((self._n - i))] for i in range(self._n)]
else:
return [[self._k for j in range((self._n - i))] for i in range(self._n)]
def _cftp_lower(self):
'\n Return the smallest member of the poset of Gelfand-Tsetlin patterns having the given ``n`` and ``k``.\n\n TESTS::\n\n sage: GelfandTsetlinPatterns(3, 5)._cftp_lower()\n [[0, 0, 0], [0, 0], [0]]\n sage: GelfandTsetlinPatterns(3, 5, strict=True)._cftp_lower()\n [[2, 1, 0], [1, 0], [0]]\n '
if self._strict:
return [[(((self._n - j) - i) - 1) for j in range((self._n - i))] for i in range(self._n)]
else:
return [[0 for j in range((self._n - i))] for i in range(self._n)]
def _cftp(self, start_row):
'\n Implement coupling from the past.\n\n ALGORITHM:\n\n The set of Gelfand-Tsetlin patterns can partially ordered by\n elementwise domination. The partial order has unique maximum\n and minimum elements that are computed by the methods\n :meth:`_cftp_upper` and :meth:`_cftp_lower`. We then run the Markov\n chain that randomly toggles each element up or down from the\n past until the state reached from the upper and lower start\n points coalesce as described in [Propp1997]_.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(3, 5)\n sage: G._cftp(0) # random\n [[5, 3, 2], [4, 2], [3]]\n sage: G._cftp(0) in G\n True\n '
from sage.misc.randstate import current_randstate
from sage.misc.randstate import seed, random
count = (self._n * self._k)
seedlist = [(current_randstate().long_seed(), count)]
upper = []
lower = []
while True:
upper = self._cftp_upper()
lower = self._cftp_lower()
for (currseed, count) in seedlist:
with seed(currseed):
for _ in range(count):
for row in range(start_row, self._n):
for col in range((self._n - row)):
direction = (random() % 2)
self._toggle_markov_chain(upper, row, col, direction)
self._toggle_markov_chain(lower, row, col, direction)
if all(((x == y) for (l1, l2) in zip(upper, lower) for (x, y) in zip(l1, l2))):
break
count = (seedlist[0][1] * 2)
seedlist.insert(0, (current_randstate().long_seed(), count))
return GelfandTsetlinPattern(upper)
def random_element(self) -> GelfandTsetlinPattern:
'\n Return a uniformly random Gelfand-Tsetlin pattern.\n\n EXAMPLES::\n\n sage: g = GelfandTsetlinPatterns(4, 5)\n sage: x = g.random_element()\n sage: x in g\n True\n sage: len(x)\n 4\n sage: all(y in range(5+1) for z in x for y in z)\n True\n sage: x.check()\n\n ::\n\n sage: g = GelfandTsetlinPatterns(4, 5, strict=True)\n sage: x = g.random_element()\n sage: x in g\n True\n sage: len(x)\n 4\n sage: all(y in range(5+1) for z in x for y in z)\n True\n sage: x.check()\n sage: x.is_strict()\n True\n '
if ((self._n is not None) and (self._k is not None)):
if (self._strict and ((self._k + 1) < self._n)):
raise ValueError('cannot sample from empty set')
elif (self._k < 0):
raise ValueError('cannot sample from empty set')
else:
return self._cftp(0)
else:
raise ValueError('cannot sample from infinite set')
|
class GelfandTsetlinPatternsTopRow(GelfandTsetlinPatterns):
'\n Gelfand-Tsetlin patterns with a fixed top row.\n '
def __init__(self, top_row, strict):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(top_row=[4,4,3,1])\n sage: TestSuite(G).run()\n\n TESTS:\n\n Check a border case in :trac:`14765`::\n\n sage: G = GelfandTsetlinPatterns(top_row=[])\n sage: list(G)\n [[]]\n '
self._row = top_row
n = len(top_row)
if (n == 0):
k = 0
else:
k = top_row[0]
GelfandTsetlinPatterns.__init__(self, n, k, strict)
def _repr_(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: GelfandTsetlinPatterns(top_row=[4,4,3,1])\n Gelfand-Tsetlin patterns with top row [4, 4, 3, 1]\n sage: GelfandTsetlinPatterns(top_row=[5,4,3,1], strict=True)\n Strict Gelfand-Tsetlin patterns with top row [5, 4, 3, 1]\n '
base = ('Gelfand-Tsetlin patterns with top row %s' % list(self._row))
if self._strict:
base = ('Strict ' + base)
return base
def __contains__(self, gt) -> bool:
'\n Check if ``gt`` is in ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(top_row=[4,4,1])\n sage: [[4,4,1], [4,2], [3]] in G\n True\n sage: [[4,3,1], [4,2], [3]] in G\n False\n '
if (gt and (tuple(gt[0]) != self._row)):
return False
return GelfandTsetlinPatterns.__contains__(self, gt)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(top_row=[4,2,1])\n sage: list(G)\n [[[4, 2, 1], [2, 1], [1]],\n [[4, 2, 1], [2, 1], [2]],\n [[4, 2, 1], [2, 2], [2]],\n [[4, 2, 1], [3, 1], [1]],\n [[4, 2, 1], [3, 1], [2]],\n [[4, 2, 1], [3, 1], [3]],\n [[4, 2, 1], [3, 2], [2]],\n [[4, 2, 1], [3, 2], [3]],\n [[4, 2, 1], [4, 1], [1]],\n [[4, 2, 1], [4, 1], [2]],\n [[4, 2, 1], [4, 1], [3]],\n [[4, 2, 1], [4, 1], [4]],\n [[4, 2, 1], [4, 2], [2]],\n [[4, 2, 1], [4, 2], [3]],\n [[4, 2, 1], [4, 2], [4]]]\n '
if (self._strict and any(((self._row[i] == self._row[(i + 1)]) for i in range((self._n - 1))))):
return
if (self._n == 0):
(yield self.element_class(self, []))
return
if (self._n == 1):
(yield self.element_class(self, [list(self._row)]))
return
iters = ([None] * self._n)
ret = ([None] * self._n)
ret[0] = list(self._row)
min_pos = 1
iters[1] = self._row_iter(ret[0])
pos = 1
while (pos >= min_pos):
try:
ret[pos] = next(iters[pos])
pos += 1
if (pos == self._n):
(yield self.element_class(self, ret[:]))
pos -= 1
continue
iters[pos] = self._row_iter(ret[(pos - 1)])
except StopIteration:
pos -= 1
def top_row(self):
'\n Return the top row of ``self``.\n\n EXAMPLES::\n\n sage: G = GelfandTsetlinPatterns(top_row=[4,4,3,1])\n sage: G.top_row()\n (4, 4, 3, 1)\n '
return self._row
def Tokuyama_formula(self, name='t'):
"\n Return the Tokuyama formula of ``self``.\n\n Following the exposition of [BBF]_, Tokuyama's formula asserts\n\n .. MATH::\n\n \\sum_{G} (t+1)^{s(G)} t^{l(G)}\n z_1^{d_{n+1}} z_2^{d_{n}-d_{n+1}} \\cdots z_{n+1}^{d_1-d_2}\n = s_{\\lambda} (z_1, \\ldots, z_{n+1}) \\prod_{i<j} (z_j+tz_i),\n\n where the sum is over all strict Gelfand-Tsetlin patterns with fixed\n top row `\\lambda+\\rho`, with `\\lambda` a partition with at most\n `n+1` parts and `\\rho = (n,n-1,\\dots,1,0)`, and `s_{\\lambda}` is a Schur\n function.\n\n INPUT:\n\n - ``name`` -- (Default: ``'t'``) An alternative name for the\n variable `t`.\n\n EXAMPLES::\n\n sage: GT = GelfandTsetlinPatterns(top_row=[2,1,0],strict=True)\n sage: GT.Tokuyama_formula()\n t^3*x1^2*x2 + t^2*x1*x2^2 + t^2*x1^2*x3 + t^2*x1*x2*x3 + t*x1*x2*x3 + t*x2^2*x3 + t*x1*x3^2 + x2*x3^2\n sage: GT = GelfandTsetlinPatterns(top_row=[3,2,1],strict=True)\n sage: GT.Tokuyama_formula()\n t^3*x1^3*x2^2*x3 + t^2*x1^2*x2^3*x3 + t^2*x1^3*x2*x3^2 + t^2*x1^2*x2^2*x3^2 + t*x1^2*x2^2*x3^2 + t*x1*x2^3*x3^2 + t*x1^2*x2*x3^3 + x1*x2^2*x3^3\n sage: GT = GelfandTsetlinPatterns(top_row=[1,1,1],strict=True)\n sage: GT.Tokuyama_formula()\n 0\n "
n = self._n
variables = ([name] + [('x%d' % i) for i in range(1, (n + 1))])
R = PolynomialRing(ZZ, names=variables)
t = R.gen(0)
x = R.gens()[1:]
GT = GelfandTsetlinPatterns(top_row=self._row, strict=True)
return sum((((((t + 1) ** gt.number_of_special_entries()) * (t ** gt.number_of_boxes())) * prod(((x[i] ** gt.weight()[i]) for i in range(n)))) for gt in GT))
def _cftp_upper(self) -> list:
'\n Return the largest member of the poset of Gelfand-Tsetlin patterns having the given ``top_row``.\n\n TESTS::\n\n sage: GelfandTsetlinPatterns(top_row = [5, 4, 3])._cftp_upper()\n [[5, 4, 3], [5, 4], [5]]\n '
return [[self._row[j] for j in range((self._n - i))] for i in range(self._n)]
def _cftp_lower(self) -> list:
'\n Return the smallest member of the poset of Gelfand-Tsetlin patterns having the given ``top_row``.\n\n TESTS::\n\n sage: GelfandTsetlinPatterns(top_row = [5, 4, 3])._cftp_lower()\n [[5, 4, 3], [4, 3], [3]]\n '
return [[self._row[(i + j)] for j in range((self._n - i))] for i in range(self._n)]
def random_element(self) -> GelfandTsetlinPattern:
'\n Return a uniformly random Gelfand-Tsetlin pattern with specified top row.\n\n EXAMPLES::\n\n sage: g = GelfandTsetlinPatterns(top_row = [4, 3, 1, 1])\n sage: x = g.random_element()\n sage: x in g\n True\n sage: x[0] == [4, 3, 1, 1]\n True\n sage: x.check()\n\n sage: g = GelfandTsetlinPatterns(top_row=[4, 3, 2, 1], strict=True)\n sage: x = g.random_element()\n sage: x in g\n True\n sage: x[0] == [4, 3, 2, 1]\n True\n sage: x.is_strict()\n True\n sage: x.check()\n '
if self._strict:
return self._cftp(1)
l = [i for i in self._row if (i > 0)]
return SemistandardTableaux(l, max_entry=self._n).random_element().to_Gelfand_Tsetlin_pattern()
|
def GraphPaths(g, source=None, target=None):
'\n Return the combinatorial class of paths in the directed acyclic graph g.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n\n If source and target are not given, then the returned class\n contains all paths (including trivial paths containing only one\n vertex).\n\n ::\n\n sage: p = GraphPaths(G); p\n Paths in Multi-digraph on 5 vertices\n sage: p.cardinality()\n 37\n sage: path = p.random_element()\n sage: all(G.has_edge(*path[i:i+2]) for i in range(len(path) -1))\n True\n\n If the source is specified, then the returned class contains all of\n the paths starting at the vertex source (including the trivial\n path).\n\n ::\n\n sage: p = GraphPaths(G, source=3); p\n Paths in Multi-digraph on 5 vertices starting at 3\n sage: p.list()\n [[3], [3, 4], [3, 4, 5], [3, 4, 5]]\n\n If the target is specified, then the returned class contains all of\n the paths ending at the vertex target (including the trivial\n path).\n\n ::\n\n sage: p = GraphPaths(G, target=3); p\n Paths in Multi-digraph on 5 vertices ending at 3\n sage: p.cardinality()\n 5\n sage: p.list()\n [[3], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3]]\n\n If both the target and source are specified, then the returned\n class contains all of the paths from source to target.\n\n ::\n\n sage: p = GraphPaths(G, source=1, target=3); p\n Paths in Multi-digraph on 5 vertices starting at 1 and ending at 3\n sage: p.cardinality()\n 3\n sage: p.list()\n [[1, 2, 3], [1, 2, 3], [1, 3]]\n\n Note that G must be a directed acyclic graph.\n\n ::\n\n sage: G = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[2,5,7], 5:[6]}, multiedges=True)\n sage: GraphPaths(G)\n Traceback (most recent call last):\n ...\n TypeError: g must be a directed acyclic graph\n '
if (not isinstance(g, digraph.DiGraph)):
raise TypeError('g must be a DiGraph')
elif (not g.is_directed_acyclic()):
raise TypeError('g must be a directed acyclic graph')
if ((source is None) and (target is None)):
return GraphPaths_all(g)
elif ((source is not None) and (target is None)):
if (source not in g):
raise ValueError('source must be in g')
return GraphPaths_s(g, source)
elif ((source is None) and (target is not None)):
if (target not in g):
raise ValueError('target must be in g')
return GraphPaths_t(g, target)
else:
if (source not in g):
raise ValueError('source must be in g')
if (target not in g):
raise ValueError('target must be in g')
return GraphPaths_st(g, source, target)
|
class GraphPaths_common():
def __eq__(self, other):
'\n Test for equality.\n\n EXAMPLES::\n\n sage: G1 = DiGraph({1:[2,3], 2:[3]})\n sage: p1 = GraphPaths(G1)\n sage: G2 = DiGraph({2:[3], 3:[4]})\n sage: p2 = GraphPaths(G2)\n sage: p1 == p1\n True\n sage: p1 == p2\n False\n '
if (not isinstance(other, GraphPaths_common)):
return False
return (self.graph == other.graph)
def __ne__(self, other):
'\n Test for unequality.\n\n EXAMPLES::\n\n sage: G1 = DiGraph({1:[2,3], 2:[3]})\n sage: p1 = GraphPaths(G1)\n sage: G2 = DiGraph({2:[3], 3:[4]})\n sage: p2 = GraphPaths(G2)\n sage: p1 != p2\n True\n sage: p1 != p1\n False\n '
return (not (self == other))
def outgoing_edges(self, v):
"\n Return a list of v's outgoing edges.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G)\n sage: p.outgoing_edges(2)\n [(2, 3, None), (2, 4, None)]\n "
return list(self.graph.outgoing_edge_iterator(v))
def incoming_edges(self, v):
"\n Return a list of v's incoming edges.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G)\n sage: p.incoming_edges(2)\n [(1, 2, None), (1, 2, None)]\n "
return list(self.graph.incoming_edge_iterator(v))
def outgoing_paths(self, v):
'\n Return a list of the paths that start at v.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: gp = GraphPaths(G)\n sage: gp.outgoing_paths(3)\n [[3], [3, 4], [3, 4, 5], [3, 4, 5]]\n sage: gp.outgoing_paths(2)\n [[2],\n [2, 3],\n [2, 3, 4],\n [2, 3, 4, 5],\n [2, 3, 4, 5],\n [2, 4],\n [2, 4, 5],\n [2, 4, 5]]\n '
source_paths = [[v]]
for e in self.outgoing_edges(v):
target = e[1]
target_paths = self.outgoing_paths(target)
target_paths = [([v] + path) for path in target_paths]
source_paths += target_paths
return source_paths
def incoming_paths(self, v):
'\n Return a list of paths that end at v.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: gp = GraphPaths(G)\n sage: gp.incoming_paths(2)\n [[2], [1, 2], [1, 2]]\n '
target_paths = [[v]]
for e in self.incoming_edges(v):
source = e[0]
source_paths = self.incoming_paths(source)
source_paths = [(path + [v]) for path in source_paths]
target_paths += source_paths
return target_paths
def paths_from_source_to_target(self, source, target):
'\n Return a list of paths from source to target.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: gp = GraphPaths(G)\n sage: gp.paths_from_source_to_target(2,4)\n [[2, 3, 4], [2, 4]]\n '
source_paths = self.outgoing_paths(source)
paths = []
for path in source_paths:
if (path[(- 1)] == target):
paths.append(path)
return paths
def paths(self):
'\n Return a list of all the paths of ``self``.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: gp = GraphPaths(G)\n sage: len(gp.paths())\n 37\n '
paths = []
for source in self.graph.vertex_iterator():
paths += self.outgoing_paths(source)
return paths
|
class GraphPaths_all(Parent, GraphPaths_common):
'\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G)\n sage: p.cardinality()\n 37\n '
def __init__(self, g):
'\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G)\n sage: p == loads(dumps(p))\n True\n '
self.graph = g
Parent.__init__(self, category=FiniteEnumeratedSets())
def __repr__(self):
"\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G)\n sage: repr(p)\n 'Paths in Multi-digraph on 5 vertices'\n "
return ('Paths in %s' % repr(self.graph))
def list(self):
'\n Return a list of the paths of ``self``.\n\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: len(GraphPaths(G).list())\n 37\n '
return self.paths()
|
class GraphPaths_t(Parent, GraphPaths_common):
def __init__(self, g, target):
'\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, target=4)\n sage: p == loads(dumps(p))\n True\n '
self.graph = g
self.target = target
Parent.__init__(self, category=FiniteEnumeratedSets())
def __repr__(self):
"\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, target=4)\n sage: repr(p)\n 'Paths in Multi-digraph on 5 vertices ending at 4'\n "
return ('Paths in %s ending at %s' % (repr(self.graph), self.target))
def list(self):
'\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, target=4)\n sage: p.list()\n [[4],\n [2, 4],\n [1, 2, 4],\n [1, 2, 4],\n [3, 4],\n [1, 3, 4],\n [2, 3, 4],\n [1, 2, 3, 4],\n [1, 2, 3, 4]]\n '
return self.incoming_paths(self.target)
|
class GraphPaths_s(Parent, GraphPaths_common):
def __init__(self, g, source):
'\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, 4)\n sage: p == loads(dumps(p))\n True\n '
self.graph = g
self.source = source
Parent.__init__(self, category=FiniteEnumeratedSets())
def __repr__(self):
"\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, 4)\n sage: repr(p)\n 'Paths in Multi-digraph on 5 vertices starting at 4'\n "
return ('Paths in %s starting at %s' % (repr(self.graph), self.source))
def list(self):
'\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G, 4)\n sage: p.list()\n [[4], [4, 5], [4, 5]]\n '
return self.outgoing_paths(self.source)
|
class GraphPaths_st(Parent, GraphPaths_common):
'\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: GraphPaths(G,1,2).cardinality()\n 2\n sage: GraphPaths(G,1,3).cardinality()\n 3\n sage: GraphPaths(G,1,4).cardinality()\n 5\n sage: GraphPaths(G,1,5).cardinality()\n 10\n sage: GraphPaths(G,2,3).cardinality()\n 1\n sage: GraphPaths(G,2,4).cardinality()\n 2\n sage: GraphPaths(G,2,5).cardinality()\n 4\n sage: GraphPaths(G,3,4).cardinality()\n 1\n sage: GraphPaths(G,3,5).cardinality()\n 2\n sage: GraphPaths(G,4,5).cardinality()\n 2\n '
def __init__(self, g, source, target):
'\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G,1,2)\n sage: p == loads(dumps(p))\n True\n '
self.graph = g
self.source = source
self.target = target
Parent.__init__(self, category=FiniteEnumeratedSets())
def __repr__(self):
"\n TESTS::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G,1,2)\n sage: repr(p)\n 'Paths in Multi-digraph on 5 vertices starting at 1 and ending at 2'\n "
return ('Paths in %s starting at %s and ending at %s' % (repr(self.graph), self.source, self.target))
def list(self):
'\n EXAMPLES::\n\n sage: G = DiGraph({1:[2,2,3], 2:[3,4], 3:[4], 4:[5,5]}, multiedges=True)\n sage: p = GraphPaths(G,1,2)\n sage: p.list()\n [[1, 2], [1, 2]]\n '
return self.paths_from_source_to_target(self.source, self.target)
|
def product(m):
'\n Iterator over the switch for the iteration of the product\n `[m_0] \\times [m_1] \\ldots \\times [m_k]`.\n\n The iterator return at each step a pair ``(p,i)`` which corresponds to the\n modification to perform to get the next element. More precisely, one has to\n apply the increment ``i`` at the position ``p``. By construction, the\n increment is either ``+1`` or ``-1``.\n\n This is algorithm H in [Knu2011]_ Section 7.2.1.1, "Generating All\n `n`-Tuples": loopless reflected mixed-radix Gray generation.\n\n INPUT:\n\n - ``m`` -- a list or tuple of positive integers that correspond to the size\n of the sets in the product\n\n EXAMPLES::\n\n sage: from sage.combinat.gray_codes import product\n sage: l = [0,0,0]\n sage: for p,i in product([3,3,3]):\n ....: l[p] += i\n ....: print(l)\n [1, 0, 0]\n [2, 0, 0]\n [2, 1, 0]\n [1, 1, 0]\n [0, 1, 0]\n [0, 2, 0]\n [1, 2, 0]\n [2, 2, 0]\n [2, 2, 1]\n [1, 2, 1]\n [0, 2, 1]\n [0, 1, 1]\n [1, 1, 1]\n [2, 1, 1]\n [2, 0, 1]\n [1, 0, 1]\n [0, 0, 1]\n [0, 0, 2]\n [1, 0, 2]\n [2, 0, 2]\n [2, 1, 2]\n [1, 1, 2]\n [0, 1, 2]\n [0, 2, 2]\n [1, 2, 2]\n [2, 2, 2]\n sage: l = [0,0]\n sage: for i,j in product([2,1]):\n ....: l[i] += j\n ....: print(l)\n [1, 0]\n\n TESTS::\n\n sage: for t in [[2,2,2],[2,1,2],[3,2,1],[2,1,3]]:\n ....: assert sum(1 for _ in product(t)) == prod(t)-1\n '
n = k = 0
new_m = []
mm = []
for i in m:
i = int(i)
if (i <= 0):
raise ValueError('accept only positive integers')
if (i > 1):
new_m.append((i - 1))
mm.append(k)
n += 1
k += 1
m = new_m
f = list(range((n + 1)))
o = ([1] * n)
a = ([0] * n)
j = f[0]
while (j != n):
f[0] = 0
oo = o[j]
a[j] += oo
if ((a[j] == 0) or (a[j] == m[j])):
f[j] = f[(j + 1)]
f[(j + 1)] = (j + 1)
o[j] = (- oo)
(yield (mm[j], oo))
j = f[0]
|
def combinations(n, t):
'\n Iterator through the switches of the revolving door algorithm.\n\n The revolving door algorithm is a way to generate all combinations of a set\n (i.e. the subset of given cardinality) in such way that two consecutive\n subsets differ by one element. At each step, the iterator output a pair\n ``(i,j)`` where the item ``i`` has to be removed and ``j`` has to be added.\n\n The ground set is always `\\{0, 1, ..., n-1\\}`. Note that ``n`` can be\n infinity in that algorithm.\n\n See [Knu2011]_ Section 7.2.1.3, "Generating All Combinations".\n\n INPUT:\n\n - ``n`` -- (integer or ``Infinity``) -- size of the ground set\n\n - ``t`` -- (integer) -- size of the subsets\n\n EXAMPLES::\n\n sage: from sage.combinat.gray_codes import combinations\n sage: b = [1, 1, 1, 0, 0]\n sage: for i,j in combinations(5,3):\n ....: b[i] = 0; b[j] = 1\n ....: print(b)\n [1, 0, 1, 1, 0]\n [0, 1, 1, 1, 0]\n [1, 1, 0, 1, 0]\n [1, 0, 0, 1, 1]\n [0, 1, 0, 1, 1]\n [0, 0, 1, 1, 1]\n [1, 0, 1, 0, 1]\n [0, 1, 1, 0, 1]\n [1, 1, 0, 0, 1]\n\n sage: s = set([0,1])\n sage: for i,j in combinations(4,2):\n ....: s.remove(i)\n ....: s.add(j)\n ....: print(sorted(s))\n [1, 2]\n [0, 2]\n [2, 3]\n [1, 3]\n [0, 3]\n\n Note that ``n`` can be infinity::\n\n sage: c = combinations(Infinity,4)\n sage: s = set([0,1,2,3])\n sage: for _ in range(10):\n ....: i,j = next(c)\n ....: s.remove(i); s.add(j)\n ....: print(sorted(s))\n [0, 1, 3, 4]\n [1, 2, 3, 4]\n [0, 2, 3, 4]\n [0, 1, 2, 4]\n [0, 1, 4, 5]\n [1, 2, 4, 5]\n [0, 2, 4, 5]\n [2, 3, 4, 5]\n [1, 3, 4, 5]\n [0, 3, 4, 5]\n sage: for _ in range(1000):\n ....: i,j = next(c)\n ....: s.remove(i); s.add(j)\n sage: sorted(s)\n [0, 4, 13, 14]\n\n TESTS::\n\n sage: def check_sets_from_iter(n,k):\n ....: l = []\n ....: s = set(range(k))\n ....: l.append(frozenset(s))\n ....: for i,j in combinations(n,k):\n ....: s.remove(i)\n ....: s.add(j)\n ....: assert len(s) == k\n ....: l.append(frozenset(s))\n ....: assert len(set(l)) == binomial(n,k)\n sage: check_sets_from_iter(9,5)\n sage: check_sets_from_iter(8,5)\n sage: check_sets_from_iter(5,6)\n Traceback (most recent call last):\n ...\n AssertionError: t(=6) must be >=0 and <=n(=5)\n\n '
from sage.rings.infinity import Infinity
t = int(t)
if (n != Infinity):
n = int(n)
else:
n = Infinity
assert ((0 <= t) and (t <= n)), 't(={}) must be >=0 and <=n(={})'.format(t, n)
if ((t == 0) or (t == n)):
return iter([])
if (t % 2):
return _revolving_door_odd(n, t)
else:
return _revolving_door_even(n, t)
|
def _revolving_door_odd(n, t):
'\n Revolving door switch for odd `t`.\n\n TESTS::\n\n sage: from sage.combinat.gray_codes import _revolving_door_odd\n sage: sum(1 for _ in _revolving_door_odd(13,3)) == binomial(13,3) - 1\n True\n sage: sum(1 for _ in _revolving_door_odd(10,5)) == binomial(10,5) - 1\n True\n '
c = (list(range(t)) + [n])
while True:
if ((c[0] + 1) < c[1]):
(yield (c[0], (c[0] + 1)))
c[0] += 1
continue
j = 1
while (j < t):
if (c[j] > j):
(yield (c[j], (j - 1)))
c[j] = c[(j - 1)]
c[(j - 1)] = (j - 1)
break
j += 1
if ((c[j] + 1) < c[(j + 1)]):
(yield (c[(j - 1)], (c[j] + 1)))
c[(j - 1)] = c[j]
c[j] += 1
break
j += 1
else:
break
|
def _revolving_door_even(n, t):
'\n Revolving door algorithm for even `t`.\n\n TESTS::\n\n sage: from sage.combinat.gray_codes import _revolving_door_even\n sage: sum(1 for _ in _revolving_door_even(13,4)) == binomial(13,4) - 1\n True\n sage: sum(1 for _ in _revolving_door_even(12,6)) == binomial(12,6) - 1\n True\n '
c = (list(range(t)) + [n])
while True:
if (c[0] > 0):
(yield (c[0], (c[0] - 1)))
c[0] -= 1
continue
j = 1
if ((c[j] + 1) < c[(j + 1)]):
(yield (c[(j - 1)], (c[j] + 1)))
c[(j - 1)] = c[j]
c[j] += 1
continue
j += 1
while (j < t):
if (c[j] > j):
(yield (c[j], (j - 1)))
c[j] = c[(j - 1)]
c[(j - 1)] = (j - 1)
break
j += 1
if ((c[j] + 1) < c[(j + 1)]):
(yield (c[(j - 1)], (c[j] + 1)))
c[(j - 1)] = c[j]
c[j] += 1
break
j += 1
else:
break
|
class GrossmanLarsonAlgebra(CombinatorialFreeModule):
'\n The Grossman-Larson Hopf Algebra.\n\n The Grossman-Larson Hopf Algebras are Hopf algebras with a basis\n indexed by forests of decorated rooted trees. They are the\n universal enveloping algebras of free pre-Lie algebras, seen\n as Lie algebras.\n\n The Grossman-Larson Hopf algebra on a given set `E` has an\n explicit description using rooted forests. The underlying vector\n space has a basis indexed by finite rooted forests endowed with a\n map from their vertices to `E` (called the "labeling").\n In this basis, the product of two\n (decorated) rooted forests `S * T` is a sum over all maps from\n the set of roots of `T` to the union of a singleton `\\{\\#\\}` and\n the set of vertices of `S`. Given such a map, one defines a new\n forest as follows. Starting from the disjoint union of all rooted trees\n of `S` and `T`, one adds an edge from every root of `T` to its\n image when this image is not the fake vertex labelled ``#``.\n The coproduct sends a rooted forest `T` to the sum of all tensors\n `T_1 \\otimes T_2` obtained by splitting the connected components\n of `T` into two subsets and letting `T_1` be the forest formed\n by the first subset and `T_2` the forest formed by the second.\n This yields a connected graded Hopf algebra (the degree of a\n forest is its number of vertices).\n\n See [Pana2002]_ (Section 2) and [GroLar1]_.\n (Note that both references use rooted trees rather than rooted\n forests, so think of each rooted forest grafted onto a new root.\n Also, the product is reversed, so they are defining the opposite\n algebra structure.)\n\n .. WARNING::\n\n For technical reasons, instead of using forests as labels for\n the basis, we use rooted trees. Their root vertex should be\n considered as a fake vertex. This fake root vertex is labelled\n ``\'#\'`` when labels are present.\n\n EXAMPLES::\n\n sage: G = algebras.GrossmanLarson(QQ, \'xy\')\n sage: x, y = G.single_vertex_all()\n sage: ascii_art(x*y)\n B + B\n # #_\n | / /\n x x y\n |\n y\n\n sage: ascii_art(x*x*x)\n B + B + 3*B + B\n # # #_ _#__\n | | / / / / /\n x x_ x x x x x\n | / / |\n x x x x\n |\n x\n\n The Grossman-Larson algebra is associative::\n\n sage: z = x * y\n sage: x * (y * z) == (x * y) * z\n True\n\n It is not commutative::\n\n sage: x * y == y * x\n False\n\n When ``None`` is given as input, unlabelled forests are used instead;\n this corresponds to a `1`-element set `E`::\n\n sage: G = algebras.GrossmanLarson(QQ, None)\n sage: x = G.single_vertex_all()[0]\n sage: ascii_art(x*x)\n B + B\n o o_\n | / /\n o o o\n |\n o\n\n .. NOTE::\n\n Variables names can be ``None``, a list of strings, a string\n or an integer. When ``None`` is given, unlabelled rooted\n forests are used. When a single string is given, each letter is taken\n as a variable. See\n :func:`sage.combinat.words.alphabet.build_alphabet`.\n\n .. WARNING::\n\n Beware that the underlying combinatorial free module is based\n either on ``RootedTrees`` or on ``LabelledRootedTrees``, with no\n restriction on the labellings. This means that all code calling\n the :meth:`basis` method would not give meaningful results, since\n :meth:`basis` returns many "chaff" elements that do not belong to\n the algebra.\n\n REFERENCES:\n\n - [Pana2002]_\n\n - [GroLar1]_\n '
@staticmethod
def __classcall_private__(cls, R, names=None):
"\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: F1 = algebras.GrossmanLarson(QQ, 'xyz')\n sage: F2 = algebras.GrossmanLarson(QQ, ['x','y','z'])\n sage: F3 = algebras.GrossmanLarson(QQ, Alphabet('xyz'))\n sage: F1 is F2 and F1 is F3\n True\n "
if (names is not None):
if ((names not in ZZ) and (',' in names)):
names = [u for u in names if (u != ',')]
names = Alphabet(names)
if (R not in Rings()):
raise TypeError('argument R must be a ring')
return super().__classcall__(cls, R, names)
def __init__(self, R, names=None):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: A = algebras.GrossmanLarson(QQ, '@'); A\n Grossman-Larson Hopf algebra on one generator ['@']\n over Rational Field\n sage: TestSuite(A).run() # long time\n\n sage: F = algebras.GrossmanLarson(QQ, 'xy')\n sage: TestSuite(F).run() # long time\n\n sage: A = algebras.GrossmanLarson(QQ, None); A\n Grossman-Larson Hopf algebra on one generator ['o'] over\n Rational Field\n\n sage: F = algebras.GrossmanLarson(QQ, ['x','y']); F\n Grossman-Larson Hopf algebra on 2 generators ['x', 'y']\n over Rational Field\n\n sage: A = algebras.GrossmanLarson(QQ, []); A\n Grossman-Larson Hopf algebra on 0 generators [] over\n Rational Field\n "
if (names is None):
Trees = RootedTrees()
key = RootedTree.sort_key
self._alphabet = Alphabet(['o'])
else:
Trees = LabelledRootedTrees()
key = LabelledRootedTree.sort_key
self._alphabet = names
cat = HopfAlgebras(R).WithBasis().Graded()
CombinatorialFreeModule.__init__(self, R, Trees, latex_prefix='', sorting_key=key, category=cat)
def variable_names(self):
"\n Return the names of the variables.\n\n This returns the set `E` (as a family).\n\n EXAMPLES::\n\n sage: R = algebras.GrossmanLarson(QQ, 'xy')\n sage: R.variable_names()\n {'x', 'y'}\n\n sage: R = algebras.GrossmanLarson(QQ, ['a','b'])\n sage: R.variable_names()\n {'a', 'b'}\n\n sage: R = algebras.GrossmanLarson(QQ, 2)\n sage: R.variable_names()\n {0, 1}\n\n sage: R = algebras.GrossmanLarson(QQ, None)\n sage: R.variable_names()\n {'o'}\n "
return self._alphabet
def _repr_(self):
"\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.GrossmanLarson(QQ, '@') # indirect doctest\n Grossman-Larson Hopf algebra on one generator ['@'] over Rational Field\n sage: algebras.GrossmanLarson(QQ, None) # indirect doctest\n Grossman-Larson Hopf algebra on one generator ['o'] over Rational Field\n sage: algebras.GrossmanLarson(QQ, ['a','b'])\n Grossman-Larson Hopf algebra on 2 generators ['a', 'b'] over Rational Field\n "
n = len(self.single_vertex_all())
if (n == 1):
gen = 'one generator'
else:
gen = '{} generators'.format(n)
s = 'Grossman-Larson Hopf algebra on {} {} over {}'
try:
return s.format(gen, self._alphabet.list(), self.base_ring())
except NotImplementedError:
return s.format(gen, self._alphabet, self.base_ring())
def single_vertex(self, i):
"\n Return the ``i``-th rooted forest with one vertex.\n\n This is the rooted forest with just one vertex, labelled by the\n ``i``-th element of the label list.\n\n .. SEEALSO:: :meth:`single_vertex_all`.\n\n INPUT:\n\n - ``i`` -- a nonnegative integer\n\n EXAMPLES::\n\n sage: F = algebras.GrossmanLarson(ZZ, 'xyz')\n sage: F.single_vertex(0)\n B[#[x[]]]\n\n sage: F.single_vertex(4)\n Traceback (most recent call last):\n ...\n IndexError: argument i (= 4) must be between 0 and 2\n "
G = self.single_vertex_all()
n = len(G)
if ((i < 0) or (not (i < n))):
m = 'argument i (= {}) must be between 0 and {}'.format(i, (n - 1))
raise IndexError(m)
return G[i]
def single_vertex_all(self):
"\n Return the rooted forests with one vertex in ``self``.\n\n They freely generate the Lie algebra of primitive elements\n as a pre-Lie algebra.\n\n .. SEEALSO:: :meth:`single_vertex`.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(ZZ, 'fgh')\n sage: A.single_vertex_all()\n (B[#[f[]]], B[#[g[]]], B[#[h[]]])\n\n sage: A = algebras.GrossmanLarson(QQ, ['x1','x2'])\n sage: A.single_vertex_all()\n (B[#[x1[]]], B[#[x2[]]])\n\n sage: A = algebras.GrossmanLarson(ZZ, None)\n sage: A.single_vertex_all()\n (B[[[]]],)\n "
Trees = self.basis().keys()
return tuple(Family(self._alphabet, (lambda a: self.monomial(Trees([Trees([], a)], ROOT)))))
def _first_ngens(self, n):
"\n Return the first generators.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, ['x1','x2'])\n sage: A._first_ngens(2)\n (B[#[x1[]]], B[#[x2[]]])\n\n sage: A = algebras.GrossmanLarson(ZZ, None)\n sage: A._first_ngens(1)\n (B[[[]]],)\n "
return self.single_vertex_all()[:n]
def change_ring(self, R):
"\n Return the Grossman-Larson algebra in the same variables over `R`.\n\n INPUT:\n\n - `R` -- a ring\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(ZZ, 'fgh')\n sage: A.change_ring(QQ)\n Grossman-Larson Hopf algebra on 3 generators ['f', 'g', 'h']\n over Rational Field\n "
return GrossmanLarsonAlgebra(R, names=self.variable_names())
def degree_on_basis(self, t):
"\n Return the degree of a rooted forest in the Grossman-Larson algebra.\n\n This is the total number of vertices of the forest.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, '@')\n sage: RT = A.basis().keys()\n sage: A.degree_on_basis(RT([RT([])]))\n 1\n "
return (t.node_number() - 1)
@cached_method
def an_element(self):
"\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, 'xy')\n sage: A.an_element()\n B[#[x[]]] + 2*B[#[x[x[]]]] + 2*B[#[x[], x[]]]\n "
o = self.single_vertex(0)
return (o + ((2 * o) * o))
def some_elements(self):
"\n Return some elements of the Grossman-Larson Hopf algebra.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, None)\n sage: A.some_elements()\n [B[[[]]], B[[]] + B[[[[]]]] + B[[[], []]],\n 4*B[[[[]]]] + 4*B[[[], []]]]\n\n With several generators::\n\n sage: A = algebras.GrossmanLarson(QQ, 'xy')\n sage: A.some_elements()\n [B[#[x[]]],\n B[#[]] + B[#[x[x[]]]] + B[#[x[], x[]]],\n B[#[x[x[]]]] + 3*B[#[x[y[]]]] + B[#[x[], x[]]] + 3*B[#[x[], y[]]]]\n "
o = self.single_vertex(0)
o1 = self.single_vertex_all()[(- 1)]
x = (o * o)
y = (o * o1)
return [o, (1 + x), (x + (3 * y))]
def product_on_basis(self, x, y):
"\n Return the product of two forests `x` and `y`.\n\n This is the sum over all possible ways for the components\n of the forest `y` to either fall side-by-side with components\n of `x` or be grafted on a vertex of `x`.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, None)\n sage: RT = A.basis().keys()\n sage: x = RT([RT([])])\n sage: A.product_on_basis(x, x)\n B[[[[]]]] + B[[[], []]]\n\n Check that the product is the correct one::\n\n sage: A = algebras.GrossmanLarson(QQ, 'uv')\n sage: RT = A.basis().keys()\n sage: Tu = RT([RT([],'u')],'#')\n sage: Tv = RT([RT([],'v')],'#')\n sage: A.product_on_basis(Tu, Tv)\n B[#[u[v[]]]] + B[#[u[], v[]]]\n "
return self.sum((self.basis()[x.single_graft(y, graftingFunction)] for graftingFunction in product(list(x.paths()), repeat=len(y))))
def one_basis(self):
"\n Return the empty rooted forest.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, 'ab')\n sage: A.one_basis()\n #[]\n\n sage: A = algebras.GrossmanLarson(QQ, None)\n sage: A.one_basis()\n []\n "
Trees = self.basis().keys()
return Trees([], ROOT)
def coproduct_on_basis(self, x):
"\n Return the coproduct of a forest.\n\n EXAMPLES::\n\n sage: G = algebras.GrossmanLarson(QQ,2)\n sage: x, y = G.single_vertex_all()\n sage: ascii_art(G.coproduct(x)) # indirect doctest\n 1 # B + B # 1\n # #\n | |\n 0 0\n\n sage: Delta_xy = G.coproduct(y*x)\n sage: ascii_art(Delta_xy) # random indirect doctest\n 1 # B + 1 # B + B # B + B # 1 + B # B + B # 1\n #_ # # # #_ # # #\n / / | | | / / | | |\n 0 1 1 0 1 0 1 1 0 1\n | |\n 0 0\n\n TESTS::\n\n sage: Delta_xy.coefficients()\n [1, 1, 1, 1, 1, 1]\n sage: sortkey = G.print_options()['sorting_key']\n sage: doublekey = lambda tt: (sortkey(tt[0]), sortkey(tt[1]))\n sage: sorted(Delta_xy.monomial_coefficients(), key=doublekey)\n [(#[], #[1[0[]]]),\n (#[], #[0[], 1[]]),\n (#[0[]], #[1[]]),\n (#[1[]], #[0[]]),\n (#[1[0[]]], #[]),\n (#[0[], 1[]], #[])]\n "
B = self.basis()
Trees = B.keys()
subtrees = list(x)
num_subtrees = len(subtrees)
indx = list(range(num_subtrees))
return sum((B[Trees([subtrees[i] for i in S], ROOT)].tensor(B[Trees([subtrees[i] for i in indx if (i not in S)], ROOT)]) for k in range((num_subtrees + 1)) for S in combinations(indx, k)))
def counit_on_basis(self, x):
"\n Return the counit on a basis element.\n\n This is zero unless the forest `x` is empty.\n\n EXAMPLES::\n\n sage: A = algebras.GrossmanLarson(QQ, 'xy')\n sage: RT = A.basis().keys()\n sage: x = RT([RT([],'x')],'#')\n sage: A.counit_on_basis(x)\n 0\n sage: A.counit_on_basis(RT([],'#'))\n 1\n "
if (x.node_number() == 1):
return self.base_ring().one()
return self.base_ring().zero()
def antipode_on_basis(self, x):
'\n Return the antipode of a forest.\n\n EXAMPLES::\n\n sage: G = algebras.GrossmanLarson(QQ,2)\n sage: x, y = G.single_vertex_all()\n sage: G.antipode(x) # indirect doctest\n -B[#[0[]]]\n\n sage: G.antipode(y*x) # indirect doctest\n B[#[0[1[]]]] + B[#[0[], 1[]]]\n '
B = self.basis()
Trees = B.keys()
subtrees = list(x)
if (not subtrees):
return self.one()
num_subtrees = len(subtrees)
indx = list(range(num_subtrees))
return sum((((- self.antipode_on_basis(Trees([subtrees[i] for i in S], ROOT))) * B[Trees([subtrees[i] for i in indx if (i not in S)], ROOT)]) for k in range(num_subtrees) for S in combinations(indx, k)))
def _element_constructor_(self, x):
"\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R = algebras.GrossmanLarson(QQ, 'xy')\n sage: x, y = R.single_vertex_all()\n sage: R(x)\n B[#[x[]]]\n sage: R(x+4*y)\n B[#[x[]]] + 4*B[#[y[]]]\n\n sage: Trees = R.basis().keys()\n sage: R(Trees([],'#'))\n B[#[]]\n\n sage: D = algebras.GrossmanLarson(ZZ, 'xy')\n sage: X, Y = D.single_vertex_all()\n sage: R(X-Y).parent()\n Grossman-Larson Hopf algebra on 2 generators ['x', 'y'] over Rational Field\n\n TESTS::\n\n sage: Trees = R.basis().keys()\n sage: R(Trees([],'x'))\n Traceback (most recent call last):\n ...\n ValueError: incorrect root label\n\n sage: R.<x,y> = algebras.GrossmanLarson(QQ)\n sage: R(x) is x\n True\n sage: S.<z> = algebras.GrossmanLarson(GF(3))\n sage: R(z)\n Traceback (most recent call last):\n ...\n TypeError: not able to convert this to this algebra\n "
if (isinstance(x, (RootedTree, LabelledRootedTree)) and (x in self.basis().keys())):
if (hasattr(x, 'label') and (x.label() != ROOT)):
raise ValueError('incorrect root label')
return self.monomial(x)
try:
P = x.parent()
if isinstance(P, GrossmanLarsonAlgebra):
if (P is self):
return x
if self._coerce_map_from_(P):
return self.element_class(self, x.monomial_coefficients())
except AttributeError:
raise TypeError('not able to convert this to this algebra')
else:
raise TypeError('not able to convert this to this algebra')
def _coerce_map_from_(self, R):
"\n Return ``True`` if there is a coercion from ``R`` into ``self``\n and ``False`` otherwise.\n\n The things that coerce into ``self`` are\n\n - Grossman-Larson Hopf algebras whose set `E` of labels is\n a subset of the corresponding set of ``self``, and whose base\n ring has a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: F = algebras.GrossmanLarson(GF(7), 'xyz'); F\n Grossman-Larson Hopf algebra on 3 generators ['x', 'y', 'z']\n over Finite Field of size 7\n\n Elements of the Grossman-Larson Hopf algebra canonically coerce in::\n\n sage: x, y, z = F.single_vertex_all()\n sage: F.coerce(x+y) == x+y\n True\n\n The Grossman-Larson Hopf algebra over `\\ZZ` on `x, y, z`\n coerces in, since `\\ZZ` coerces to `\\GF{7}`::\n\n sage: G = algebras.GrossmanLarson(ZZ, 'xyz')\n sage: Gx,Gy,Gz = G.single_vertex_all()\n sage: z = F.coerce(Gx+Gy); z\n B[#[x[]]] + B[#[y[]]]\n sage: z.parent() is F\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so the Grossman-Larson\n algebra over `\\GF{7}` does not coerce to the one over `\\ZZ`::\n\n sage: G.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Grossman-Larson Hopf algebra\n on 3 generators ['x', 'y', 'z'] over Finite Field of size\n 7 to Grossman-Larson Hopf algebra on 3 generators ['x', 'y', 'z']\n over Integer Ring\n\n TESTS::\n\n sage: F = algebras.GrossmanLarson(ZZ, 'xyz')\n sage: G = algebras.GrossmanLarson(QQ, 'xyz')\n sage: H = algebras.GrossmanLarson(ZZ, 'y')\n sage: F._coerce_map_from_(G)\n False\n sage: G._coerce_map_from_(F)\n True\n sage: F._coerce_map_from_(H)\n True\n sage: F._coerce_map_from_(QQ)\n False\n sage: G._coerce_map_from_(QQ)\n False\n sage: F.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n "
if isinstance(R, GrossmanLarsonAlgebra):
if all(((x in self.variable_names()) for x in R.variable_names())):
if self.base_ring().has_coerce_map_from(R.base_ring()):
return True
return False
|
def _make_partition(l):
'\n Return the list as a partition.\n\n This is intended to be fast, so checks are bypassed.\n\n TESTS::\n\n sage: from sage.combinat.growth import _make_partition\n sage: p = _make_partition([3,2,1,0]); p\n [3, 2, 1]\n\n sage: p.parent()\n Partitions\n '
return _Partitions.element_class(_Partitions, l)
|
class GrowthDiagram(SageObject):
"\n A generalized Schensted growth diagram in the sense of Fomin.\n\n Growth diagrams were introduced by Sergey Fomin [Fom1994]_,\n [Fom1995]_ and provide a vast generalization of the\n Robinson-Schensted-Knuth (RSK) correspondence between matrices\n with non-negative integer entries and pairs of semistandard Young\n tableaux of the same shape.\n\n A growth diagram is based on the notion of *dual graded graphs*,\n a pair of digraphs `P, Q` (multiple edges being allowed) on the\n same set of vertices `V`, that satisfy the following conditions:\n\n * the graphs are graded, that is, there is a function `\\rho:\n V \\to \\NN`, such that for any edge `(v, w)` of `P` and also\n of `Q` we have `\\rho(w) = \\rho(v) + 1`,\n\n * there is a vertex `0` with rank zero, and\n\n * there is a positive integer `r` such that `DU = UD + rI` on the\n free `\\ZZ`-module `\\ZZ[V]`, where `D` is the down operator of\n `Q`, assigning to each vertex the formal sum of its\n predecessors, `U` is the up operator of `P`, assigning to each\n vertex the formal sum of its successors, and `I` is the\n identity operator.\n\n Growth diagrams are defined by providing a pair of local rules: a\n 'forward' rule, whose input are three vertices `y`, `t` and `x`\n of the dual graded graphs and an integer, and whose output is a\n fourth vertex `z`. This rule should be invertible in the\n following sense: there is a so-called 'backward' rule that\n recovers the integer and `t` given `y`, `z` and `x`.\n\n All implemented growth diagram rules are available by\n ``GrowthDiagram.rules.<tab>``. The current list is:\n\n - :class:`~sage.combinat.growth.RuleRSK` -- RSK\n - :class:`~sage.combinat.growth.RuleBurge` -- a variation of RSK\n originally due to Burge\n - :class:`~sage.combinat.growth.RuleBinaryWord` -- a correspondence\n producing binary words originally due to Viennot\n - :class:`~sage.combinat.growth.RuleDomino` -- a correspondence\n producing domino tableaux originally due to Barbasch and Vogan\n - :class:`~sage.combinat.growth.RuleShiftedShapes` -- a correspondence\n for shifted shapes, where the original insertion algorithm is due\n to Sagan and Worley, and Haiman.\n - :class:`~sage.combinat.growth.RuleSylvester` -- the Sylvester\n correspondence, producing binary trees\n - :class:`~sage.combinat.growth.RuleYoungFibonacci` -- the\n Young-Fibonacci correspondence\n - :class:`~sage.combinat.growth.RuleLLMS` -- LLMS insertion\n\n INPUT:\n\n - ``rule`` -- :class:`~sage.combinat.growth.Rule`;\n the growth diagram rule\n\n - ``filling`` -- (optional) a dictionary whose keys are coordinates\n and values are integers, a list of lists of integers, or a word\n with integer values; if a word, then negative letters but without\n repetitions are allowed and interpreted as coloured permutations\n\n - ``shape`` -- (optional) a (possibly skew) partition\n\n - ``labels`` -- (optional) a list that specifies a path whose length\n in the half-perimeter of the shape; more details given below\n\n If ``filling`` is not given, then the growth diagram is determined\n by applying the backward rule to ``labels`` decorating the\n boundary opposite of the origin of the ``shape``. In this case,\n ``labels`` are interpreted as labelling the boundary opposite of\n the origin.\n\n Otherwise, ``shape`` is inferred from ``filling`` or ``labels`` if\n possible and ``labels`` is set to ``rule.zero`` if not specified.\n Here, ``labels`` are labelling the boundary on the side of the origin.\n\n For ``labels``, if ``rule.has_multiple_edges`` is ``True``, then the\n elements should be of the form `(v_1, e_1, \\ldots, e_{n-1}, v_n)`,\n where `n` is the half-perimeter of ``shape``, and `(v_{i-1}, e_i, v_i)`\n is an edge in the dual graded graph for all `i`. Otherwise, it is a\n list of `n` vertices.\n\n .. NOTE::\n\n Coordinates are of the form ``(col, row)`` where the origin is\n in the upper left, to be consistent with permutation matrices\n and skew tableaux (in English convention). This is different\n from Fomin's convention, who uses a Cartesian coordinate system.\n\n Conventions are chosen such that for permutations, the same\n growth diagram is constructed when passing the permutation\n matrix instead.\n\n EXAMPLES:\n\n We create a growth diagram using the forward RSK rule and a permutation::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: pi = Permutation([4, 1, 2, 3])\n sage: G = GrowthDiagram(RuleRSK, pi); G\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\n 1 0 0 0\n sage: G.out_labels()\n [[], [1], [1, 1], [2, 1], [3, 1], [3], [2], [1], []]\n\n Passing the permutation matrix instead gives the same result::\n\n sage: G = GrowthDiagram(RuleRSK, pi.to_matrix()) # needs sage.modules\n sage: ascii_art([G.P_symbol(), G.Q_symbol()]) # needs sage.modules\n [ 1 2 3 1 3 4 ]\n [ 4 , 2 ]\n\n We give the same example but using a skew shape::\n\n sage: shape = SkewPartition([[4,4,4,2],[1,1]])\n sage: G = GrowthDiagram(RuleRSK, pi, shape=shape); G\n . 1 0 0\n . 0 1 0\n 0 0 0 1\n 1 0\n sage: G.out_labels()\n [[], [1], [1, 1], [1], [2], [3], [2], [1], []]\n\n We construct a growth diagram using the backwards RSK rule by\n specifying the labels::\n\n sage: GrowthDiagram(RuleRSK, labels=G.out_labels())\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\n 1 0\n "
def __init__(self, rule, filling=None, shape=None, labels=None):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: w = [3,3,2,4,1]; G = GrowthDiagram(RuleRSK, w)\n sage: [G.P_symbol(), G.Q_symbol()]\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n sage: RSK(w)\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n\n sage: TestSuite(G).run()\n\n sage: GrowthDiagram(RuleRSK)\n Traceback (most recent call last):\n ...\n ValueError: please provide a filling or a sequence of labels\n '
if (not isinstance(rule, Rule)):
raise TypeError('the rule must be an instance of Rule')
self.rule = rule
if (filling is None):
if (labels is None):
raise ValueError('please provide a filling or a sequence of labels')
labels = self._process_labels(labels)
if (shape is None):
shape = self._shape_from_labels(labels)
(self._lambda, self._mu) = self._process_shape(shape)
self._out_labels = labels
self._check_labels(self._out_labels)
self._shrink()
else:
(self._filling, (self._lambda, self._mu)) = self._process_filling_and_shape(filling, shape)
if (labels is None):
rule = self.rule
if rule.has_multiple_edges:
self._in_labels = (([rule.zero, rule.zero_edge] * (self.half_perimeter() - 1)) + [rule.zero])
else:
self._in_labels = ([rule.zero] * self.half_perimeter())
else:
labels = self._process_labels(labels)
self._in_labels = labels
self._check_labels(self._in_labels)
self._grow()
def filling(self):
'\n Return the filling of the diagram as a dictionary.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: G.filling()\n {(0, 1): 1, (1, 0): 1, (2, 1): 2}\n '
return self._filling
def conjugate(self):
'\n Return the conjugate growth diagram of ``self``.\n\n This is the growth diagram with the filling reflected over the\n main diagonal.\n\n The sequence of labels along the boundary on the side of the\n origin is the reversal of the corresponding sequence of the\n original growth diagram.\n\n When the filling is a permutation, the conjugate filling\n corresponds to its inverse.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: Gc = G.conjugate()\n sage: (Gc.P_symbol(), Gc.Q_symbol()) == (G.Q_symbol(), G.P_symbol())\n True\n\n TESTS:\n\n Check that labels and shape are handled correctly::\n\n sage: o = [[2,1],[2,2],[3,2],[4,2],[4,1],[4,1,1],[3,1,1],[3,1],[3,2],[3,1],[2,1]]\n sage: l = [o[i//2] if is_even(i) else min(o[(i-1)//2],o[(i+1)//2])\n ....: for i in range(2*len(o)-1)]\n sage: la = list(range(len(o)-2, 0, -1))\n sage: G = RuleRSK(labels=l[1:-1], shape=la)\n sage: G.out_labels() == G.conjugate().out_labels()[::-1]\n True\n '
F = {(j, i): v for ((i, j), v) in self._filling.items()}
return GrowthDiagram(self.rule, filling=F, shape=self.shape().conjugate(), labels=self.in_labels()[::(- 1)])
def rotate(self):
'\n Return the growth diagram with the filling rotated by 180 degrees.\n\n The rotated growth diagram is initialized with\n ``labels=None``, that is, all labels along the boundary on\n the side of the origin are set to ``rule.zero``.\n\n For RSK-growth diagrams and rectangular fillings, this\n corresponds to evacuation of the `P`- and the `Q`-symbol.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: Gc = G.rotate()\n sage: ascii_art([Gc.P_symbol(), Gc.Q_symbol()])\n [ 1 1 1 1 1 2 ]\n [ 2 , 3 ]\n\n sage: ascii_art([Tableau(t).evacuation()\n ....: for t in [G.P_symbol(), G.Q_symbol()]])\n [ 1 1 1 1 1 2 ]\n [ 2 , 3 ]\n\n TESTS:\n\n Check that shape is handled correctly::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK,\n ....: filling={(0,2):1, (3,1):2, (2,1):3},\n ....: shape=SkewPartition([[5,5,5,3],[3,1]]))\n sage: G\n . . . 0 0\n . 0 3 2 0\n 1 0 0 0 0\n 0 0 0\n sage: G.rotate()\n . . 0 0 0\n 0 0 0 0 1\n 0 2 3 0\n 0 0\n '
l = self._lambda[0]
h = len(self._lambda)
shape_lambda = ([(l - p) for p in self._mu] + ([l] * (h - len(self._mu))))
shape_mu = [(l - p) for p in self._lambda]
shape = SkewPartition([shape_lambda[::(- 1)], shape_mu[::(- 1)]])
F = {(((l - i) - 1), ((h - j) - 1)): v for ((i, j), v) in self._filling.items()}
return GrowthDiagram(self.rule, filling=F, shape=shape)
def half_perimeter(self):
'\n Return half the perimeter of the shape of the growth diagram.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, {(0,1):1, (2,0):1}, SkewPartition([[3,1],[1]])); G\n . 0 1\n 1\n sage: G.half_perimeter()\n 6\n '
if (not self._lambda):
return 1
return ((self._lambda[0] + len(self._lambda)) + 1)
def shape(self):
'\n Return the shape of the growth diagram as a skew partition.\n\n .. WARNING::\n\n In the literature the label on the corner opposite of the\n origin of a rectangular filling is often called the shape\n of the filling. This method returns the shape of the\n region instead.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: GrowthDiagram(RuleRSK, [1]).shape()\n [1] / []\n '
return SkewPartition([self._lambda, self._mu])
def out_labels(self):
'\n Return the labels along the boundary opposite of the origin.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: G.out_labels()\n [[], [1], [1, 1], [3, 1], [1], []]\n '
return self._out_labels
def in_labels(self):
'\n Return the labels along the boundary on the side of the origin.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, labels=[[2,2],[3,2],[3,3],[3,2]]); G\n 1 0\n sage: G.in_labels()\n [[2, 2], [2, 2], [2, 2], [3, 2]]\n '
return self._in_labels
def P_symbol(self):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a generalized standard tableau.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 2 2 1 3 3 ]\n [ 2 , 2 ]\n '
return self.rule.P_symbol(self.P_chain())
def Q_symbol(self):
'\n Return the labels along the horizontal boundary of a rectangular\n growth diagram as a generalized standard tableau.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, [[0,1,0], [1,0,2]])\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 2 2 1 3 3 ]\n [ 2 , 2 ]\n '
return self.rule.Q_symbol(self.Q_chain())
def P_chain(self):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: G = GrowthDiagram(BinaryWord, [4, 1, 2, 3])\n sage: G.P_chain()\n [word: , word: 1, word: 11, word: 111, word: 1011]\n\n Check that :trac:`25631` is fixed::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord(filling = {}).P_chain()\n [word: ]\n\n '
if (not self.is_rectangular()):
raise ValueError('the P symbol is only defined for rectangular shapes')
if self._lambda:
if self.rule.has_multiple_edges:
r = (2 * self._lambda[0])
else:
r = self._lambda[0]
else:
r = 0
return self._out_labels[r:][::(- 1)]
def Q_chain(self):
'\n Return the labels along the horizontal boundary of a rectangular\n growth diagram.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: G = GrowthDiagram(BinaryWord, [[0,1,0,0], [0,0,1,0], [0,0,0,1], [1,0,0,0]])\n sage: G.Q_chain()\n [word: , word: 1, word: 10, word: 101, word: 1011]\n\n Check that :trac:`25631` is fixed::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord(filling = {}).Q_chain()\n [word: ]\n\n '
if (not self.is_rectangular()):
raise ValueError('the Q symbol is only defined for rectangular shapes')
if self._lambda:
if self.rule.has_multiple_edges:
r = ((2 * self._lambda[0]) + 1)
else:
r = (self._lambda[0] + 1)
else:
r = 1
return self._out_labels[:r]
def is_rectangular(self):
'\n Return ``True`` if the shape of the growth diagram is rectangular.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: GrowthDiagram(RuleRSK, [2,3,1]).is_rectangular()\n True\n sage: GrowthDiagram(RuleRSK, [[1,0,1],[0,1]]).is_rectangular()\n False\n '
return (all(((x == 0) for x in self._mu)) and all(((x == self._lambda[0]) for x in self._lambda)))
def to_word(self):
'\n Return the filling as a word, if the shape is rectangular and\n there is at most one nonzero entry in each column, which must\n be 1.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: w = [3,3,2,4,1]; G = GrowthDiagram(RuleRSK, w)\n sage: G\n 0 0 0 0 1\n 0 0 1 0 0\n 1 1 0 0 0\n 0 0 0 1 0\n sage: G.to_word()\n [3, 3, 2, 4, 1]\n '
if (not self.is_rectangular()):
raise ValueError('can only convert fillings of rectangular shapes to words')
w = ([0] * self._lambda[0])
for ((i, j), v) in self._filling.items():
if (v != 0):
if (v == 1):
if (w[i] == 0):
w[i] = (j + 1)
else:
raise ValueError('can only convert fillings with at most one entry per column to words')
elif (v == (- 1)):
if (w[i] == 0):
w[i] = (- (j + 1))
else:
raise ValueError('can only convert fillings with at most one entry per column to words')
else:
raise ValueError("can only convert 0-1 fillings to words; try 'to_biword'")
return w
def to_biword(self):
'\n Return the filling as a biword, if the shape is rectangular.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: P = Tableau([[1,2,2],[2]])\n sage: Q = Tableau([[1,3,3],[2]])\n sage: bw = RSK_inverse(P, Q); bw\n [[1, 2, 3, 3], [2, 1, 2, 2]]\n sage: G = GrowthDiagram(RuleRSK, labels=Q.to_chain()[:-1]+P.to_chain()[::-1]); G\n 0 1 0\n 1 0 2\n\n sage: P = SemistandardTableau([[1, 1, 2], [2]])\n sage: Q = SemistandardTableau([[1, 2, 2], [2]])\n sage: G = GrowthDiagram(RuleRSK, labels=Q.to_chain()[:-1]+P.to_chain()[::-1]); G\n 0 2\n 1 1\n sage: G.to_biword()\n ([1, 2, 2, 2], [2, 1, 1, 2])\n sage: RSK([1, 2, 2, 2], [2, 1, 1, 2])\n [[[1, 1, 2], [2]], [[1, 2, 2], [2]]]\n '
if (not self.is_rectangular()):
raise ValueError('can only convert fillings of rectangular shapes to words')
w1 = []
w2 = []
for ((i, j), v) in sorted(self._filling.items()):
if (v >= 0):
w1.extend(([(i + 1)] * v))
w2.extend(([(j + 1)] * v))
else:
raise ValueError('can only convert fillings with non-negative entries to words')
return (w1, w2)
def __iter__(self):
'\n Return the rows of the filling.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = GrowthDiagram(RuleRSK, {(0,1):1, (1,0):1}, SkewPartition([[2,1],[1]]))\n sage: list(G)\n [[None, 1], [1]]\n\n sage: pi = Permutation([2,3,1,6,4,5])\n sage: G = GrowthDiagram(RuleRSK, pi)\n sage: list(G)\n [[0, 0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 1, 0, 0]]\n '
return ((([None] * self._mu[r]) + [self._filling.get(((self._mu[r] + j), r), 0) for j in range((self._lambda[r] - self._mu[r]))]) for r in range(len(self._lambda)))
def _repr_(self):
'\n Return a string with the filling of the growth diagram\n as a skew tableau.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: GrowthDiagram(RuleRSK, {(0,1):1, (1,0):1}, SkewPartition([[2,1],[1]]))\n . 1\n 1\n\n sage: GrowthDiagram(RuleRSK, {(0,1):1, (2,0):1}, SkewPartition([[3,1],[1]]))\n . 0 1\n 1\n '
return SkewTableau(expr=[self._mu, [[self._filling.get(((self._mu[r] + j), r), 0) for j in range((self._lambda[r] - self._mu[r]))] for r in range(len(self._lambda))][::(- 1)]])._repr_diagram()
def __eq__(self, other):
'\n Return ``True`` if the growth diagram ``other`` has the same\n shape and the same filling as ``self``.\n\n EXAMPLES:\n\n Equality ignores zeros in fillings::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G1 = GrowthDiagram(RuleRSK, {(0, 1): 1, (1, 0): 1})\n sage: G2 = GrowthDiagram(RuleRSK, {(0, 0): 0, (0, 1): 1, (1, 0): 1})\n sage: G1 == G2\n True\n\n Growth diagrams with different shapes are different::\n\n sage: G1 = GrowthDiagram(RuleRSK, [[0,1,0],[1,0]])\n sage: G2 = GrowthDiagram(RuleRSK, [[0,1,0],[1]])\n sage: G1 == G2\n False\n\n Growth diagrams with different rules are different::\n\n sage: G1 = GrowthDiagram(RuleRSK, {(0, 1): 1, (1, 0): 1})\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: G2 = GrowthDiagram(BinaryWord, {(0, 1): 1, (1, 0): 1})\n sage: G1 == G2\n False\n '
return ((type(self) is type(other)) and (self.rule == other.rule) and (self._lambda == other._lambda) and (self._mu == other._mu) and (self._filling == other._filling))
def __ne__(self, other):
'\n Return ``True`` if the growth diagram ``other`` does not have the\n same shape and the same filling as ``self``.\n\n TESTS:\n\n Equality ignores zeros in fillings::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G1 = GrowthDiagram(RuleRSK, {(0, 1): 1, (1, 0): 1})\n sage: G2 = GrowthDiagram(RuleRSK, {(0, 0): 0, (0, 1): 1, (1, 0): 1})\n sage: G1 != G2\n False\n\n Growth diagrams with different shapes are different::\n\n sage: G1 = GrowthDiagram(RuleRSK, [[0,1,0],[1,0]])\n sage: G2 = GrowthDiagram(RuleRSK, [[0,1,0],[1]])\n sage: G1 != G2\n True\n\n Growth diagrams with different rules are different::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: G1 = GrowthDiagram(RuleRSK, {(0, 1): 1, (1, 0): 1})\n sage: G2 = GrowthDiagram(BinaryWord, {(0, 1): 1, (1, 0): 1})\n sage: G1 != G2\n True\n '
return (not (self == other))
def _process_labels(self, labels):
'\n Return the list of labels such that each element has the\n correct type from the rule.\n\n .. WARNING::\n\n Assumes that ``self.rule`` is set.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: labels = [[], [1], [1,1], [1], []]\n sage: G = GrowthDiagram(RuleRSK, labels=labels) # indirect doctest\n sage: G.out_labels()[2].parent()\n Partitions\n '
rule = self.rule
if rule.has_multiple_edges:
return [(rule.normalize_vertex(val) if ((i % 2) == 0) else val) for (i, val) in enumerate(labels)]
else:
return [rule.normalize_vertex(la) for la in labels]
def _shape_from_labels(self, labels):
'\n Determine the shape of the growth diagram given a list of labels\n during initialization.\n\n The shape can be determined from the labels if the size of\n each label differs from the size of its successor.\n\n Otherwise raise an error.\n\n .. WARNING::\n\n Assumes that ``self.rule`` and ``self.rank`` is set.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: labels = [[],[2],[1],[],[1],[]]\n sage: G = GrowthDiagram(RuleRSK, labels=labels); G\n 0 1\n 1\n 1\n sage: G._shape_from_labels(G.out_labels())\n [2, 1, 1]\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted({(0, 0): 1}).out_labels()\n [[], 1, [1], 0, []]\n sage: Shifted(labels=[[], 1, [2], 0, []]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: [] has smaller rank than [2] but there is no edge of color 1 in Q\n '
rule = self.rule
is_P_edge = getattr(rule, 'is_P_edge', None)
is_Q_edge = getattr(rule, 'is_Q_edge', None)
if rule.has_multiple_edges:
def right_left_multi(la, mu, e) -> int:
if (rule.rank(la) < rule.rank(mu)):
if ((is_Q_edge is not None) and (e not in is_Q_edge(la, mu))):
raise ValueError(('%s has smaller rank than %s but there is no edge of color %s in Q' % (la, mu, e)))
return 1
elif (rule.rank(la) > rule.rank(mu)):
if ((is_P_edge is not None) and (e not in is_P_edge(mu, la))):
raise ValueError(('%s has smaller rank than %s but there is no edge of color %s in P' % (mu, la, e)))
return 0
raise ValueError('can only determine the shape of the growth diagram if ranks of successive labels differ')
return _Partitions.from_zero_one([right_left_multi(labels[i], labels[(i + 2)], labels[(i + 1)]) for i in range(0, (len(labels) - 2), 2)])
else:
def right_left(la, mu) -> int:
if (rule.rank(la) < rule.rank(mu)):
if ((is_Q_edge is not None) and (not is_Q_edge(la, mu))):
raise ValueError(('%s has smaller rank than %s but is not covered by it in Q' % (la, mu)))
return 1
elif (rule.rank(la) > rule.rank(mu)):
if ((is_P_edge is not None) and (not is_P_edge(mu, la))):
raise ValueError(('%s has smaller rank than %s but is not covered by it in P' % (mu, la)))
return 0
raise ValueError('can only determine the shape of the growth diagram if ranks of successive labels differ')
return _Partitions.from_zero_one([right_left(labels[i], labels[(i + 1)]) for i in range((len(labels) - 1))])
def _check_labels(self, labels):
'\n Check sanity of the parameter ``labels``.\n\n .. WARNING::\n\n Assumes that ``self.rule`` and ``self._lambda`` is set.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: GrowthDiagram(RuleRSK, shape=[1], labels=[[], [1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the number of labels is 2, but for this shape we need 3\n\n sage: GrowthDiagram(RuleRSK, labels=[[], [1], [2], [2,1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the number of labels is 4, but for this shape we need 1\n\n .. TODO::\n\n Can we do something more sensible when the chain\n of labels is strictly increasing?\n '
half_perimeter = self.half_perimeter()
if self.rule.has_multiple_edges:
if (not (len(labels) % 2)):
raise ValueError(('only a list of odd length can specify a path, but %s has even length' % len(labels)))
path_length = ((len(labels) + 1) / 2)
else:
path_length = len(labels)
if (path_length != half_perimeter):
raise ValueError(('the number of labels is %s, but for this shape we need %s' % (path_length, half_perimeter)))
def _process_shape(self, shape):
'\n Return a pair of partitions as lists describing the region\n of the growth diagram.\n\n TESTS:\n\n ``shape`` is a skew partition::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: filling = []\n sage: shape = SkewPartition([[4,2,1,1],[2,1,1]])\n sage: G = GrowthDiagram(RuleRSK, filling, shape) # indirect doctest\n sage: G._lambda, G._mu\n ([4, 2, 1, 1], [2, 1, 1, 0])\n\n ``shape`` is a partition::\n\n sage: filling = []\n sage: shape = Partition([3,2,1,1])\n sage: G = GrowthDiagram(RuleRSK, filling, shape) # indirect doctest\n sage: G._lambda, G._mu\n ([3, 2, 1, 1], [0, 0, 0, 0])\n '
try:
shape = _Partitions(shape)
except ValueError:
try:
shape = SkewPartition(shape)
except ValueError:
raise ValueError(('cannot make sense of shape %s' % shape))
return (list(shape[0]), (list(shape[1]) + ([0] * (len(shape[0]) - len(shape[1])))))
return (list(shape), ([0] * len(shape)))
def _process_filling_and_shape(self, filling, shape):
'\n Return a dict ``F`` such that ``F[(i,j)]`` is the element in row\n ``i`` and column ``j`` and a pair of partitions describing the\n region of the growth diagram.\n\n TESTS:\n\n ``filling`` is a dict of coordinates::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: pi = Permutation([2,3,1,6,4,5])\n sage: G = GrowthDiagram(RuleRSK, {(i,pi[i]-1):1 for i in range(len(pi))}) # indirect doctest\n sage: G._filling\n {(0, 1): 1, (1, 2): 1, (2, 0): 1, (3, 5): 1, (4, 3): 1, (5, 4): 1}\n sage: G.shape()\n [6, 6, 6, 6, 6, 6] / []\n\n ``filling`` is a dict of dicts::\n\n sage: G = GrowthDiagram(RuleRSK, {i:{pi[i]-1:1} for i in range(len(pi))}) # indirect doctest\n sage: G._filling\n {(0, 1): 1, (1, 2): 1, (2, 0): 1, (3, 5): 1, (4, 3): 1, (5, 4): 1}\n sage: G.shape()\n [6, 6, 6, 6, 6, 6] / []\n\n ``filling`` is a matrix::\n\n sage: G = GrowthDiagram(RuleRSK, pi.to_matrix()) # indirect doctest # needs sage.modules\n sage: G._filling # needs sage.modules\n {(0, 1): 1, (1, 2): 1, (2, 0): 1, (3, 5): 1, (4, 3): 1, (5, 4): 1}\n sage: G.shape() # needs sage.modules\n [6, 6, 6, 6, 6, 6] / []\n\n ``filling`` is a permutation::\n\n sage: G = GrowthDiagram(RuleRSK, pi) # indirect doctest\n sage: G._filling\n {(0, 1): 1, (1, 2): 1, (2, 0): 1, (3, 5): 1, (4, 3): 1, (5, 4): 1}\n sage: G.shape()\n [6, 6, 6, 6, 6, 6] / []\n\n ``filling`` is a list::\n\n sage: G = GrowthDiagram(RuleRSK, [3,1,4,1,5]) # indirect doctest\n sage: G._filling\n {(0, 2): 1, (1, 0): 1, (2, 3): 1, (3, 0): 1, (4, 4): 1}\n sage: G.shape()\n [5, 5, 5, 5, 5] / []\n\n ``filling`` is a list of lists::\n\n sage: G = GrowthDiagram(RuleRSK, [[1,0,1],[0,1]]) # indirect doctest\n sage: G._filling\n {(0, 0): 1, (1, 1): 1, (2, 0): 1}\n sage: G.shape()\n [3, 2] / []\n\n ``filling`` is a list of lists and shape is given::\n\n sage: G = GrowthDiagram(RuleRSK, [[1,0,1],[0,1]], # indirect doctest\n ....: shape=SkewPartition([[3,2],[1]]))\n sage: G._filling\n {(0, 0): 1, (1, 1): 1, (2, 0): 1}\n sage: G.shape()\n [3, 2] / [1]\n\n ``filling`` is empty and shape is ``None``::\n\n sage: G = GrowthDiagram(RuleRSK, {})\n sage: (G.filling(), G.shape())\n ({}, [] / [])\n '
if isinstance(filling, dict):
try:
v = next(iter(filling.values()))
if isinstance(v, dict):
F = dict()
for (i, row) in filling.items():
for (j, v) in row.items():
if (v != 0):
F[(i, j)] = int(v)
else:
F = {(i, j): v for ((i, j), v) in filling.items() if (v != 0)}
except StopIteration:
F = filling
else:
F = dict()
try:
for (i, row) in enumerate(filling):
for (j, v) in enumerate(row):
if (v != 0):
F[(j, i)] = int(v)
if (shape is None):
shape = [len(row) for row in filling]
except TypeError:
for (i, l) in enumerate(filling):
if (l > 0):
F[(i, (l - 1))] = 1
else:
F[(i, ((- l) - 1))] = (- 1)
if (shape is None):
if (F == {}):
shape = []
else:
max_row = (max((i for (i, _) in F)) + 1)
max_col = (max((j for (_, j) in F)) + 1)
shape = ([max_row] * max_col)
return (F, self._process_shape(shape))
def _grow(self):
'\n Compute the labels on the boundary opposite of the origin, given\n the filling.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: pi = Permutation([1])\n sage: G = GrowthDiagram(RuleRSK, pi) # indirect doctest\n sage: G._out_labels\n [[], [1], []]\n\n sage: pi = Permutation([1,2])\n sage: G = GrowthDiagram(RuleRSK, pi) # indirect doctest\n sage: G._out_labels\n [[], [1], [2], [1], []]\n\n sage: pi = Permutation([2,1])\n sage: G = GrowthDiagram(RuleRSK, pi) # indirect doctest\n sage: G._out_labels\n [[], [1], [1, 1], [1], []]\n\n sage: G = GrowthDiagram(RuleRSK, {(0,1):1, (1,0):1}, SkewPartition([[2,1],[1]])) # indirect doctest\n sage: G._out_labels\n [[], [1], [], [1], []]\n\n sage: G = GrowthDiagram(RuleRSK, {(1,1):1}, SkewPartition([[2,2],[1]]), labels=[[],[],[1],[],[]]) # indirect doctest\n sage: G._out_labels\n [[], [1], [2], [1], []]\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: G = GrowthDiagram(BinaryWord, {(1,1):1}, SkewPartition([[2,2],[1]]), labels=[[],[],[1],[],[]]) # indirect doctest\n sage: G._out_labels\n [word: , word: 1, word: 11, word: 1, word: ]\n '
labels = list(self._in_labels)
l = len(self._lambda)
rule = self.rule
if rule.has_multiple_edges:
for r in range(l):
for c in range(((self._mu[r] + l) - r), ((self._lambda[r] + l) - r)):
j = r
i = ((c - l) + r)
(labels[((2 * c) - 1)], labels[(2 * c)], labels[((2 * c) + 1)]) = rule.forward_rule(labels[((2 * c) - 2)], labels[((2 * c) - 1)], labels[(2 * c)], labels[((2 * c) + 1)], labels[((2 * c) + 2)], self._filling.get((i, j), 0))
else:
for r in range(l):
for c in range(((self._mu[r] + l) - r), ((self._lambda[r] + l) - r)):
j = r
i = ((c - l) + r)
labels[c] = rule.forward_rule(labels[(c - 1)], labels[c], labels[(c + 1)], self._filling.get((i, j), 0))
self._out_labels = labels
def _shrink(self):
'\n Compute the labels on the boundary near the origin, and the filling.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: filling = [[0,0,1,0,0,0,0], [0,1,0,0,0,0,0], [1,0,0,0,0,0,0],\n ....: [0,0,0,1,0,0,0], [0,0,0,0,0,0,1],\n ....: [0,0,0,0,0,1,0], [0,0,0,0,1,0,0]]\n sage: G = GrowthDiagram(RuleRSK, filling)\n sage: list(GrowthDiagram(RuleRSK, labels=G._out_labels)) == filling\n True\n\n sage: labels = [[], [1], []]\n sage: G = GrowthDiagram(RuleRSK, labels=labels) # indirect doctest\n sage: G._filling\n {(0, 0): 1}\n sage: G._in_labels\n [[], [], []]\n\n sage: labels = [[], [1], [2], [2,1], [1,1], [1], []]\n sage: G = GrowthDiagram(RuleRSK, labels=labels) # indirect doctest\n sage: G._filling\n {(0, 1): 1, (1, 2): 1, (2, 0): 1}\n sage: G._in_labels\n [[], [], [], [], [], [], []]\n\n sage: labels = [[], [1], [2], [3], [3, 1], [3, 2], [4, 2], [4, 1], [3, 1], [2, 1], [1, 1], [1], []]\n sage: G = GrowthDiagram(RuleRSK, labels=labels) # indirect doctest\n sage: G._filling\n {(0, 1): 1, (1, 2): 1, (2, 5): 1, (3, 0): 1, (4, 3): 1, (5, 4): 1}\n\n sage: labels = [[],[1],[1],[2],[2],[2,1],[2]]\n sage: G = GrowthDiagram(RuleRSK, labels=labels)\n Traceback (most recent call last):\n ...\n ValueError: can only determine the shape of the growth diagram\n if ranks of successive labels differ\n sage: G = GrowthDiagram(RuleRSK, shape=[3,2,1], labels=labels) # indirect doctest\n sage: G._filling\n {(1, 0): 1}\n sage: G._in_labels\n [[], [], [], [], [1], [1], [2]]\n\n sage: labels = [[], [1],[1],[2],[2],[2,1],[2],[2,1],[1,1],[2,1],[1,1]]\n sage: G = GrowthDiagram(RuleRSK, shape=[5,4,3,2,1], labels=labels) # indirect doctest\n sage: G._filling\n {(1, 2): 1, (2, 1): 1, (4, 0): 1}\n sage: G._in_labels\n [[], [], [], [], [], [], [1], [1], [1], [1, 1], [1, 1]]\n\n sage: labels = [[], [1],[1],[2],[2],[2,1],[2],[2,1],[1,1],[2,1],[1,1]]\n sage: G = GrowthDiagram(RuleRSK, shape=SkewPartition([[5,4,3,2,1],[3,2,1]]), labels=labels) # indirect doctest\n sage: G._filling\n {(1, 2): 1, (2, 1): 1, (4, 0): 1}\n sage: G._in_labels\n [[], [], [], [1], [1], [1], [1], [1], [1], [1, 1], [1, 1]]\n '
F = dict()
labels = list(self._out_labels)
l = len(self._lambda)
rule = self.rule
if rule.has_multiple_edges:
for r in range(l):
for c in range((self._lambda[((l - r) - 1)] + r), (self._mu[((l - r) - 1)] + r), (- 1)):
j = ((l - r) - 1)
i = ((c - r) - 1)
(labels[((2 * c) - 1)], labels[(2 * c)], labels[((2 * c) + 1)], v) = rule.backward_rule(labels[((2 * c) - 2)], labels[((2 * c) - 1)], labels[(2 * c)], labels[((2 * c) + 1)], labels[((2 * c) + 2)])
if (v != 0):
F[(i, j)] = v
else:
for r in range(l):
for c in range((self._lambda[((l - r) - 1)] + r), (self._mu[((l - r) - 1)] + r), (- 1)):
j = ((l - r) - 1)
i = ((c - r) - 1)
(labels[c], v) = rule.backward_rule(labels[(c - 1)], labels[c], labels[(c + 1)])
if (v != 0):
F[(i, j)] = v
self._in_labels = labels
self._filling = F
|
class Rule(UniqueRepresentation):
"\n Generic base class for a rule for a growth diagram.\n\n Subclasses may provide the following attributes:\n\n - ``zero`` -- the zero element of the vertices of the graphs\n\n - ``r`` -- (default: 1) the parameter in the equation `DU - UD = rI`\n\n - ``has_multiple_edges`` -- (default: ``False``) if the dual\n graded graph has multiple edges and therefore edges are\n triples consisting of two vertices and a label.\n\n - ``zero_edge`` -- (default: 0) the zero label of the\n edges of the graphs used for degenerate edges. It is\n allowed to use this label also for other edges.\n\n Subclasses may provide the following methods:\n\n - ``normalize_vertex`` -- a function that converts its input to a\n vertex.\n\n - ``vertices`` -- a function that takes a non-negative integer\n as input and returns the list of vertices on this rank.\n\n - ``rank`` -- the rank function of the dual graded graphs.\n\n - ``forward_rule`` -- a function with input ``(y, t, x,\n content)`` or ``(y, e, t, f, x, content)`` if\n ``has_multiple_edges`` is ``True``. ``(y, e, t)`` is an\n edge in the graph `P`, ``(t, f, x)`` an edge in the graph\n ``Q``. It should return the fourth vertex ``z``, or, if\n ``has_multiple_edges`` is ``True``, the path ``(g, z, h)``\n from ``y`` to ``x``.\n\n - ``backward_rule`` -- a function with input ``(y, z, x)`` or\n ``(y, g, z, h, x)`` if ``has_multiple_edges`` is ``True``.\n ``(y, g, z)`` is an edge in the graph `Q`, ``(z, h, x)`` an\n edge in the graph ``P``. It should return the fourth\n vertex and the content ``(t, content)``, or, if\n ``has_multiple_edges`` is ``True``, the path from ``y`` to\n ``x`` and the content as ``(e, t, f, content)``.\n\n - ``is_P_edge``, ``is_Q_edge`` -- functions that take two\n vertices as arguments and return ``True`` or ``False``, or,\n if multiple edges are allowed, the list of edge labels of\n the edges from the first vertex to the second in the\n respective graded graph. These are only used for checking\n user input and providing the dual graded graph, and are\n therefore not mandatory.\n\n Note that the class :class:`GrowthDiagram` is able to use\n partially implemented subclasses just fine. Suppose that\n ``MyRule`` is such a subclass. Then:\n\n - ``GrowthDiagram(MyRule, my_filling)`` requires only an\n implementation of ``forward_rule``, ``zero`` and possibly\n ``has_multiple_edges``.\n\n - ``GrowthDiagram(MyRule, labels=my_labels, shape=my_shape)``\n requires only an implementation of ``backward_rule`` and\n possibly ``has_multiple_edges``, provided that the labels\n ``my_labels`` are given as needed by ``backward_rule``.\n\n - ``GrowthDiagram(MyRule, labels=my_labels)`` additionally needs\n an implementation of ``rank`` to deduce the shape.\n\n In particular, this allows to implement rules which do not quite\n fit Fomin's notion of dual graded graphs. An example would be\n Bloom and Saracino's variant of the RSK correspondence [BS2012]_,\n where a backward rule is not available.\n\n Similarly:\n\n - ``MyRule.P_graph`` only requires an implementation of\n ``vertices``, ``is_P_edge`` and possibly ``has_multiple_edges``\n is required, mutatis mutandis for ``MyRule.Q_graph``.\n\n - ``MyRule._check_duality`` requires ``P_graph`` and ``Q_graph``.\n\n In particular, this allows to work with dual graded graphs\n without local rules.\n "
has_multiple_edges = False
zero_edge = 0
r = 1
def normalize_vertex(self, v):
'\n Return ``v`` as a vertex of the dual graded graph.\n\n This is a default implementation, returning its argument.\n\n EXAMPLES::\n\n sage: from sage.combinat.growth import Rule\n sage: Rule().normalize_vertex("hello") == "hello"\n True\n '
return v
def __call__(self, *args, **kwds):
'\n Return the growth diagram corresponding to the parameters.\n\n This provides a shorthand for calling :class:`GrowthDiagram`\n directly.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: RuleRSK([2,3,1], shape=[3,2,2])\n 0 0 1\n 1 0\n 0 1\n\n sage: RuleRSK(labels=[[], [1], [2], [1], [], [1], []])\n 0 0 1\n 1 0\n 0 1\n '
return GrowthDiagram(self, *args, **kwds)
def _check_duality(self, n):
'\n Raise an error if the graphs are not `r`-dual at level ``n``.\n\n `P` and `Q` are `r`-dual if `DU = UD + rI` on the free\n `\\ZZ`-module `\\ZZ[V]`, where `D` is the down operator of `Q`,\n assigning to each vertex the formal sum of its predecessors,\n `U` is the up operator of `P`, assigning to each vertex the\n formal sum of its successors, and `I` is the identity\n operator.\n\n INPUT:\n\n - ``n`` -- a positive integer specifying which rank of\n the graph to test\n\n EXAMPLES:\n\n For binary words, we have indeed provided dual graded graphs::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord._check_duality(3)\n\n The following two graphs are not `1`-dual::\n\n sage: from sage.combinat.growth import Rule\n sage: class RuleWrong(Rule):\n ....: def vertices(self, n): return Partitions(n)\n ....: def is_Q_edge(self, v, w):\n ....: return (v, w) in [([1],[2]), ([2],[3])]\n ....: def is_P_edge(self, v, w):\n ....: return (v, w) in [([1],[2]), ([1],[1,1]), ([2],[3])]\n\n sage: RuleWrong()._check_duality(2)\n Traceback (most recent call last):\n ...\n ValueError: D U - U D differs from 1 I for vertex [2]:\n D U = [[2]]\n U D + 1 I = [[1, 1], [2], [2]]\n '
if self.has_multiple_edges:
def check_vertex(w, P, Q):
DUw = [v[0] for uw in P.outgoing_edges(w) for v in Q.incoming_edges(uw[1])]
UDw = [v[1] for lw in Q.incoming_edges(w) for v in P.outgoing_edges(lw[0])]
UDw.extend(([w] * self.r))
if (sorted(DUw) != sorted(UDw)):
raise ValueError(('D U - U D differs from %s I for vertex %s:\nD U = %s\nU D + %s I = %s' % (self.r, w, DUw, self.r, UDw)))
else:
def check_vertex(w, P, Q):
DUw = [v for uw in P.upper_covers(w) for v in Q.lower_covers(uw)]
UDw = [v for lw in Q.lower_covers(w) for v in P.upper_covers(lw)]
UDw.extend(([w] * self.r))
if (sorted(DUw) != sorted(UDw)):
raise ValueError(('D U - U D differs from %s I for vertex %s:\nD U = %s\nU D + %s I = %s' % (self.r, w, DUw, self.r, UDw)))
P = self.P_graph((n + 2))
Q = self.Q_graph((n + 2))
for w in self.vertices(n):
check_vertex(w, P, Q)
def P_graph(self, n):
'\n Return the first ``n`` levels of the first dual graded graph.\n\n The non-degenerate edges in the vertical direction come from\n this graph.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Domino.P_graph(3)\n Finite poset containing 8 elements\n '
if self.has_multiple_edges:
D = DiGraph([(x, y, e) for k in range((n - 1)) for x in self.vertices(k) for y in self.vertices((k + 1)) for e in self.is_P_edge(x, y)], multiedges=True)
return D
else:
return Poset(([w for k in range(n) for w in self.vertices(k)], self.is_P_edge), cover_relations=True)
def Q_graph(self, n):
'\n Return the first ``n`` levels of the second dual graded graph.\n\n The non-degenerate edges in the horizontal direction come\n from this graph.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Q = Domino.Q_graph(3); Q\n Finite poset containing 8 elements\n\n sage: Q.upper_covers(Partition([1,1]))\n [[1, 1, 1, 1], [3, 1], [2, 2]]\n '
if self.has_multiple_edges:
D = DiGraph([(x, y, e) for k in range((n - 1)) for x in self.vertices(k) for y in self.vertices((k + 1)) for e in self.is_Q_edge(x, y)], multiedges=True)
return D
else:
return Poset(([w for k in range(n) for w in self.vertices(k)], self.is_Q_edge), cover_relations=True)
|
class RuleShiftedShapes(Rule):
"\n A class modelling the Schensted correspondence for shifted\n shapes.\n\n This agrees with Sagan [Sag1987]_ and Worley's [Wor1984]_, and\n Haiman's [Hai1989]_ insertion algorithms, see Proposition 4.5.2\n of [Fom1995]_.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: GrowthDiagram(Shifted, [3,1,2])\n 0 1 0\n 0 0 1\n 1 0 0\n\n The vertices of the dual graded graph are shifted shapes::\n\n sage: Shifted.vertices(3)\n Partitions of the integer 3 satisfying constraints max_slope=-1\n\n Let us check the example just before Corollary 3.2 in [Sag1987]_.\n Note that, instead of passing the rule to :class:`GrowthDiagram`,\n we can also call the rule to create growth diagrams::\n\n sage: G = Shifted([2,6,5,1,7,4,3])\n sage: G.P_chain()\n [[], 0, [1], 0, [2], 0, [3], 0, [3, 1], 0, [3, 2], 0, [4, 2], 0, [5, 2]]\n sage: G.Q_chain()\n [[], 1, [1], 2, [2], 1, [2, 1], 3, [3, 1], 2, [4, 1], 3, [4, 2], 3, [5, 2]]\n\n TESTS::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.zero\n []\n\n sage: Shifted._check_duality(4)\n\n Check that the rules are bijective::\n\n sage: all(Shifted(labels=Shifted(pi).out_labels()).to_word() == pi\n ....: for pi in Permutations(5))\n True\n sage: pi = Permutations(10).random_element()\n sage: G = Shifted(pi)\n sage: list(Shifted(labels=G.out_labels())) == list(G)\n True\n "
zero = _make_partition([])
has_multiple_edges = True
def normalize_vertex(self, v):
'\n Return ``v`` as a partition.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.normalize_vertex([3,1]).parent()\n Partitions\n '
return _make_partition(v)
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.vertices(3)\n Partitions of the integer 3 satisfying constraints max_slope=-1\n '
if (n == 0):
return [self.zero]
else:
return Partitions(n, max_slope=(- 1))
def rank(self, v):
'\n Return the rank of ``v``: the size of the shifted partition.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.rank(Shifted.vertices(3)[0])\n 3\n '
return v.size()
def is_Q_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `Q`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``w`` is obtained from ``v`` by adding a\n cell. It is a black (color 1) edge, if the cell is on the\n diagonal, otherwise it can be blue or red (color 2 or 3).\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: v = Shifted.vertices(2)[0]; v\n [2]\n sage: [(w, Shifted.is_Q_edge(v, w)) for w in Shifted.vertices(3)]\n [([3], [2, 3]), ([2, 1], [1])]\n sage: all(Shifted.is_Q_edge(v, w) == [] for w in Shifted.vertices(4))\n True\n '
if ((self.rank(v) + 1) != self.rank(w)):
return []
try:
l = SkewPartition([w, v]).cells()
except ValueError:
return []
else:
if (l[0][1] == 0):
return [1]
else:
return [2, 3]
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``w`` contains ``v``.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: v = Shifted.vertices(2)[0]; v\n [2]\n sage: [w for w in Shifted.vertices(3) if Shifted.is_P_edge(v, w)]\n [[3], [2, 1]]\n '
if ((self.rank(v) + 1) != self.rank(w)):
return []
return ([0] if w.contains(v) else [])
def P_symbol(self, P_chain):
"\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a shifted tableau.\n\n EXAMPLES:\n\n Check the example just before Corollary 3.2 in [Sag1987]_::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: G = Shifted([2,6,5,1,7,4,3])\n sage: G.P_symbol().pp()\n 1 2 3 6 7\n 4 5\n\n Check the example just before Corollary 8.2 in [SS1990]_::\n\n sage: T = ShiftedPrimedTableau([[4],[1],[5]], skew=[3,1])\n sage: T.pp()\n . . . 4\n . 1\n 5\n sage: U = ShiftedPrimedTableau([[1],[3.5],[5]], skew=[3,1])\n sage: U.pp()\n . . . 1\n . 4'\n 5\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: labels = [mu if is_even(i) else 0\n ....: for i, mu in enumerate(T.to_chain()[::-1])] + U.to_chain()[1:]\n sage: G = Shifted({(1,2):1, (2,1):1}, shape=[5,5,5,5,5], labels=labels)\n sage: G.P_symbol().pp()\n . . . . 2\n . . 1 3\n . 4 5\n\n "
chain = P_chain[::2]
shape = chain[(- 1)]
T = [[None for _ in range(r)] for r in shape]
for i in range(1, len(chain)):
la = chain[i]
mu = chain[(i - 1)]
mu += ([0] * (len(la) - len(mu)))
for r in range(len(la)):
for c in range(mu[r], la[r]):
T[r][c] = i
skew = _make_partition([row.count(None) for row in T])
T = [[e for e in row if (e is not None)] for row in T]
return ShiftedPrimedTableau(T, skew=skew)
def Q_symbol(self, Q_chain):
"\n Return the labels along the horizontal boundary of a rectangular\n growth diagram as a skew tableau.\n\n EXAMPLES:\n\n Check the example just before Corollary 3.2 in [Sag1987]_::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: G = Shifted([2,6,5,1,7,4,3])\n sage: G.Q_symbol().pp()\n 1 2 4' 5 7'\n 3 6'\n\n Check the example just before Corollary 8.2 in [SS1990]_::\n\n sage: T = ShiftedPrimedTableau([[4],[1],[5]], skew=[3,1])\n sage: T.pp()\n . . . 4\n . 1\n 5\n sage: U = ShiftedPrimedTableau([[1],[3.5],[5]], skew=[3,1])\n sage: U.pp()\n . . . 1\n . 4'\n 5\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: labels = [mu if is_even(i) else 0\n ....: for i, mu in enumerate(T.to_chain()[::-1])] + U.to_chain()[1:]\n sage: G = Shifted({(1,2):1, (2,1):1}, shape=[5,5,5,5,5], labels=labels)\n sage: G.Q_symbol().pp()\n . . . . 2\n . . 1 4'\n . 3' 5'\n\n "
chain = Q_chain
shape = chain[(- 1)]
T = [[None for _ in range(r)] for r in shape]
for i in range(1, ((len(chain) + 1) // 2)):
la = chain[(2 * i)]
if (chain[((2 * i) - 1)] == 3):
prime = 0.5
else:
prime = 0
mu = chain[(2 * (i - 1))]
mu += ([0] * (len(la) - len(mu)))
for r in range(len(la)):
for c in range(mu[r], la[r]):
T[r][c] = (i - prime)
skew = _make_partition([row.count(None) for row in T])
T = [[e for e in row if (e is not None)] for row in T]
return ShiftedPrimedTableau(T, skew=skew)
def forward_rule(self, y, e, t, f, x, content):
'\n Return the output path given two incident edges and the content.\n\n See [Fom1995]_ Lemma 4.5.1, page 38.\n\n INPUT:\n\n - ``y, e, t, f, x`` -- a path of three partitions and two\n colors from a cell in a growth diagram, labelled as::\n\n t f x\n e\n y\n\n - ``content`` -- `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The two colors and the fourth partition ``g``, ``z``, ``h``\n according to Sagan-Worley insertion.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.forward_rule([], 0, [], 0, [], 1)\n (1, [1], 0)\n\n sage: Shifted.forward_rule([1], 0, [1], 0, [1], 1)\n (2, [2], 0)\n\n if ``x != y``::\n\n sage: Shifted.forward_rule([3], 0, [2], 1, [2,1], 0)\n (1, [3, 1], 0)\n\n sage: Shifted.forward_rule([2,1], 0, [2], 2, [3], 0)\n (2, [3, 1], 0)\n\n if ``x == y != t``::\n\n sage: Shifted.forward_rule([3], 0, [2], 2, [3], 0)\n (1, [3, 1], 0)\n\n sage: Shifted.forward_rule([3,1], 0, [2,1], 2, [3,1], 0)\n (2, [3, 2], 0)\n\n sage: Shifted.forward_rule([2,1], 0, [2], 1, [2,1], 0)\n (3, [3, 1], 0)\n\n sage: Shifted.forward_rule([3], 0, [2], 3, [3], 0)\n (3, [4], 0)\n\n '
if (e != 0):
raise ValueError('the P-graph should not be colored')
h = 0
if (x == t == y):
if (f != 0):
raise ValueError('degenerate edge f should have color 0')
if (content == 0):
(g, z) = (0, x)
elif (content == 1):
if (not x):
(g, z) = (1, _Partitions(x).add_cell(0))
else:
(g, z) = (2, _make_partition(x).add_cell(0))
else:
raise NotImplementedError
elif (content != 0):
raise ValueError(('for y=%s, t=%s, x=%s, the content should be 0 but is %s' % (y, t, x, content)))
elif (x != t == y):
(g, z) = (f, x)
elif (x == t != y):
if (f != 0):
raise ValueError('degenerate edge f should have color 0')
(g, z) = (f, y)
elif (x != y):
row = SkewPartition([x, t]).cells()[0][0]
(g, z) = (f, _make_partition(y).add_cell(row))
elif ((x == y != t) and (f == 2)):
row = (1 + SkewPartition([x, t]).cells()[0][0])
if (row == len(y)):
(g, z) = (1, _make_partition(y).add_cell(row))
else:
(g, z) = (2, _make_partition(y).add_cell(row))
elif ((x == y != t) and (f in [1, 3])):
c = SkewPartition([x, t]).cells()[0]
col = ((c[0] + c[1]) + 1)
for i in range(len(y)):
if ((i + y[i]) == col):
z = ((y[:i] + [(y[i] + 1)]) + y[(i + 1):])
break
g = 3
else:
raise NotImplementedError
return (g, _make_partition(z), h)
def backward_rule(self, y, g, z, h, x):
'\n Return the input path and the content given two incident edges.\n\n See [Fom1995]_ Lemma 4.5.1, page 38.\n\n INPUT:\n\n - ``y, g, z, h, x`` -- a path of three partitions and two\n colors from a cell in a growth diagram, labelled as::\n\n x\n h\n y g z\n\n OUTPUT:\n\n A tuple ``(e, t, f, content)`` consisting of the shape ``t``\n of the fourth word, the colours of the incident edges and the\n content of the cell according to Sagan - Worley insertion.\n\n EXAMPLES::\n\n sage: Shifted = GrowthDiagram.rules.ShiftedShapes()\n sage: Shifted.backward_rule([], 1, [1], 0, [])\n (0, [], 0, 1)\n\n sage: Shifted.backward_rule([1], 2, [2], 0, [1])\n (0, [1], 0, 1)\n\n if ``x != y``::\n\n sage: Shifted.backward_rule([3], 1, [3, 1], 0, [2,1])\n (0, [2], 1, 0)\n\n sage: Shifted.backward_rule([2,1], 2, [3, 1], 0, [3])\n (0, [2], 2, 0)\n\n if ``x == y != t``::\n\n sage: Shifted.backward_rule([3], 1, [3, 1], 0, [3])\n (0, [2], 2, 0)\n\n sage: Shifted.backward_rule([3,1], 2, [3, 2], 0, [3,1])\n (0, [2, 1], 2, 0)\n\n sage: Shifted.backward_rule([2,1], 3, [3, 1], 0, [2,1])\n (0, [2], 1, 0)\n\n sage: Shifted.backward_rule([3], 3, [4], 0, [3])\n (0, [2], 3, 0)\n '
if (h != 0):
raise ValueError('the P-graph should not be colored')
if (x == y == z):
if (g != 0):
raise ValueError('degenerate edge g should have color 0')
return (0, x, 0, 0)
elif (x == z != y):
return (0, y, g, 0)
elif (x != z == y):
if (g != 0):
raise ValueError('degenerate edge g should have color 0')
return (0, x, 0, 0)
elif (x != y):
row = SkewPartition([z, x]).cells()[0][0]
return (0, _make_partition(y).remove_cell(row), g, 0)
else:
(row, col) = SkewPartition([z, x]).cells()[0]
if ((row > 0) and (g in [1, 2])):
return (0, _make_partition(y).remove_cell((row - 1)), 2, 0)
elif ((row == 0) and (g in [1, 2])):
return (0, y, 0, 1)
else:
for i in range((len(y) - 1), (- 1), (- 1)):
if ((i + y[i]) == (col + row)):
if (y[i] == 1):
t = y[:i]
return (0, t, 1, 0)
else:
t = ((y[:i] + [(y[i] - 1)]) + y[(i + 1):])
return (0, t, 3, 0)
raise ValueError('this should not happen')
|
class RuleLLMS(Rule):
'\n A rule modelling the Schensted correspondence for affine\n permutations.\n\n EXAMPLES::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: GrowthDiagram(LLMS3, [3,1,2])\n 0 1 0\n 0 0 1\n 1 0 0\n\n The vertices of the dual graded graph are\n :class:`~sage.combinat.core.Cores`::\n\n sage: LLMS3.vertices(4)\n 3-Cores of length 4\n\n Let us check example of Figure 1 in [LS2007]_. Note that,\n instead of passing the rule to :class:`GrowthDiagram`, we can\n also call the rule to create growth diagrams::\n\n sage: G = LLMS3([4,1,2,6,3,5]); G\n 0 1 0 0 0 0\n 0 0 1 0 0 0\n 0 0 0 0 1 0\n 1 0 0 0 0 0\n 0 0 0 0 0 1\n 0 0 0 1 0 0\n\n The :meth:`P_symbol` is a\n :class:`~sage.combinat.k_tableau.StrongTableau`::\n\n sage: G.P_symbol().pp()\n -1 -2 -3 -5\n 3 5\n -4 -6\n 5\n 6\n\n The :meth:`Q_symbol` is a\n :class:`~sage.combinat.k_tableau.WeakTableau`::\n\n sage: G.Q_symbol().pp()\n 1 3 4 5\n 2 5\n 3 6\n 5\n 6\n\n Let us also check Example 6.2 in [LLMSSZ2013]_::\n\n sage: G = LLMS3([4,1,3,2])\n sage: G.P_symbol().pp()\n -1 -2 3\n -3\n -4\n\n sage: G.Q_symbol().pp()\n 1 3 4\n 2\n 3\n\n TESTS::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: LLMS3.zero\n []\n '
zero_edge = None
has_multiple_edges = True
def __init__(self, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: TestSuite(LLMS3).run()\n '
self.k = k
self.zero = Core([], k)
def normalize_vertex(self, v):
'\n Convert ``v`` to a `k`-core.\n\n EXAMPLES::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: LLMS3.normalize_vertex([3,1]).parent()\n 3-Cores of length 3\n '
return Core(v, self.k)
def rank(self, v):
'\n Return the rank of ``v``: the length of the core.\n\n EXAMPLES::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: LLMS3.rank(LLMS3.vertices(3)[0])\n 3\n '
return v.length()
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: LLMS3.vertices(2)\n 3-Cores of length 2\n '
return Cores(self.k, length=n)
def is_Q_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `Q`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``w`` is a weak cover of ``v``, see\n :meth:`~sage.combinat.core.Core.weak_covers()`.\n\n EXAMPLES::\n\n sage: LLMS4 = GrowthDiagram.rules.LLMS(4)\n sage: v = LLMS4.vertices(3)[1]; v\n [2, 1]\n sage: [w for w in LLMS4.vertices(4) if len(LLMS4.is_Q_edge(v, w)) > 0]\n [[2, 2], [3, 1, 1]]\n sage: all(LLMS4.is_Q_edge(v, w) == [] for w in LLMS4.vertices(5))\n True\n '
return ([None] if (w in v.weak_covers()) else [])
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n For two k-cores v and w containing v, there are as many edges as\n there are components in the skew partition w/v. These\n components are ribbons, and therefore contain a unique cell\n with maximal content. We index the edge with this content.\n\n EXAMPLES::\n\n sage: LLMS4 = GrowthDiagram.rules.LLMS(4)\n sage: v = LLMS4.vertices(2)[0]; v\n [2]\n sage: [(w, LLMS4.is_P_edge(v, w)) for w in LLMS4.vertices(3)]\n [([3], [2]), ([2, 1], [-1]), ([1, 1, 1], [])]\n sage: all(LLMS4.is_P_edge(v, w) == [] for w in LLMS4.vertices(4))\n True\n '
if (w in v.strong_covers()):
T = SkewPartition([w.to_partition(), v.to_partition()])
return [max([(j - i) for (i, j) in c]) for c in T.cell_poset().connected_components()]
else:
return []
def P_symbol(self, P_chain):
'\n Return the labels along the vertical boundary of a\n rectangular growth diagram as a skew\n :class:`~sage.combinat.k_tableau.StrongTableau`.\n\n EXAMPLES::\n\n sage: LLMS4 = GrowthDiagram.rules.LLMS(4)\n sage: G = LLMS4([3,4,1,2])\n sage: G.P_symbol().pp()\n -1 -2\n -3 -4\n '
C = P_chain
T = SkewTableau(chain=C[::2])
S = T.to_list()
for (entry, content) in enumerate(C[1::2], 1):
for (i, j) in T.cells_containing(entry):
if ((j - i) == content):
S[i][j] = (- S[i][j])
break
return StrongTableau(S, (self.k - 1))
def Q_symbol(self, Q_chain):
'\n Return the labels along the horizontal boundary of a\n rectangular growth diagram as a skew\n :class:`~sage.combinat.k_tableau.WeakTableau`.\n\n EXAMPLES::\n\n sage: LLMS4 = GrowthDiagram.rules.LLMS(4)\n sage: G = LLMS4([3,4,1,2])\n sage: G.Q_symbol().pp()\n 1 2\n 3 4\n '
return WeakTableau(SkewTableau(chain=Q_chain[::2]), (self.k - 1))
def forward_rule(self, y, e, t, f, x, content):
'\n Return the output path given two incident edges and the content.\n\n See [LS2007]_ Section 3.4 and [LLMSSZ2013]_ Section 6.3.\n\n INPUT:\n\n - ``y, e, t, f, x`` -- a path of three partitions and two\n colors from a cell in a growth diagram, labelled as::\n\n t f x\n e\n y\n\n - ``content`` -- `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The two colors and the fourth partition g, z, h according to\n LLMS insertion.\n\n EXAMPLES::\n\n sage: LLMS3 = GrowthDiagram.rules.LLMS(3)\n sage: LLMS4 = GrowthDiagram.rules.LLMS(4)\n\n sage: Z = LLMS3.zero\n sage: LLMS3.forward_rule(Z, None, Z, None, Z, 0)\n (None, [], None)\n\n sage: LLMS3.forward_rule(Z, None, Z, None, Z, 1)\n (None, [1], 0)\n\n sage: Y = Core([3,1,1], 3)\n sage: LLMS3.forward_rule(Y, None, Y, None, Y, 1)\n (None, [4, 2, 1, 1], 3)\n\n if ``x != y``::\n\n sage: Y = Core([1,1], 3); T = Core([1], 3); X = Core([2], 3)\n sage: LLMS3.forward_rule(Y, -1, T, None, X, 0)\n (None, [2, 1, 1], -1)\n\n sage: Y = Core([2], 4); T = Core([1], 4); X = Core([1,1], 4)\n sage: LLMS4.forward_rule(Y, 1, T, None, X, 0)\n (None, [2, 1], 1)\n\n sage: Y = Core([2,1,1], 3); T = Core([2], 3); X = Core([3,1], 3)\n sage: LLMS3.forward_rule(Y, -1, T, None, X, 0)\n (None, [3, 1, 1], -2)\n\n if ``x == y != t``::\n\n sage: Y = Core([1], 3); T = Core([], 3); X = Core([1], 3)\n sage: LLMS3.forward_rule(Y, 0, T, None, X, 0)\n (None, [1, 1], -1)\n\n sage: Y = Core([1], 4); T = Core([], 4); X = Core([1], 4)\n sage: LLMS4.forward_rule(Y, 0, T, None, X, 0)\n (None, [1, 1], -1)\n\n sage: Y = Core([2,1], 4); T = Core([1,1], 4); X = Core([2,1], 4)\n sage: LLMS4.forward_rule(Y, 1, T, None, X, 0)\n (None, [2, 2], 0)\n '
if (f is not None):
raise ValueError('the Q-graph should not be colored')
g = None
if (x == t == y):
if (e is not None):
raise ValueError('degenerate edge e should have color None')
if (content == 0):
(z, h) = (x, None)
elif (content == 1):
if (t.size() == 0):
z = t.affine_symmetric_group_simple_action(0)
else:
z = t.affine_symmetric_group_simple_action((t[0] % self.k))
h = (z[0] - 1)
else:
assert False, 'BUG in RuleLLMS'
elif (content != 0):
raise ValueError(('for y=%s, t=%s, x=%s, the content should be 0 but is %s' % (y, t, x, content)))
elif (x != t == y):
if (e is not None):
raise ValueError('degenerate edge e should have color None')
(z, h) = (x, e)
elif (x == t != y):
(z, h) = (y, e)
else:
qx = SkewPartition([x.to_partition(), t.to_partition()])
qy = SkewPartition([y.to_partition(), t.to_partition()])
if (not all(((c in qx.cells()) for c in qy.cells()))):
res = [((j - i) % self.k) for (i, j) in qx.cells()]
assert (len(set(res)) == 1)
r = res[0]
z = y.affine_symmetric_group_simple_action(r)
if ((e % self.k) == r):
h = (e - 1)
else:
h = e
elif (x == y != t):
cprime = sorted([c for c in y.to_partition().addable_cells() if ((c[1] - c[0]) <= e)], key=(lambda c: (- (c[1] - c[0]))))[0]
h = (cprime[1] - cprime[0])
z = y.affine_symmetric_group_simple_action((h % self.k))
return (g, z, h)
|
class RuleBinaryWord(Rule):
'\n A rule modelling a Schensted-like correspondence for binary words.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: GrowthDiagram(BinaryWord, [3,1,2])\n 0 1 0\n 0 0 1\n 1 0 0\n\n The vertices of the dual graded graph are binary words::\n\n sage: BinaryWord.vertices(3)\n [word: 100, word: 101, word: 110, word: 111]\n\n Note that, instead of passing the rule to :class:`GrowthDiagram`,\n we can also use call the rule to create growth diagrams. For\n example::\n\n sage: BinaryWord([2,4,1,3]).P_chain()\n [word: , word: 1, word: 10, word: 101, word: 1101]\n sage: BinaryWord([2,4,1,3]).Q_chain()\n [word: , word: 1, word: 11, word: 110, word: 1101]\n\n The Kleitman Greene invariant is the descent word, encoded by the\n positions of the zeros::\n\n sage: pi = Permutation([4,1,8,3,6,5,2,7,9])\n sage: G = BinaryWord(pi); G\n 0 1 0 0 0 0 0 0 0\n 0 0 0 0 0 0 1 0 0\n 0 0 0 1 0 0 0 0 0\n 1 0 0 0 0 0 0 0 0\n 0 0 0 0 0 1 0 0 0\n 0 0 0 0 1 0 0 0 0\n 0 0 0 0 0 0 0 1 0\n 0 0 1 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 1\n sage: pi.descents()\n [1, 3, 5, 6]\n\n TESTS::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord.zero\n word:\n sage: G = BinaryWord(labels=[[1,1],[1,1,0],[0,1]])\n Traceback (most recent call last):\n ...\n ValueError: 01 has smaller rank than 110 but is not covered by it in P\n\n sage: G = BinaryWord(labels=[[1,1],[1,0,1],[0,1]])\n Traceback (most recent call last):\n ...\n ValueError: 11 has smaller rank than 101 but is not covered by it in Q\n\n Check duality::\n\n sage: BinaryWord._check_duality(4)\n\n Check that the rules are bijective::\n\n sage: all(BinaryWord(labels=BinaryWord(pi).out_labels()).to_word()\n ....: == pi for pi in Permutations(4))\n True\n sage: pi = Permutations(10).random_element()\n sage: G = BinaryWord(pi)\n sage: list(BinaryWord(labels=G.out_labels())) == list(G)\n True\n\n Test that the Kleitman Greene invariant is indeed the descent word::\n\n sage: r = 4\n sage: all(Word([0 if i in w.descents() else 1 for i in range(r)])\n ....: == BinaryWord(w).out_labels()[r]\n ....: for w in Permutations(r))\n True\n '
zero = Word([], alphabet=[0, 1])
def normalize_vertex(self, v):
'\n Return ``v`` as a binary word.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord.normalize_vertex([0,1]).parent()\n Finite words over {0, 1}\n '
return Word(v, alphabet=[0, 1])
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord.vertices(3)\n [word: 100, word: 101, word: 110, word: 111]\n '
if (n == 0):
return [self.zero]
else:
w1 = Word([1], [0, 1])
return [(w1 + w) for w in Words([0, 1], (n - 1))]
def rank(self, v):
'\n Return the rank of ``v``: number of letters of the word.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: BinaryWord.rank(BinaryWord.vertices(3)[0])\n 3\n '
return len(v)
def is_Q_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `Q`-edge of ``self``.\n\n ``(w, v)`` is an edge if ``w`` is obtained from ``v`` by\n appending a letter.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: v = BinaryWord.vertices(2)[0]; v\n word: 10\n sage: [w for w in BinaryWord.vertices(3) if BinaryWord.is_Q_edge(v, w)]\n [word: 100, word: 101]\n sage: [w for w in BinaryWord.vertices(4) if BinaryWord.is_Q_edge(v, w)]\n []\n '
return (w[:(- 1)] == v)
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``v`` is obtained from ``w`` by\n deleting a letter.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: v = BinaryWord.vertices(2)[1]; v\n word: 11\n sage: [w for w in BinaryWord.vertices(3) if BinaryWord.is_P_edge(v, w)]\n [word: 101, word: 110, word: 111]\n sage: [w for w in BinaryWord.vertices(4) if BinaryWord.is_P_edge(v, w)]\n []\n '
return ((len(w) == (len(v) + 1)) and v.is_subword_of(w))
def forward_rule(self, y, t, x, content):
"\n Return the output shape given three shapes and the content.\n\n See [Fom1995]_ Lemma 4.6.1, page 40.\n\n INPUT:\n\n - ``y, t, x`` -- three binary words from a cell in a growth\n diagram, labelled as::\n\n t x\n y\n\n - ``content`` -- `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The fourth binary word ``z`` according to Viennot's\n bijection [Vie1983]_.\n\n EXAMPLES::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n\n sage: BinaryWord.forward_rule([], [], [], 1)\n word: 1\n\n sage: BinaryWord.forward_rule([1], [1], [1], 1)\n word: 11\n\n if ``x != y`` append last letter of ``x`` to ``y``::\n\n sage: BinaryWord.forward_rule([1,0], [1], [1,1], 0)\n word: 101\n\n if ``x == y != t`` append ``0`` to ``y``::\n\n sage: BinaryWord.forward_rule([1,1], [1], [1,1], 0)\n word: 110\n "
if (x == t == y):
if (content == 0):
z = x
elif (content == 1):
z = Word((list(y) + [1]), alphabet=[0, 1])
else:
raise NotImplementedError
elif (content != 0):
raise ValueError(('for y=%s, t=%s, x=%s, the content should be 0 but is %s' % (y, t, x, content)))
elif (x != t == y):
z = x
elif (x == t != y):
z = y
elif (x != y):
z = Word((list(y) + [x[(- 1)]]), alphabet=[0, 1])
elif (x == y != t):
z = Word((list(y) + [0]), alphabet=[0, 1])
else:
raise NotImplementedError
return z
def backward_rule(self, y, z, x):
"\n Return the content and the input shape.\n\n See [Fom1995]_ Lemma 4.6.1, page 40.\n\n - ``y, z, x`` -- three binary words from a cell in a growth diagram,\n labelled as::\n\n x\n y z\n\n OUTPUT:\n\n A pair ``(t, content)`` consisting of the shape of the fourth\n word and the content of the cell according to Viennot's\n bijection [Vie1983]_.\n\n TESTS::\n\n sage: BinaryWord = GrowthDiagram.rules.BinaryWord()\n sage: w = [4,1,8,3,6,5,2,7,9]; G = GrowthDiagram(BinaryWord, w)\n sage: BinaryWord(labels=G.out_labels()).to_word() == w # indirect doctest\n True\n "
if (x == y == z):
return (x, 0)
elif (x == z != y):
return (y, 0)
elif (x != z == y):
return (x, 0)
elif ((x == y) and (len(z) > 0) and (z[(- 1)] == 1)):
return (x, 1)
else:
return (x[:(- 1)], 0)
|
class RuleSylvester(Rule):
'\n A rule modelling a Schensted-like correspondence for binary trees.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: GrowthDiagram(Sylvester, [3,1,2])\n 0 1 0\n 0 0 1\n 1 0 0\n\n The vertices of the dual graded graph are\n :class:`~sage.combinat.binary_tree.BinaryTrees`::\n\n sage: Sylvester.vertices(3)\n Binary trees of size 3\n\n The :meth:`~sage.combinat.growth.Rule.P_graph` is also known as\n the bracket tree, the :meth:`~sage.combinat.growth.Rule.Q_graph`\n is the lattice of finite order ideals of the infinite binary\n tree, see Example 2.4.6 in [Fom1994]_.\n\n For a permutation, the :meth:`P_symbol` is the binary search\n tree, the :meth:`Q_symbol` is the increasing tree corresponding\n to the inverse permutation. Note that, instead of passing the\n rule to :class:`GrowthDiagram`, we can also call the rule to\n create growth diagrams. From [Nze2007]_::\n\n sage: pi = Permutation([3,5,1,4,2,6]); G = Sylvester(pi); G\n 0 0 1 0 0 0\n 0 0 0 0 1 0\n 1 0 0 0 0 0\n 0 0 0 1 0 0\n 0 1 0 0 0 0\n 0 0 0 0 0 1\n sage: ascii_art(G.P_symbol())\n __3__\n / \\\n 1 5\n \\ / \\\n 2 4 6\n sage: ascii_art(G.Q_symbol())\n __1__\n / \\\n 3 2\n \\ / \\\n 5 4 6\n\n sage: all(Sylvester(pi).P_symbol() == pi.binary_search_tree()\n ....: for pi in Permutations(5))\n True\n\n sage: all(Sylvester(pi).Q_symbol() == pi.inverse().increasing_tree()\n ....: for pi in Permutations(5))\n True\n\n TESTS::\n\n sage: Sylvester.zero\n .\n\n sage: B = BinaryTree; R = B([None,[]]); L = B([[],None])\n sage: T = B([[],[]]); S = B([L,None])\n sage: G = Sylvester(labels=[R, T, R])\n Traceback (most recent call last):\n ...\n ValueError: [., [., .]] has smaller rank than [[., .], [., .]]\n but is not covered by it in P\n\n sage: G = Sylvester(labels=[R, S, R])\n Traceback (most recent call last):\n ...\n ValueError: [., [., .]] has smaller rank than [[[., .], .], .]\n but is not covered by it in Q\n\n Check duality::\n\n sage: Sylvester._check_duality(4)\n\n Check that the rules are bijective::\n\n sage: all(Sylvester(labels=GrowthDiagram(Sylvester, pi).out_labels()).to_word()\n ....: == pi for pi in Permutations(4))\n True\n sage: pi = Permutations(10).random_element()\n sage: G = GrowthDiagram(Sylvester, pi)\n sage: list(Sylvester(labels=G.out_labels())) == list(G)\n True\n '
zero = BinaryTree()
def normalize_vertex(self, v):
'\n Return ``v`` as a binary tree.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: Sylvester.normalize_vertex([[],[]]).parent()\n Binary trees\n '
return BinaryTree(v)
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: Sylvester.vertices(3)\n Binary trees of size 3\n '
return BinaryTrees(n)
def rank(self, v):
'\n Return the rank of ``v``: the number of nodes of the tree.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: Sylvester.rank(Sylvester.vertices(3)[0])\n 3\n '
return v.node_number()
def is_Q_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `Q`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``v`` is a sub-tree of ``w`` with one\n node less.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: v = Sylvester.vertices(2)[1]; ascii_art(v)\n o\n /\n o\n sage: ascii_art([w for w in Sylvester.vertices(3) if Sylvester.is_Q_edge(v, w)])\n [ o , o, o ]\n [ / \\ / / ]\n [ o o o o ]\n [ \\ / ]\n [ o o ]\n sage: [w for w in Sylvester.vertices(4) if Sylvester.is_Q_edge(v, w)]\n []\n '
def is_subtree(T1, T2):
if T2.is_empty():
return False
elif (T2[0].is_empty() and T2[1].is_empty()):
return T1.is_empty()
elif T1.is_empty():
return False
else:
return (((T1[0] == T2[0]) and is_subtree(T1[1], T2[1])) or ((T1[1] == T2[1]) and is_subtree(T1[0], T2[0])))
return is_subtree(v, w)
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``v`` is obtained from ``w`` by deleting\n its right-most node.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: v = Sylvester.vertices(2)[1]; ascii_art(v)\n o\n /\n o\n\n sage: ascii_art([w for w in Sylvester.vertices(3) if Sylvester.is_P_edge(v, w)])\n [ o , o ]\n [ / \\ / ]\n [ o o o ]\n [ / ]\n [ o ]\n\n sage: [w for w in Sylvester.vertices(4) if Sylvester.is_P_edge(v, w)]\n []\n '
if w.is_empty():
return False
else:
return (v == RuleSylvester._delete_right_most_node(w))
def P_symbol(self, P_chain):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a labelled binary tree.\n\n For permutations, this coincides with the binary search tree.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: pi = Permutation([2,4,3,1])\n sage: ascii_art(Sylvester(pi).P_symbol())\n _2_\n / \\\n 1 4\n /\n 3\n sage: Sylvester(pi).P_symbol() == pi.binary_search_tree()\n True\n\n We can also do the skew version::\n\n sage: B = BinaryTree; E = B(); N = B([])\n sage: ascii_art(Sylvester([3,2], shape=[3,3,3], labels=[N,N,N,E,E,E,N]).P_symbol())\n __1___\n / \\\n None 3\n /\n 2\n '
def add_label(L, S, T, m):
if (T[0] == S):
L = LabelledBinaryTree([L, None], m)
else:
assert (T[0] == S[0])
l = L.label()
L = LabelledBinaryTree([L[0], add_label(L[1], S[1], T[1], m)], l)
return L
L = LabelledBinaryTree(P_chain[0])
for i in range(1, len(P_chain)):
(S, T) = (P_chain[(i - 1)], P_chain[i])
L = add_label(L, S, T, i)
return L
def Q_symbol(self, Q_chain):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a labelled binary tree.\n\n For permutations, this coincides with the increasing tree.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: pi = Permutation([2,4,3,1])\n sage: ascii_art(Sylvester(pi).Q_symbol())\n _1_\n / \\\n 4 2\n /\n 3\n sage: Sylvester(pi).Q_symbol() == pi.inverse().increasing_tree()\n True\n\n We can also do the skew version::\n\n sage: B = BinaryTree; E = B(); N = B([])\n sage: ascii_art(Sylvester([3,2], shape=[3,3,3], labels=[N,N,N,E,E,E,N]).Q_symbol())\n _None_\n / \\\n 3 1\n /\n 2\n '
def add_label(L, S, T, m):
if L.is_empty():
assert (T.node_number() == 1)
return LabelledBinaryTree([], m)
l = L.label()
if (T[0] == S[0]):
return LabelledBinaryTree([L[0], add_label(L[1], S[1], T[1], m)], l)
else:
return LabelledBinaryTree([add_label(L[0], S[0], T[0], m), L[1]], l)
L = LabelledBinaryTree(Q_chain[0])
for i in range(1, len(Q_chain)):
(S, T) = (Q_chain[(i - 1)], Q_chain[i])
L = add_label(L, S, T, i)
return L
@staticmethod
def _delete_right_most_node(b):
'\n Return the tree obtained by deleting the right most node from ``b``.\n\n TESTS::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: b = BinaryTree([]); b\n [., .]\n sage: Sylvester._delete_right_most_node(b)\n .\n sage: b = BinaryTree([[[], []], None]); ascii_art(b)\n o\n /\n o\n / \\\n o o\n sage: ascii_art(Sylvester._delete_right_most_node(b))\n o\n / \\\n o o\n '
if b.is_empty():
raise ValueError('cannot delete right most node from empty tree')
elif b[1].is_empty():
return b[0]
else:
return BinaryTree([b[0], RuleSylvester._delete_right_most_node(b[1])])
def forward_rule(self, y, t, x, content):
'\n Return the output shape given three shapes and the content.\n\n See [Nze2007]_, page 9.\n\n INPUT:\n\n - ``y, t, x`` -- three binary trees from a cell in a growth\n diagram, labelled as::\n\n t x\n y\n\n - ``content`` -- `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The fourth binary tree ``z``.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: B = BinaryTree; E = B(); N = B([]); L = B([[],None])\n sage: R = B([None,[]]); T = B([[],[]])\n\n sage: ascii_art(Sylvester.forward_rule(E, E, E, 1))\n o\n sage: ascii_art(Sylvester.forward_rule(N, N, N, 1))\n o\n \\\n o\n sage: ascii_art(Sylvester.forward_rule(L, L, L, 1))\n o\n / \\\n o o\n sage: ascii_art(Sylvester.forward_rule(R, R, R, 1))\n o\n \\\n o\n \\\n o\n\n If ``y != x``, obtain ``z`` from ``y`` adding a node such\n that deleting the right most gives ``x``::\n\n sage: ascii_art(Sylvester.forward_rule(R, N, L, 0))\n o\n / \\\n o o\n\n sage: ascii_art(Sylvester.forward_rule(L, N, R, 0))\n o\n /\n o\n \\\n o\n\n If ``y == x != t``, obtain ``z`` from ``x`` by adding a node\n as left child to the right most node::\n\n sage: ascii_art(Sylvester.forward_rule(N, E, N, 0))\n o\n /\n o\n sage: ascii_art(Sylvester.forward_rule(T, L, T, 0))\n _o_\n / \\\n o o\n /\n o\n sage: ascii_art(Sylvester.forward_rule(L, N, L, 0))\n o\n /\n o\n /\n o\n sage: ascii_art(Sylvester.forward_rule(R, N, R, 0))\n o\n \\\n o\n /\n o\n '
def successors(b):
'\n Return all trees obtained from ``b`` by adding a node.\n '
if b.is_empty():
(yield BinaryTree([]))
else:
for t in successors(b[0]):
(yield BinaryTree([t, b[1]]))
for t in successors(b[1]):
(yield BinaryTree([b[0], t]))
def union(y, x):
'\n Return the unique tree obtained by adding a node to ``y`` such\n that deleting the right most node gives ``x``.\n '
for t in successors(y):
if (RuleSylvester._delete_right_most_node(t) == x):
return t
raise ValueError(('could not find union of %s and %s' % (y, x)))
if (y == t == x):
if (content == 0):
z = y
elif (content == 1):
z = t.over(BinaryTree([]))
else:
raise NotImplementedError
elif (content != 0):
raise ValueError(('for y=%s, t=%s, x=%s, the content should be 0 but is %s' % (y, t, x, content)))
elif (y != t == x):
z = y
elif (y == t != x):
z = x
else:
z = union(y, x)
return z
def backward_rule(self, y, z, x):
'\n Return the output shape given three shapes and the content.\n\n See [Nze2007]_, page 9.\n\n INPUT:\n\n - ``y, z, x`` -- three binary trees from a cell in a growth\n diagram, labelled as::\n\n x\n y z\n\n OUTPUT:\n\n A pair ``(t, content)`` consisting of the shape of the fourth\n binary tree t and the content of the cell.\n\n EXAMPLES::\n\n sage: Sylvester = GrowthDiagram.rules.Sylvester()\n sage: B = BinaryTree; E = B(); N = B([]); L = B([[],None])\n sage: R = B([None,[]]); T = B([[],[]])\n\n sage: ascii_art(Sylvester.backward_rule(E, E, E))\n ( , 0 )\n sage: ascii_art(Sylvester.backward_rule(N, N, N))\n ( o, 0 )\n '
if (x == y == z):
return (x, 0)
elif (x == z != y):
return (y, 0)
elif (x != z == y):
return (x, 0)
elif ((x == y) and (z == x.over(BinaryTree([])))):
return (x, 1)
else:
t = RuleSylvester._delete_right_most_node(y)
return (t, 0)
|
class RuleYoungFibonacci(Rule):
'\n A rule modelling a Schensted-like correspondence for\n Young-Fibonacci-tableaux.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: GrowthDiagram(YF, [3,1,2])\n 0 1 0\n 0 0 1\n 1 0 0\n\n The vertices of the dual graded graph are Fibonacci words -\n compositions into parts of size at most two::\n\n sage: YF.vertices(4)\n [word: 22, word: 211, word: 121, word: 112, word: 1111]\n\n Note that, instead of passing the rule to :class:`GrowthDiagram`,\n we can also use call the rule to create growth diagrams. For\n example::\n\n sage: G = YF([2, 3, 7, 4, 1, 6, 5]); G\n 0 0 0 0 1 0 0\n 1 0 0 0 0 0 0\n 0 1 0 0 0 0 0\n 0 0 0 1 0 0 0\n 0 0 0 0 0 0 1\n 0 0 0 0 0 1 0\n 0 0 1 0 0 0 0\n\n The Kleitman Greene invariant is: take the last letter and the\n largest letter of the permutation and remove them. If they\n coincide write 1, otherwise write 2::\n\n sage: G.P_chain()[-1]\n word: 21211\n\n TESTS::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: YF.zero\n word:\n\n Check duality::\n\n sage: YF._check_duality(4)\n\n sage: G = YF(labels=[[1],[1,0],[1]])\n Traceback (most recent call last):\n ...\n ValueError: 0 not in alphabet\n\n sage: G = YF(labels=[[1,1],[1,2]])\n Traceback (most recent call last):\n ...\n ValueError: 11 has smaller rank than 12 but is not covered by it in Q\n\n sage: G = YF(labels=[[1,2],[1,1]])\n Traceback (most recent call last):\n ...\n ValueError: 11 has smaller rank than 12 but is not covered by it in P\n\n sage: all(YF(labels=YF(pi).out_labels()).to_word()\n ....: == pi for pi in Permutations(4))\n True\n sage: pi = Permutations(10).random_element()\n sage: G = YF(pi)\n sage: list(YF(labels=G.out_labels())) == list(G)\n True\n '
zero = Word([], alphabet=[1, 2])
def normalize_vertex(self, v):
'\n Return ``v`` as a word with letters 1 and 2.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: YF.normalize_vertex([1,2,1]).parent()\n Finite words over {1, 2}\n '
return Word(v, alphabet=[1, 2])
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: YF.vertices(3)\n [word: 21, word: 12, word: 111]\n '
if (n == 0):
return [self.zero]
else:
return [Word(list(w), [1, 2]) for w in Compositions(n, max_part=2)]
def rank(self, v):
'\n Return the rank of ``v``: the size of the corresponding composition.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: YF.rank(YF.vertices(3)[0])\n 3\n '
return sum(v)
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``v`` is obtained from ``w`` by deleting\n a ``1`` or replacing the left-most ``2`` by a ``1``.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: v = YF.vertices(5)[5]; v\n word: 1121\n sage: [w for w in YF.vertices(6) if YF.is_P_edge(v, w)]\n [word: 2121, word: 11121]\n sage: [w for w in YF.vertices(7) if YF.is_P_edge(v, w)]\n []\n '
if (sum(w) != (sum(v) + 1)):
return False
ell = len(v)
w = list(w)
for i in range((ell + 1)):
d = list(v)
d.insert(i, 1)
if (w == d):
return True
if ((i < ell) and (v[i] == 1)):
d = list(v)
d[i] = 2
if (w == d):
return True
break
return False
is_Q_edge = is_P_edge
def forward_rule(self, y, t, x, content):
'\n Return the output shape given three shapes and the content.\n\n See [Fom1995]_ Lemma 4.4.1, page 35.\n\n INPUT:\n\n - ``y, t, x`` -- three Fibonacci words from a\n cell in a growth diagram, labelled as::\n\n t x\n y\n\n - ``content`` -- `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The fourth Fibonacci word.\n\n EXAMPLES::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n\n sage: YF.forward_rule([], [], [], 1)\n word: 1\n\n sage: YF.forward_rule([1], [1], [1], 1)\n word: 11\n\n sage: YF.forward_rule([1,2], [1], [1,1], 0)\n word: 21\n\n sage: YF.forward_rule([1,1], [1], [1,1], 0)\n word: 21\n '
if (x == t == y):
if (content == 0):
r = x
elif (content == 1):
r = Word(([1] + list(y)), alphabet=[1, 2])
else:
raise NotImplementedError
elif (content != 0):
raise ValueError(('for y=%s, t=%s, x=%s, the content should be 0 but is %s' % (y, t, x, content)))
elif (x == t):
r = y
elif (y == t):
r = x
elif (x != t != y):
r = Word(([2] + list(t)), alphabet=[1, 2])
else:
raise NotImplementedError(('for y=%s, t=%s, x=%s, content %s we have no rule' % (y, t, x, content)))
return r
def backward_rule(self, y, z, x):
'\n Return the content and the input shape.\n\n See [Fom1995]_ Lemma 4.4.1, page 35.\n\n - ``y, z, x`` -- three Fibonacci words from a cell in a\n growth diagram, labelled as::\n\n x\n y z\n\n OUTPUT:\n\n A pair ``(t, content)`` consisting of the shape of the fourth\n word and the content of the cell.\n\n TESTS::\n\n sage: YF = GrowthDiagram.rules.YoungFibonacci()\n sage: w = [4,1,8,3,6,5,2,7,9]; G = YF(w)\n sage: GrowthDiagram(YF, labels=G.out_labels()).to_word() == w # indirect doctest\n True\n '
if (x == y == z):
return (x, 0)
elif (x == z != y):
return (y, 0)
elif (x != z == y):
return (x, 0)
elif (z[0] == 1):
return (z[1:], 1)
elif (z[0] == 2):
return (z[1:], 0)
|
class RulePartitions(Rule):
"\n A rule for growth diagrams on Young's lattice on integer\n partitions graded by size.\n\n TESTS::\n\n sage: Burge = GrowthDiagram.rules.Burge()\n sage: Burge.zero\n []\n sage: G = GrowthDiagram(Burge, labels=[[1],[1]])\n Traceback (most recent call last):\n ...\n ValueError: can only determine the shape of the growth diagram\n if ranks of successive labels differ\n "
zero = _make_partition([])
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: RSK = GrowthDiagram.rules.RSK()\n sage: RSK.vertices(3)\n Partitions of the integer 3\n '
return Partitions(n)
def normalize_vertex(self, v):
'\n Return ``v`` as a partition.\n\n EXAMPLES::\n\n sage: RSK = GrowthDiagram.rules.RSK()\n sage: RSK.normalize_vertex([3,1]).parent()\n Partitions\n '
return _make_partition(v)
def rank(self, v):
'\n Return the rank of ``v``: the size of the partition.\n\n EXAMPLES::\n\n sage: RSK = GrowthDiagram.rules.RSK()\n sage: RSK.rank(RSK.vertices(3)[0])\n 3\n '
return v.size()
def P_symbol(self, P_chain):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a (skew) tableau.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = RuleRSK([[0,1,0], [1,0,2]])\n sage: G.P_symbol().pp()\n 1 2 2\n 2\n '
return SkewTableau(chain=P_chain)
def Q_symbol(self, Q_chain):
'\n Return the labels along the horizontal boundary of a rectangular\n growth diagram as a skew tableau.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: G = RuleRSK([[0,1,0], [1,0,2]])\n sage: G.Q_symbol().pp()\n 1 3 3\n 2\n '
return SkewTableau(chain=Q_chain)
|
class RuleRSK(RulePartitions):
'\n A rule modelling Robinson-Schensted-Knuth insertion.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: GrowthDiagram(RuleRSK, [3,2,1,2,3])\n 0 0 1 0 0\n 0 1 0 1 0\n 1 0 0 0 1\n\n The vertices of the dual graded graph are integer partitions::\n\n sage: RuleRSK.vertices(3)\n Partitions of the integer 3\n\n The local rules implemented provide the RSK correspondence\n between matrices with non-negative integer entries and pairs of\n semistandard tableaux, the\n :meth:`~sage.combinat.growth.RulePartitions.P_symbol` and the\n :meth:`~sage.combinat.growth.RulePartitions.Q_symbol`. For\n permutations, it reduces to classical Schensted insertion.\n\n Instead of passing the rule to :class:`GrowthDiagram`, we can\n also call the rule to create growth diagrams. For example::\n\n sage: m = matrix([[0,0,0,0,1],[1,1,0,2,0], [0,3,0,0,0]])\n sage: G = RuleRSK(m); G\n 0 0 0 0 1\n 1 1 0 2 0\n 0 3 0 0 0\n\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 2 2 2 3 1 2 2 2 2 ]\n [ 2 3 4 4 ]\n [ 3 , 5 ]\n\n For rectangular fillings, the Kleitman-Greene invariant is the\n shape of the :meth:`P_symbol` (or the :meth:`Q_symbol`). Put\n differently, it is the partition labelling the lower right corner\n of the filling (recall that we are using matrix coordinates). It\n can be computed alternatively as the partition\n `(\\mu_1,\\dots,\\mu_n)`, where `\\mu_1 + \\dots + \\mu_i` is the\n maximal sum of entries in a collection of `i` pairwise disjoint\n sequences of cells with weakly increasing coordinates.\n\n For rectangular fillings, we could also use the (faster)\n implementation provided via :func:`~sage.combinat.rsk.RSK`.\n Because the of the coordinate conventions in\n :func:`~sage.combinat.rsk.RSK`, we have to transpose matrices::\n\n sage: [G.P_symbol(), G.Q_symbol()] == RSK(m.transpose())\n True\n\n sage: n = 5; l = [(pi, RuleRSK(pi)) for pi in Permutations(n)]\n sage: all([G.P_symbol(), G.Q_symbol()] == RSK(pi) for pi, G in l)\n True\n\n sage: n = 5; l = [(w, RuleRSK(w)) for w in Words([1,2,3], 5)]\n sage: all([G.P_symbol(), G.Q_symbol()] == RSK(pi) for pi, G in l)\n True\n '
def forward_rule(self, y, t, x, content):
'\n Return the output shape given three shapes and the content.\n\n See [Kra2006]_ `(F^1 0)-(F^1 2)`.\n\n INPUT:\n\n - ``y, t, x`` -- three partitions from a cell in a\n growth diagram, labelled as::\n\n t x\n y\n\n - ``content`` -- a non-negative integer; the content of the cell\n\n OUTPUT:\n\n The fourth partition according to the Robinson-Schensted-Knuth\n correspondence.\n\n EXAMPLES::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: RuleRSK.forward_rule([2,1],[2,1],[2,1],1)\n [3, 1]\n\n sage: RuleRSK.forward_rule([1],[],[2],2)\n [4, 1]\n '
carry = content
z = []
while True:
if (x == []):
row1 = 0
else:
row1 = x[0]
if (y == []):
row3 = 0
else:
row3 = y[0]
newPart = (max(row1, row3) + carry)
if (newPart == 0):
return z[::(- 1)]
else:
z = ([newPart] + z)
if (t == []):
carry = min(row1, row3)
else:
carry = (min(row1, row3) - t[0])
x = x[1:]
t = t[1:]
y = y[1:]
def backward_rule(self, y, z, x):
'\n Return the content and the input shape.\n\n See [Kra2006]_ `(B^1 0)-(B^1 2)`.\n\n INPUT:\n\n - ``y, z, x`` -- three partitions from a cell in a\n growth diagram, labelled as::\n\n x\n y z\n\n OUTPUT:\n\n A pair ``(t, content)`` consisting of the shape of the fourth\n word according to the Robinson-Schensted-Knuth correspondence\n and the content of the cell.\n\n TESTS::\n\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: w = [4,1,8,3,6,5,2,7,9]; G = RuleRSK(w)\n sage: GrowthDiagram(RuleRSK, labels=G._out_labels).to_word() == w # indirect doctest\n True\n '
carry = 0
i = len(z)
t = []
while (i > 0):
if (len(x) < i):
row1 = 0
else:
row1 = x[(i - 1)]
if (len(y) < i):
row3 = 0
else:
row3 = y[(i - 1)]
t = ([(min(row1, row3) - carry)] + t)
carry = (z[(i - 1)] - max(row1, row3))
i = (i - 1)
return (_make_partition(t), carry)
|
class RuleBurge(RulePartitions):
"\n A rule modelling Burge insertion.\n\n EXAMPLES::\n\n sage: Burge = GrowthDiagram.rules.Burge()\n sage: GrowthDiagram(Burge, labels=[[],[1,1,1],[2,1,1,1],[2,1,1],[2,1],[1,1],[]])\n 1 1\n 0 1\n 1 0\n 1 0\n\n The vertices of the dual graded graph are integer partitions::\n\n sage: Burge.vertices(3)\n Partitions of the integer 3\n\n The local rules implemented provide Burge's correspondence\n between matrices with non-negative integer entries and pairs of\n semistandard tableaux, the\n :meth:`~sage.combinat.growth.RulePartitions.P_symbol` and the\n :meth:`~sage.combinat.growth.RulePartitions.Q_symbol`. For\n permutations, it reduces to classical Schensted insertion.\n\n Instead of passing the rule to :class:`GrowthDiagram`, we can\n also call the rule to create growth diagrams. For example::\n\n sage: m = matrix([[2,0,0,1,0],[1,1,0,0,0], [0,0,0,0,3]])\n sage: G = Burge(m); G\n 2 0 0 1 0\n 1 1 0 0 0\n 0 0 0 0 3\n\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 2 3 1 2 5 ]\n [ 1 3 1 5 ]\n [ 1 3 1 5 ]\n [ 2 , 4 ]\n\n For rectangular fillings, the Kleitman-Greene invariant is the\n shape of the\n :meth:`~sage.combinat.growth.RulePartitions.P_symbol`. Put\n differently, it is the partition labelling the lower right corner\n of the filling (recall that we are using matrix coordinates). It\n can be computed alternatively as the transpose of the partition\n `(\\mu_1, \\ldots, \\mu_n)`, where `\\mu_1 + \\cdots + \\mu_i` is the\n maximal sum of entries in a collection of `i` pairwise disjoint\n sequences of cells with weakly decreasing row indices and weakly\n increasing column indices.\n "
def forward_rule(self, y, t, x, content):
'\n Return the output shape given three shapes and the content.\n\n See [Kra2006]_ `(F^4 0)-(F^4 2)`.\n\n INPUT:\n\n - ``y, t, x`` -- three from a cell in a growth diagram,\n labelled as::\n\n t x\n y\n\n - ``content`` -- a non-negative integer; the content of the cell\n\n OUTPUT:\n\n The fourth partition according to the Burge correspondence.\n\n EXAMPLES::\n\n sage: Burge = GrowthDiagram.rules.Burge()\n sage: Burge.forward_rule([2,1],[2,1],[2,1],1)\n [3, 1]\n\n sage: Burge.forward_rule([1],[],[2],2)\n [2, 1, 1, 1]\n '
n = ((content + len(x)) + len(y))
x += ([0] * (n - len(x)))
y += ([0] * (n - len(y)))
t += ([0] * (n - len(t)))
z = ([0] * n)
carry = content
for (i, (row1, row2, row3)) in enumerate(zip(x, t, y)):
s = min(int((row1 == row2 == row3)), carry)
new_part = (max(row1, row3) + s)
if new_part:
z[i] = new_part
carry += (((- s) + min(row1, row3)) - row2)
else:
break
return _make_partition(z)
def backward_rule(self, y, z, x):
'\n Return the content and the input shape.\n\n See [Kra2006]_ `(B^4 0)-(B^4 2)`. (In the arXiv version of\n the article there is a typo: in the computation of carry in\n `(B^4 2)` , `\\rho` must be replaced by `\\lambda`).\n\n INPUT:\n\n - ``y, z, x`` -- three partitions from a cell in a\n growth diagram, labelled as::\n\n x\n y z\n\n OUTPUT:\n\n A pair ``(t, content)`` consisting of the shape of the fourth\n partition according to the Burge correspondence and the content of\n the cell.\n\n EXAMPLES::\n\n sage: Burge = GrowthDiagram.rules.Burge()\n sage: Burge.backward_rule([1,1,1],[2,1,1,1],[2,1,1])\n ([1, 1], 0)\n\n TESTS::\n\n sage: w = [4,1,8,3,6,5,2,7,9]; G = Burge(w)\n sage: GrowthDiagram(Burge, labels=G._out_labels).to_word() == w # indirect doctest\n True\n '
t = ([0] * len(z))
mu = (([0] * (len(z) - len(x))) + x[::(- 1)])
nu = (([0] * (len(z) - len(y))) + y[::(- 1)])
la = z[::(- 1)]
carry = 0
for (i, (mu_i, la_i, nu_i)) in enumerate(zip(mu, la, nu)):
s = min(int((mu_i == nu_i == la_i)), carry)
t[i] = (min(mu_i, nu_i) - s)
carry += (((- s) + la_i) - max(mu_i, nu_i))
t.reverse()
return (_make_partition(t), carry)
|
class RuleDomino(Rule):
'\n A rule modelling domino insertion.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: GrowthDiagram(Domino, [[1,0,0],[0,0,1],[0,-1,0]])\n 1 0 0\n 0 0 1\n 0 -1 0\n\n The vertices of the dual graded graph are integer partitions\n whose Ferrers diagram can be tiled with dominoes::\n\n sage: Domino.vertices(2)\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n\n Instead of passing the rule to :class:`GrowthDiagram`, we can\n also call the rule to create growth diagrams. For example, let\n us check Figure 3 in [Lam2004]_::\n\n sage: G = Domino([[0,0,0,-1],[0,0,1,0],[-1,0,0,0],[0,1,0,0]]); G\n 0 0 0 -1\n 0 0 1 0\n -1 0 0 0\n 0 1 0 0\n\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 2 4 1 2 2 ]\n [ 1 2 4 1 3 3 ]\n [ 3 3 , 4 4 ]\n\n The spin of a domino tableau is half the number of vertical dominoes::\n\n sage: def spin(T):\n ....: return sum(2*len(set(row)) - len(row) for row in T)/4\n\n According to [Lam2004]_, the number of negative entries in the\n signed permutation equals the sum of the spins of the two\n associated tableaux::\n\n sage: pi = [3,-1,2,4,-5]\n sage: G = Domino(pi)\n sage: list(G.filling().values()).count(-1) == spin(G.P_symbol()) + spin(G.Q_symbol())\n True\n\n Negating all signs transposes all the partitions::\n\n sage: G.P_symbol() == Domino([-e for e in pi]).P_symbol().conjugate()\n True\n\n TESTS:\n\n Check duality::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Domino._check_duality(3)\n\n sage: G = Domino([[0,1,0],[0,0,-1],[1,0,0]]); G\n 0 1 0\n 0 0 -1\n 1 0 0\n\n sage: ascii_art([G.P_symbol(), G.Q_symbol()])\n [ 1 1 1 1 ]\n [ 2 3 2 2 ]\n [ 2 3, 3 3 ]\n\n sage: l = {pi: Domino(pi) for pi in SignedPermutations(4)}\n sage: S = Set([(G.P_symbol(), G.Q_symbol()) for G in l.values()])\n sage: S.cardinality()\n 384\n\n Check the color-to-spin property for all permutations of size 4::\n\n sage: all(list(G.filling().values()).count(-1) == spin(G.P_symbol()) + spin(G.Q_symbol())\n ....: for G in l.values())\n True\n\n Negating all signs transposes all the partitions::\n\n sage: W = SignedPermutations(4)\n sage: all(l[pi].P_symbol() == l[W([-e for e in pi])].P_symbol().conjugate()\n ....: for pi in l)\n True\n\n Check part of Theorem 4.2.3 in [Lee1996]_::\n\n sage: def to_permutation(pi):\n ....: pi1 = list(pi)\n ....: n = len(pi1)\n ....: pi2 = [-e for e in pi][::-1] + pi1\n ....: return Permutation([e+n+1 if e<0 else e+n for e in pi2])\n sage: RuleRSK = GrowthDiagram.rules.RSK()\n sage: def good(pi):\n ....: return Domino(pi).P_chain()[-1] == RuleRSK(to_permutation(pi)).P_chain()[-1]\n sage: all(good(pi) for pi in SignedPermutations(4))\n True\n\n sage: G = Domino(labels=[[1],[2,1]])\n Traceback (most recent call last):\n ...\n ValueError: [1] has smaller rank than [2, 1] but is not covered by it in Q\n\n sage: G = Domino(labels=[[2,1],[1]])\n Traceback (most recent call last):\n ...\n ValueError: [1] has smaller rank than [2, 1] but is not covered by it in P\n '
r = 2
zero = _make_partition([])
def normalize_vertex(self, v):
'\n Return ``v`` as a partition.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Domino.normalize_vertex([3,1]).parent()\n Partitions\n '
return _make_partition(v)
def vertices(self, n):
'\n Return the vertices of the dual graded graph on level ``n``.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Domino.vertices(2)\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n '
return [la for la in Partitions((2 * n)) if (len(la.core(2)) == 0)]
def rank(self, v):
'\n Return the rank of ``v``.\n\n The rank of a vertex is half the size of the partition,\n which equals the number of dominoes in any filling.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: Domino.rank(Domino.vertices(3)[0])\n 3\n '
return (v.size() // 2)
def is_P_edge(self, v, w):
'\n Return whether ``(v, w)`` is a `P`-edge of ``self``.\n\n ``(v, w)`` is an edge if ``v`` is obtained from ``w`` by deleting\n a domino.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: v = Domino.vertices(2)[1]; ascii_art(v)\n ***\n *\n sage: ascii_art([w for w in Domino.vertices(3) if Domino.is_P_edge(v, w)])\n [ *** ]\n [ * ]\n [ ***** *** * ]\n [ * , ***, * ]\n sage: [w for w in Domino.vertices(4) if Domino.is_P_edge(v, w)]\n []\n '
try:
((row_1, col_1), (row_2, col_2)) = SkewPartition([w, v]).cells()
except ValueError:
return False
return ((row_1 == row_2) or (col_1 == col_2))
is_Q_edge = is_P_edge
def P_symbol(self, P_chain):
'\n Return the labels along the vertical boundary of a rectangular\n growth diagram as a (skew) domino tableau.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n sage: G = Domino([[0,1,0],[0,0,-1],[1,0,0]])\n sage: G.P_symbol().pp()\n 1 1\n 2 3\n 2 3\n '
return SkewTableau(chain=P_chain)
Q_symbol = P_symbol
def forward_rule(self, y, t, x, content):
'\n Return the output shape given three shapes and the content.\n\n See [Lam2004]_ Section 3.1.\n\n INPUT:\n\n - ``y, t, x`` -- three partitions from a cell in a\n growth diagram, labelled as::\n\n t x\n y\n\n - ``content`` -- `-1`, `0` or `1`; the content of the cell\n\n OUTPUT:\n\n The fourth partition according to domino insertion.\n\n EXAMPLES::\n\n sage: Domino = GrowthDiagram.rules.Domino()\n\n Rule 1::\n\n sage: Domino.forward_rule([], [], [], 1)\n [2]\n\n sage: Domino.forward_rule([1,1], [1,1], [1,1], 1)\n [3, 1]\n\n Rule 2::\n\n sage: Domino.forward_rule([1,1], [1,1], [1,1], -1)\n [1, 1, 1, 1]\n\n Rule 3::\n\n sage: Domino.forward_rule([1,1], [1,1], [2,2], 0)\n [2, 2]\n\n Rule 4::\n\n sage: Domino.forward_rule([2,2,2], [2,2], [3,3], 0)\n [3, 3, 2]\n\n sage: Domino.forward_rule([2], [], [1,1], 0)\n [2, 2]\n\n sage: Domino.forward_rule([1,1], [], [2], 0)\n [2, 2]\n\n sage: Domino.forward_rule([2], [], [2], 0)\n [2, 2]\n\n sage: Domino.forward_rule([4], [2], [4], 0)\n [4, 2]\n\n sage: Domino.forward_rule([1,1,1,1], [1,1], [1,1,1,1], 0)\n [2, 2, 1, 1]\n\n sage: Domino.forward_rule([2,1,1], [2], [4], 0)\n [4, 1, 1]\n '
def union(la, mu):
'\n Return the union of the two partitions.\n '
return [max(p, q) for (p, q) in zip_longest(la, mu, fillvalue=0)]
if (content not in [0, 1, (- 1)]):
raise ValueError('domino: the content of the filling must be in {-1,0,1}')
if (content == 1):
if (not (x == t == y)):
raise ValueError('all shapes must be equal')
if (t == []):
z = [2]
else:
z = ([(t[0] + 2)] + t[1:])
elif (content == (- 1)):
if (not (x == t == y)):
raise ValueError('all shapes must be equal')
z = (t + [1, 1])
elif ((content == 0) and ((t == x) or (t == y))):
z = union(x, y)
else:
gamma3 = set(SkewPartition([y, t]).cells())
gamma1 = set(SkewPartition([x, t]).cells())
diff = gamma1.intersection(gamma3)
(cell1, cell2) = gamma3
if (len(diff) == 0):
z = union(x, y)
elif (len(diff) == 1):
z = copy(x)
(k, l) = diff.pop()
if (z[k] <= (l + 1)):
z[k] += 1
z[(k + 1)] += 1
elif (len(z) <= (k + 1)):
z += [2]
else:
z[(k + 1)] += 2
elif (cell1[0] == cell2[0]):
z = copy(x)
if (len(z) <= (cell1[0] + 1)):
z += [2]
else:
z[(cell1[0] + 1)] += 2
else:
z = copy(x)
for (r, p) in enumerate(z):
if (p <= (cell1[1] + 1)):
z[r] += 1
z[(r + 1)] += 1
break
else:
raise NotImplementedError(('domino: cannot call forward rule with shapes %s and content %s' % ((y, t, x), content)))
return z
|
class Rules():
'\n Catalog of rules for growth diagrams.\n '
ShiftedShapes = RuleShiftedShapes
LLMS = RuleLLMS
BinaryWord = RuleBinaryWord
Sylvester = RuleSylvester
YoungFibonacci = RuleYoungFibonacci
RSK = RuleRSK
Burge = RuleBurge
Domino = RuleDomino
|
def hall_polynomial(nu, mu, la, q=None):
'\n Return the (classical) Hall polynomial `P^{\\nu}_{\\mu,\\lambda}`\n (where `\\nu`, `\\mu` and `\\lambda` are the inputs ``nu``, ``mu``\n and ``la``).\n\n Let `\\nu,\\mu,\\lambda` be partitions. The Hall polynomial\n `P^{\\nu}_{\\mu,\\lambda}(q)` (in the indeterminate `q`) is defined\n as follows: Specialize `q` to a prime power, and consider the\n category of `\\GF{q}`-vector spaces with a distinguished\n nilpotent endomorphism. The morphisms in this category shall be\n the linear maps commuting with the distinguished endomorphisms.\n The *type* of an object in the category will be the Jordan type\n of the distinguished endomorphism; this is a partition. Now, if\n `N` is any fixed object of type `\\nu` in this category, then\n the polynomial `P^{\\nu}_{\\mu,\\lambda}(q)` specialized at the\n prime power `q` counts the number of subobjects `L` of `N` having\n type `\\lambda` such that the quotient object `N / L` has type\n `\\mu`. This determines the values of the polynomial\n `P^{\\nu}_{\\mu,\\lambda}` at infinitely many points (namely, at all\n prime powers), and hence `P^{\\nu}_{\\mu,\\lambda}` is uniquely\n determined. The degree of this polynomial is at most\n `n(\\nu) - n(\\lambda) - n(\\mu)`, where\n `n(\\kappa) = \\sum_i (i-1) \\kappa_i` for every partition `\\kappa`.\n (If this is negative, then the polynomial is zero.)\n\n These are the structure coefficients of the\n :class:`(classical) Hall algebra <HallAlgebra>`.\n\n If `\\lvert \\nu \\rvert \\neq \\lvert \\mu \\rvert + \\lvert \\lambda \\rvert`,\n then we have `P^{\\nu}_{\\mu,\\lambda} = 0`. More generally, if the\n Littlewood-Richardson coefficient `c^{\\nu}_{\\mu,\\lambda}`\n vanishes, then `P^{\\nu}_{\\mu,\\lambda} = 0`.\n\n The Hall polynomials satisfy the symmetry property\n `P^{\\nu}_{\\mu,\\lambda} = P^{\\nu}_{\\lambda,\\mu}`.\n\n ALGORITHM:\n\n If `\\lambda = (1^r)` and\n `\\lvert \\nu \\rvert = \\lvert \\mu \\rvert + \\lvert \\lambda \\rvert`,\n then we compute `P^{\\nu}_{\\mu,\\lambda}` as follows (cf. Example 2.4\n in [Sch2006]_):\n\n First, write `\\nu = (1^{l_1}, 2^{l_2}, \\ldots, n^{l_n})`, and\n define a sequence `r = r_0 \\geq r_1 \\geq \\cdots \\geq r_n` such that\n\n .. MATH::\n\n \\mu = \\left( 1^{l_1 - r_0 + 2r_1 - r_2}, 2^{l_2 - r_1 + 2r_2 - r_3},\n \\ldots , (n-1)^{l_{n-1} - r_{n-2} + 2r_{n-1} - r_n},\n n^{l_n - r_{n-1} + r_n} \\right).\n\n Thus if `\\mu = (1^{m_1}, \\ldots, n^{m_n})`, we have the following system\n of equations:\n\n .. MATH::\n\n \\begin{aligned}\n m_1 & = l_1 - r + 2r_1 - r_2,\n \\\\ m_2 & = l_2 - r_1 + 2r_2 - r_3,\n \\\\ & \\vdots ,\n \\\\ m_{n-1} & = l_{n-1} - r_{n-2} + 2r_{n-1} - r_n,\n \\\\ m_n & = l_n - r_{n-1} + r_n\n \\end{aligned}\n\n and solving for `r_i` and back substituting we obtain the equations:\n\n .. MATH::\n\n \\begin{aligned}\n r_n & = r_{n-1} + m_n - l_n,\n \\\\ r_{n-1} & = r_{n-2} + m_{n-1} - l_{n-1} + m_n - l_n,\n \\\\ & \\vdots ,\n \\\\ r_1 & = r + \\sum_{k=1}^n (m_k - l_k),\n \\end{aligned}\n\n or in general we have the recursive equation:\n\n .. MATH::\n\n r_i = r_{i-1} + \\sum_{k=i}^n (m_k - l_k).\n\n This, combined with the condition that `r_0 = r`, determines the\n `r_i` uniquely (recursively). Next we define\n\n .. MATH::\n\n t = (r_{n-2} - r_{n-1})(l_n - r_{n-1})\n + (r_{n-3} - r_{n-2})(l_{n-1} + l_n - r_{n-2}) + \\cdots\n + (r_0 - r_1)(l_2 + \\cdots + l_n - r_1),\n\n and with these notations we have\n\n .. MATH::\n\n P^{\\nu}_{\\mu,(1^r)} = q^t \\binom{l_n}{r_{n-1}}_q\n \\binom{l_{n-1}}{r_{n-2} - r_{n-1}}_q \\cdots \\binom{l_1}{r_0 - r_1}_q.\n\n To compute `P^{\\nu}_{\\mu,\\lambda}` in general, we compute the product\n `I_{\\mu} I_{\\lambda}` in the Hall algebra and return the coefficient of\n `I_{\\nu}`.\n\n EXAMPLES::\n\n sage: from sage.combinat.hall_polynomial import hall_polynomial\n sage: hall_polynomial([1,1],[1],[1])\n q + 1\n sage: hall_polynomial([2],[1],[1])\n 1\n sage: hall_polynomial([2,1],[2],[1])\n q\n sage: hall_polynomial([2,2,1],[2,1],[1,1])\n q^2 + q\n sage: hall_polynomial([2,2,2,1],[2,2,1],[1,1])\n q^4 + q^3 + q^2\n sage: hall_polynomial([3,2,2,1], [3,2], [2,1])\n q^6 + q^5\n sage: hall_polynomial([4,2,1,1], [3,1,1], [2,1])\n 2*q^3 + q^2 - q - 1\n sage: hall_polynomial([4,2], [2,1], [2,1], 0)\n 1\n\n TESTS::\n\n sage: hall_polynomial([3], [1], [1], 0)\n 0\n '
if (q is None):
q = ZZ['q'].gen()
R = q.parent()
nu = Partition(nu)
mu = Partition(mu)
la = Partition(la)
if (sum(nu) != (sum(mu) + sum(la))):
return R.zero()
if all(((x == 1) for x in la)):
r = [len(la)]
exp_nu = nu.to_exp()
exp_mu = mu.to_exp()
n = max(len(exp_nu), len(exp_mu))
for k in range(n):
r.append(((r[(- 1)] + sum(exp_mu[k:])) - sum(exp_nu[k:])))
exp_nu += ([0] * (n - len(exp_nu)))
t = sum((((r[(k - 2)] - r[(k - 1)]) * (sum(exp_nu[(k - 1):]) - r[(k - 1)])) for k in range(2, (n + 1))))
if (t < 0):
return R.zero()
return (((q ** t) * q_binomial(exp_nu[(n - 1)], r[(n - 1)], q)) * prod([q_binomial(exp_nu[(k - 1)], (r[(k - 1)] - r[k]), q) for k in range(1, n)], R.one()))
from sage.algebras.hall_algebra import HallAlgebra
H = HallAlgebra(R, q)
return (H[mu] * H[la]).coefficient(nu)
|
class WeakReversePlanePartition(Tableau):
'\n A weak reverse plane partition (short: rpp).\n\n A weak reverse plane partition is a tableau with nonnegative\n entries that are weakly increasing in each row and weakly\n increasing in each column.\n\n EXAMPLES::\n\n sage: x = WeakReversePlanePartition([[0, 1, 1], [0, 1, 3], [1, 2, 2], [1, 2, 3], [2]]); x\n [[0, 1, 1], [0, 1, 3], [1, 2, 2], [1, 2, 3], [2]]\n sage: x.pp()\n 0 1 1\n 0 1 3\n 1 2 2\n 1 2 3\n 2\n sage: x.shape()\n [3, 3, 3, 3, 1]\n '
@staticmethod
def __classcall_private__(cls, r):
'\n Return an rpp object.\n\n EXAMPLES::\n\n sage: WeakReversePlanePartition([[1, 2], [1, 3], [1]])\n [[1, 2], [1, 3], [1]]\n\n TESTS::\n\n sage: a1 = [[1, 2], [1, 3], [1]]\n sage: a2 = [(1, 2), (1, 3), (1,)]\n sage: A1 = WeakReversePlanePartition(a1)\n sage: A2 = WeakReversePlanePartition(a2)\n sage: A3 = WeakReversePlanePartition(A1)\n sage: A4 = Tableau(A1)\n sage: A1 == A2 == A3 == A4\n True\n '
try:
r = list(map(tuple, r))
except TypeError:
raise TypeError('r must be a list of positive integers')
return WeakReversePlanePartitions()(r)
def __init__(self, parent, t):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: R = WeakReversePlanePartition([[0, 1, 2], [0, 2]])\n sage: TestSuite(R).run()\n '
if (not isinstance(t, Tableau)):
t = [list(row) for row in t]
else:
t = list(t)
Tableau.__init__(self, parent, t)
@combinatorial_map(order=2, name='conjugate')
def conjugate(self):
'\n Return the conjugate of ``self``.\n\n EXAMPLES::\n\n sage: c = WeakReversePlanePartition([[1,1],[1,3],[2]]).conjugate(); c\n [[1, 1, 2], [1, 3]]\n sage: c.parent()\n Weak Reverse Plane Partitions\n '
C = super().conjugate()
return WeakReversePlanePartition(C)
def hillman_grassl_inverse(self):
'\n Return the image of the `\\lambda`-rpp ``self`` under the\n inverse of the Hillman-Grassl correspondence (as a\n :class:`~sage.combinat.tableau.Tableau`).\n\n Fix a partition `\\lambda`\n (see :meth:`~sage.combinat.partition.Partition`).\n We draw all partitions and tableaux in English notation.\n\n A `\\lambda`-*array* will mean a tableau of shape `\\lambda` whose\n entries are nonnegative integers. (No conditions on the order of\n these entries are made. Note that `0` is allowed.)\n\n A *weak reverse plane partition of shape* `\\lambda` (short:\n `\\lambda`-*rpp*) will mean a `\\lambda`-array whose entries weakly\n increase along each row and weakly increase along each column.\n\n The inverse `H^{-1}` of the Hillman-Grassl correspondence (see\n (:meth:`~sage.combinat.tableau.Tableau.hillman_grassl` for the\n latter) sends a `\\lambda`-rpp `\\pi` to a `\\lambda`-array\n `H^{-1}(\\pi)` constructed recursively as follows:\n\n * If all entries of `\\pi` are `0`, then `H^{-1}(\\pi) = \\pi`.\n\n * Otherwise, let `s` be the index of the leftmost column of `\\pi`\n containing a nonzero entry. Write the `\\lambda`-array `M`\n as `(m_{i, j})`.\n\n * Define a sequence `((i_1, j_1), (i_2, j_2), \\ldots,\n (i_n, j_n))` of boxes in the diagram of `\\lambda` (actually a\n lattice path made of northward and eastward steps) as follows:\n Let `(i_1, j_1)` be the bottommost box in the `s`-th column\n of `\\pi`.\n If `(i_k, j_k)` is defined for some `k \\geq 1`, then\n `(i_{k+1}, j_{k+1})` is constructed as follows:\n If `q_{i_k - 1, j_k}` is well-defined and equals `q_{i_k, j_k}`,\n then we set `(i_{k+1}, j_{k+1}) = (i_k - 1, j_k)`. Otherwise,\n we set `(i_{k+1}, j_{k+1}) = (i_k, j_k + 1)` if this is still\n a box of `\\lambda`. Otherwise, the sequence ends here.\n\n * Let `\\pi\'` be the `\\lambda`-rpp obtained from `\\pi` by\n subtracting `1` from the `(i_k, j_k)`-th entry of `\\pi` for each\n `k \\in \\{1, 2, \\ldots, n\\}`.\n\n * Let `N\'` be the image `H^{-1}(\\pi\')` (which is already\n constructed by recursion).\n Then, `H^{-1}(\\pi)` is obtained from `N\'` by adding `1` to the\n `(i_n, s)`-th entry of `N\'`.\n\n This construction appears in [HilGra1976]_ Section 6 (where\n `\\lambda`-arrays are re-encoded as sequences of "hook number\n multiplicities") and [EnumComb2]_ Section 7.22.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.hillman_grassl.hillman_grassl_inverse`\n for the inverse of the Hillman-Grassl correspondence as a\n standalone function.\n\n :meth:`~sage.combinat.tableau.Tableau.hillman_grassl`\n for the inverse map.\n\n EXAMPLES::\n\n sage: a = WeakReversePlanePartition([[2, 2, 4], [2, 3, 4], [3, 5]])\n sage: a.hillman_grassl_inverse()\n [[2, 1, 1], [0, 2, 0], [1, 1]]\n sage: b = WeakReversePlanePartition([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]])\n sage: B = b.hillman_grassl_inverse(); B\n [[1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1]]\n sage: b.parent(), B.parent()\n (Weak Reverse Plane Partitions, Tableaux)\n\n Applying the inverse of the Hillman-Grassl correspondence\n to the transpose of a `\\lambda`-rpp `M` yields the same\n result as applying it to `M` and then transposing the\n result ([Gans1981]_ Corollary 3.4)::\n\n sage: a = WeakReversePlanePartition([[1,3,5],[2,4]])\n sage: aic = a.hillman_grassl_inverse().conjugate()\n sage: aic == a.conjugate().hillman_grassl_inverse()\n True\n '
return Tableau(hillman_grassl_inverse(list(self)))
def pak_correspondence(self):
"\n Return the image of the `\\lambda`-rpp ``self`` under the Pak\n correspondence (as a :class:`~sage.combinat.tableau.Tableau`).\n\n See :mod:`~sage.combinat.hillman_grassl`.\n\n The Pak correspondence is the map `\\xi_\\lambda`\n from [Sulzgr2017]_ Section 7, and is the map\n `\\xi_\\lambda` from [Pak2002]_ Section 4.\n It is the inverse of the Sulzgruber correspondence\n (:meth:`sulzgruber_correspondence`).\n The following description of the Pak correspondence follows\n [Hopkins2017]_ (which denotes it by `\\mathcal{RSK}^{-1}`):\n\n Fix a partition `\\lambda`\n (see :meth:`~sage.combinat.partition.Partition`).\n We draw all partitions and tableaux in English notation.\n\n A `\\lambda`-*array* will mean a tableau of shape `\\lambda` whose\n entries are nonnegative integers. (No conditions on the order of\n these entries are made. Note that `0` is allowed.)\n\n A *weak reverse plane partition of shape* `\\lambda` (short:\n `\\lambda`-*rpp*) will mean a `\\lambda`-array whose entries weakly\n increase along each row and weakly increase along each column.\n\n We shall also use the following notation:\n If `(u, v)` is a cell of `\\lambda`, and if `\\pi` is a\n `\\lambda`-rpp, then:\n\n * the *lower bound* of `\\pi` at `(u, v)` (denoted by\n `\\pi_{<(u, v)}`) is defined to be\n `\\max \\{ \\pi_{u-1, v} , \\pi_{u, v-1} \\}`\n (where `\\pi_{0, v}` and `\\pi_{u, 0}` are understood to\n mean `0`).\n\n * the *upper bound* of `\\pi` at `(u, v)` (denoted by\n `\\pi_{>(u, v)}`) is defined to be\n `\\min \\{ \\pi_{u+1, v} , \\pi_{u, v+1} \\}`\n (where `\\pi_{i, j}` is understood to mean `+ \\infty`\n if `(i, j)` is not in `\\lambda`; thus, the upper\n bound at a corner cell is `+ \\infty`).\n\n * *toggling* `\\pi` at `(u, v)` means replacing the entry\n `\\pi_{u, v}` of `\\pi` at `(u, v)` by\n `\\pi_{<(u, v)} + \\pi_{>(u, v)} - \\pi_{u, v}`\n (this is well-defined as long as `(u, v)` is not a\n corner of `\\lambda`).\n\n Note that every `\\lambda`-rpp `\\pi` and every cell\n `(u, v)` of `\\lambda` satisfy\n `\\pi_{<(u, v)} \\leq \\pi_{u, v} \\leq \\pi_{>(u, v)}`.\n Note that toggling a `\\lambda`-rpp (at a cell that is not\n a corner) always results in a `\\lambda`-rpp. Also,\n toggling is an involution).\n\n Note also that the lower bound of `\\pi` at `(u, v)` is\n defined (and finite) even when `(u, v)` is not a cell of\n `\\lambda`, as long as both `(u-1, v)` and `(u, v-1)` are\n cells of `\\lambda`.\n\n The Pak correspondence `\\Phi_\\lambda` sends a `\\lambda`-array\n `M = (m_{i, j})` to a `\\lambda`-rpp `\\Phi_\\lambda(M)`. It\n is defined by recursion on `\\lambda` (that is, we assume that\n `\\Phi_\\mu` is already defined for every partition `\\mu`\n smaller than `\\lambda`), and its definition proceeds as\n follows:\n\n * If `\\lambda = \\varnothing`, then `\\Phi_\\lambda` is the\n obvious bijection sending the only `\\varnothing`-array\n to the only `\\varnothing`-rpp.\n\n * Pick any corner `c = (i, j)` of `\\lambda`, and let `\\mu`\n be the result of removing this corner `c` from the partition\n `\\lambda`. (The exact choice of `c` is immaterial.)\n\n * Let `M'` be what remains of `M` when the corner cell `c`\n is removed.\n\n * Let `\\pi' = \\Phi_\\mu(M')`.\n\n * For each positive integer `k` such that `(i-k, j-k)` is a\n cell of `\\lambda`, toggle `\\pi'` at `(i-k, j-k)`.\n (All these togglings commute, so the order in which they\n are made is immaterial.)\n\n * Extend the `\\mu`-rpp `\\pi'` to a `\\lambda`-rpp `\\pi` by\n adding the cell `c` and writing the number\n `m_{i, j} - \\pi'_{<(i, j)}` into this cell.\n\n * Set `\\Phi_\\lambda(M) = \\pi`.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.hillman_grassl.pak_correspondence`\n for the Pak correspondence as a standalone function.\n\n :meth:`~sage.combinat.tableau.Tableau.sulzgruber_correspondence`\n for the inverse map.\n\n EXAMPLES::\n\n sage: a = WeakReversePlanePartition([[1, 2, 3], [1, 2, 3], [2, 4, 4]])\n sage: A = a.pak_correspondence(); A\n [[1, 0, 2], [0, 2, 0], [1, 1, 0]]\n sage: a.parent(), A.parent()\n (Weak Reverse Plane Partitions, Tableaux)\n\n Applying the Pak correspondence to the transpose of a\n `\\lambda`-rpp `M` yields the same result as applying it to\n `M` and then transposing the result::\n\n sage: a = WeakReversePlanePartition([[1,3,5],[2,4]])\n sage: acc = a.pak_correspondence().conjugate()\n sage: acc == a.conjugate().pak_correspondence()\n True\n "
return Tableau(pak_correspondence(list(self)))
|
class WeakReversePlanePartitions(Tableaux):
'\n The set of all weak reverse plane partitions.\n '
@staticmethod
def __classcall_private__(cls, shape=None, **kwds):
'\n Normalize input to ensure a unique representation and\n return the correct class based on input.\n\n The ``shape`` parameter is currently not implemented.\n\n EXAMPLES::\n\n sage: S1 = WeakReversePlanePartitions()\n sage: S2 = WeakReversePlanePartitions()\n sage: S1 is S2\n True\n\n sage: S1 = WeakReversePlanePartitions([4, 2, 2, 1]) # not tested (not implemented)\n sage: S2 = WeakReversePlanePartitions((4, 2, 2, 1)) # not tested (not implemented)\n sage: S1 is S2 # not tested (not implemented)\n True\n '
if (shape is not None):
raise NotImplementedError('shape cannot be specified')
return super().__classcall__(cls, **kwds)
def __init__(self):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: S = WeakReversePlanePartitions()\n sage: TestSuite(S).run()\n '
Tableaux.__init__(self, category=Sets())
def _repr_(self):
'\n TESTS::\n\n sage: WeakReversePlanePartitions()\n Weak Reverse Plane Partitions\n '
return 'Weak Reverse Plane Partitions'
Element = WeakReversePlanePartition
def an_element(self):
'\n Returns a particular element of the class.\n\n TESTS::\n\n sage: T = WeakReversePlanePartitions()\n sage: T.an_element()\n [[0, 0, 1, 2], [0, 1, 1], [0], [2]]\n '
return self.element_class(self, [[0, 0, 1, 2], [0, 1, 1], [0], [2]])
|
def transpose(M):
'\n Return the transpose of a `\\lambda`-array.\n\n The transpose of a `\\lambda`-array `(m_{i, j})` is the\n `\\lambda^t`-array `(m_{j, i})`\n (where `\\lambda^t` is the conjugate of the partition\n `\\lambda`).\n\n EXAMPLES::\n\n sage: from sage.combinat.hillman_grassl import transpose\n sage: transpose([[1, 2, 3], [4, 5]])\n [[1, 4], [2, 5], [3]]\n sage: transpose([[5, 0, 3], [4, 1, 0], [7]])\n [[5, 4, 7], [0, 1], [3, 0]]\n\n TESTS::\n\n sage: transpose(((2, 1), (3,)))\n [[2, 3], [1]]\n sage: transpose([])\n []\n sage: transpose(WeakReversePlanePartition([[1, 2, 3], [4, 5]]))\n [[1, 4], [2, 5], [3]]\n sage: transpose(WeakReversePlanePartition([]))\n []\n '
if (not M):
return []
l = len(M[0])
res = []
for j in range(l):
lj = []
for r in M:
if (len(r) <= j):
break
lj.append(r[j])
res.append(lj)
return res
|
def hillman_grassl(M):
'\n Return the image of the `\\lambda`-array ``M``\n under the Hillman-Grassl correspondence.\n\n The Hillman-Grassl correspondence is a bijection\n between the tableaux with nonnegative entries\n (otherwise arbitrary) and the weak reverse plane\n partitions with nonnegative entries.\n This bijection preserves the shape of the\n tableau. See :mod:`~sage.combinat.hillman_grassl`.\n\n See :meth:`~sage.combinat.tableau.Tableau.hillman_grassl`\n for a description of this map.\n\n .. SEEALSO::\n\n :meth:`hillman_grassl_inverse`\n\n EXAMPLES::\n\n sage: from sage.combinat.hillman_grassl import hillman_grassl\n sage: hillman_grassl([[2, 1, 1], [0, 2, 0], [1, 1]])\n [[2, 2, 4], [2, 3, 4], [3, 5]]\n sage: hillman_grassl([[1, 2, 0], [1, 0, 1], [1]])\n [[0, 1, 3], [2, 4, 4], [3]]\n sage: hillman_grassl([])\n []\n sage: hillman_grassl([[3, 1, 2]])\n [[3, 4, 6]]\n sage: hillman_grassl([[2, 2, 0], [1, 1, 1], [1]])\n [[1, 2, 4], [3, 5, 5], [4]]\n sage: hillman_grassl([[1, 1, 1, 1]]*3)\n [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]\n\n TESTS::\n\n sage: hillman_grassl(((2, 2, 0), (1, 1, 1), (1,)))\n [[1, 2, 4], [3, 5, 5], [4]]\n '
lam = [len(row) for row in M]
l = len(lam)
Mt = transpose(M)
hook_mults = []
for (j, col_j) in enumerate(Mt):
col_j_hook_mults = []
for (r, entry) in enumerate(col_j):
if (entry != 0):
col_j_hook_mults += ([(r, j)] * entry)
hook_mults += reversed(col_j_hook_mults)
res = [([0] * rowlen) for rowlen in lam]
for (r, s) in reversed(hook_mults):
i = r
j = (lam[r] - 1)
while True:
old = res[i][j]
res[i][j] += 1
if (((i + 1) != l) and (j < lam[(i + 1)]) and (old == res[(i + 1)][j])):
i += 1
else:
if (j == s):
break
j -= 1
return res
|
def hillman_grassl_inverse(M):
'\n Return the image of the `\\lambda`-rpp ``M`` under the\n inverse of the Hillman-Grassl correspondence.\n\n See :mod:`~sage.combinat.hillman_grassl`.\n\n See\n :meth:`~sage.combinat.hillman_grassl.WeakReversePlanePartition.hillman_grassl_inverse`\n for a description of this map.\n\n .. SEEALSO::\n\n :meth:`hillman_grassl`\n\n EXAMPLES::\n\n sage: from sage.combinat.hillman_grassl import hillman_grassl_inverse\n sage: hillman_grassl_inverse([[2, 2, 4], [2, 3, 4], [3, 5]])\n [[2, 1, 1], [0, 2, 0], [1, 1]]\n sage: hillman_grassl_inverse([[0, 1, 3], [2, 4, 4], [3]])\n [[1, 2, 0], [1, 0, 1], [1]]\n\n Applying the inverse of the Hillman-Grassl correspondence\n to the transpose of a `\\lambda`-rpp `M` yields the same\n result as applying it to `M` and then transposing the\n result ([Gans1981]_ Corollary 3.4)::\n\n sage: hillman_grassl_inverse([[1,3,5],[2,4]])\n [[1, 2, 2], [1, 1]]\n sage: hillman_grassl_inverse([[1,2],[3,4],[5]])\n [[1, 1], [2, 1], [2]]\n sage: hillman_grassl_inverse([[1, 2, 3], [1, 2, 3], [2, 4, 4]])\n [[1, 2, 0], [0, 1, 1], [1, 0, 1]]\n sage: hillman_grassl_inverse([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n\n TESTS::\n\n sage: a = [[3], [4], [6]]\n sage: hillman_grassl_inverse(a)\n [[3], [1], [2]]\n sage: a\n [[3], [4], [6]]\n\n sage: hillman_grassl_inverse(((1,2),(3,4),(5,)))\n [[1, 1], [2, 1], [2]]\n '
lam = [len(row) for row in M]
res = [([0] * rowlen) for rowlen in lam]
Mt = transpose(M)
while True:
for (j, col_j) in enumerate(Mt):
if all(((entry == 0) for entry in col_j)):
continue
else:
break
else:
break
s = j
i = (len(col_j) - 1)
while True:
old = col_j[i]
col_j[i] -= 1
if ((i > 0) and (old == col_j[(i - 1)])):
i -= 1
else:
j += 1
if (j == lam[i]):
break
col_j = Mt[j]
res[i][s] += 1
return res
|
def sulzgruber_correspondence(M):
'\n Return the image of a `\\lambda`-array ``M``\n under the Sulzgruber correspondence.\n\n The Sulzgruber correspondence is the map `\\Phi_\\lambda`\n from [Sulzgr2017]_ Section 7, and is the map\n `\\xi_\\lambda^{-1}` from [Pak2002]_ Section 5.\n It is denoted by `\\mathcal{RSK}` in [Hopkins2017]_.\n It is the inverse of the Pak correspondence\n (:meth:`pak_correspondence`).\n\n See :meth:`~sage.combinat.tableau.Tableau.sulzgruber_correspondence`\n for a description of this map.\n\n EXAMPLES::\n\n sage: from sage.combinat.hillman_grassl import sulzgruber_correspondence\n sage: sulzgruber_correspondence([[1, 0, 2], [0, 2, 0], [1, 1, 0]])\n [[1, 2, 3], [1, 2, 3], [2, 4, 4]]\n sage: sulzgruber_correspondence([[1, 1, 2], [0, 1, 0], [3, 0, 0]])\n [[1, 1, 4], [2, 3, 4], [4, 4, 4]]\n sage: sulzgruber_correspondence([[1, 0, 2], [0, 2, 0], [1, 1]])\n [[0, 2, 3], [1, 3, 3], [2, 4]]\n sage: sulzgruber_correspondence([[0, 2, 2], [1, 1], [2]])\n [[1, 2, 4], [1, 3], [3]]\n sage: sulzgruber_correspondence([[1, 1, 1, 1]]*3)\n [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]\n\n The Sulzgruber correspondence can actually be\n extended (by the same definition) to arrays\n of nonnegative reals rather than nonnegative\n integers. This implementation supports this::\n\n sage: sulzgruber_correspondence([[1/2, 0, 1], [0, 1, 0], [1/2, 1/2]])\n [[0, 1, 3/2], [1/2, 3/2, 3/2], [1, 2]]\n\n TESTS::\n\n sage: sulzgruber_correspondence([])\n []\n sage: sulzgruber_correspondence(((0, 2, 2), (1, 1), (2,)))\n [[1, 2, 4], [1, 3], [3]]\n '
lam = [len(row) for row in M]
l = len(lam)
if (l == 0):
return []
lam_0 = lam[0]
for (i, lam_i) in enumerate(lam):
if (lam_i != lam_0):
i -= 1
break
j = (lam_0 - 1)
x = M[i][j]
N = [list(row) for row in M]
N[i].pop()
if (not N[i]):
N.pop()
N = sulzgruber_correspondence(N)
for k in range((min(i, j) + 1)):
u = (i - k)
v = (j - k)
if ((u > 0) and (v > 0)):
lower_bound = max(N[(u - 1)][v], N[u][(v - 1)])
elif (u > 0):
lower_bound = N[(u - 1)][v]
elif (v > 0):
lower_bound = N[u][(v - 1)]
else:
lower_bound = 0
if (k > 0):
val = N[u][v]
upper_bound = min(N[(u + 1)][v], N[u][(v + 1)])
N[u][v] = ((lower_bound + upper_bound) - val)
else:
if (len(N) <= u):
N.append([])
N[u].append((lower_bound + x))
return N
|
def pak_correspondence(M, copy=True):
'\n Return the image of a `\\lambda`-rpp ``M``\n under the Pak correspondence.\n\n The Pak correspondence is the map `\\xi_\\lambda`\n from [Sulzgr2017]_ Section 7, and is the map\n `\\xi_\\lambda` from [Pak2002]_ Section 4.\n It is the inverse of the Sulzgruber correspondence\n (:meth:`sulzgruber_correspondence`).\n\n See\n :meth:`~sage.combinat.hillman_grassl.WeakReversePlanePartition.pak_correspondence`\n for a description of this map.\n\n INPUT:\n\n - ``copy`` (default: ``True``) -- boolean;\n if set to ``False``, the algorithm will mutate the\n input (but be more efficient)\n\n EXAMPLES::\n\n sage: from sage.combinat.hillman_grassl import pak_correspondence\n sage: pak_correspondence([[1, 2, 3], [1, 2, 3], [2, 4, 4]])\n [[1, 0, 2], [0, 2, 0], [1, 1, 0]]\n sage: pak_correspondence([[1, 1, 4], [2, 3, 4], [4, 4, 4]])\n [[1, 1, 2], [0, 1, 0], [3, 0, 0]]\n sage: pak_correspondence([[0, 2, 3], [1, 3, 3], [2, 4]])\n [[1, 0, 2], [0, 2, 0], [1, 1]]\n sage: pak_correspondence([[1, 2, 4], [1, 3], [3]])\n [[0, 2, 2], [1, 1], [2]]\n sage: pak_correspondence([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n\n The Pak correspondence can actually be\n extended (by the same definition) to "rpps"\n of nonnegative reals rather than nonnegative\n integers. This implementation supports this::\n\n sage: pak_correspondence([[0, 1, 3/2], [1/2, 3/2, 3/2], [1, 2]])\n [[1/2, 0, 1], [0, 1, 0], [1/2, 1/2]]\n\n TESTS::\n\n sage: pak_correspondence([])\n []\n sage: pak_correspondence(((1, 2, 4), (1, 3), (3,)))\n [[0, 2, 2], [1, 1], [2]]\n\n sage: a = [[0, 2, 3], [1, 3, 3], [2, 4]]\n sage: pak_correspondence(a)\n [[1, 0, 2], [0, 2, 0], [1, 1]]\n sage: a\n [[0, 2, 3], [1, 3, 3], [2, 4]]\n sage: pak_correspondence(a, copy=False)\n [[1, 0, 2], [0, 2, 0], [1, 1]]\n sage: a\n []\n '
if (not M):
return []
lam = [len(row) for row in M]
lam_0 = lam[0]
for (i, lam_i) in enumerate(lam):
if (lam_i != lam_0):
i -= 1
break
j = (lam_0 - 1)
x = M[i][j]
if copy:
N = [list(row) for row in M]
else:
N = M
for k in range((min(i, j) + 1)):
u = (i - k)
v = (j - k)
if ((u > 0) and (v > 0)):
lower_bound = max(N[(u - 1)][v], N[u][(v - 1)])
elif (u > 0):
lower_bound = N[(u - 1)][v]
elif (v > 0):
lower_bound = N[u][(v - 1)]
else:
lower_bound = 0
if (k > 0):
val = N[u][v]
upper_bound = min(N[(u + 1)][v], N[u][(v + 1)])
N[u][v] = ((lower_bound + upper_bound) - val)
else:
x -= lower_bound
N[i].pop()
if (not N[i]):
N.pop()
N = pak_correspondence(N, copy=False)
if (len(N) <= i):
N.append([])
N[i].append(x)
return N
|
class IntegerList(ClonableArray):
'\n Element class for :class:`IntegerLists`.\n '
def check(self):
'\n Check to make sure this is a valid element in its\n :class:`IntegerLists` parent.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(4)\n sage: C([4]).check()\n True\n sage: C([5]).check()\n False\n '
return (self in self.parent())
|
class IntegerLists(Parent):
'\n Enumerated set of lists of integers with constraints.\n\n Currently, this is simply an abstract base class which should not\n be used by itself. See :class:`IntegerListsLex` for a class which\n can be used by end users.\n\n ``IntegerLists`` is just a Python front-end, acting as a\n :class:`Parent`, supporting element classes and so on.\n The attribute ``.backend`` which is an instance of\n :class:`sage.combinat.integer_lists.base.IntegerListsBackend` is the\n Cython back-end which implements all operations such as iteration.\n\n The front-end (i.e. this class) and the back-end are supposed to be\n orthogonal: there is no imposed correspondence between front-ends\n and back-ends.\n\n For example, the set of partitions of 5 and the set of weakly\n decreasing sequences which sum to 5 might be implemented by the\n same back-end, but they will be presented to the user by a\n different front-end.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_lists import IntegerLists\n sage: L = IntegerLists(5)\n sage: L\n Integer lists of sum 5 satisfying certain constraints\n\n sage: IntegerListsLex(2, length=3, name="A given name")\n A given name\n '
backend = None
backend_class = IntegerListsBackend
Element = IntegerList
def __init__(self, *args, **kwds):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: from sage.combinat.integer_lists import IntegerLists\n sage: C = IntegerLists(2, length=3)\n sage: C == loads(dumps(C))\n True\n '
if ('name' in kwds):
self.rename(kwds.pop('name'))
if ('element_class' in kwds):
self.Element = kwds.pop('element_class')
if ('element_constructor' in kwds):
element_constructor = kwds.pop('element_constructor')
elif issubclass(self.Element, ClonableArray):
element_constructor = self._element_constructor_nocheck
else:
element_constructor = self._element_constructor_default
self._element_constructor_ = element_constructor
category = kwds.pop('category', None)
if (category is None):
category = EnumeratedSets().Finite()
self.backend = self.backend_class(*args, **kwds)
Parent.__init__(self, category=category)
def __eq__(self, other):
'\n Return whether ``self == other``.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: D = IntegerListsLex(2, length=3); L = D.list()\n sage: E = IntegerListsLex(2, min_length=3)\n sage: F = IntegerListsLex(2, length=3, element_constructor=list)\n sage: G = IntegerListsLex(4, length=3)\n sage: C == C\n True\n sage: C == D\n True\n sage: C == E\n False\n sage: C == F\n False\n sage: C == None\n False\n sage: C == G\n False\n\n This is a minimal implementation enabling pickling tests. It\n is safe, but one would want the two following objects to be\n detected as equal::\n\n sage: C = IntegerListsLex(2, ceiling=[1,1,1])\n sage: D = IntegerListsLex(2, ceiling=[1,1,1])\n sage: C == D\n False\n\n TESTS:\n\n This used to fail due to poor equality testing. See\n :trac:`17979`, comment 433::\n\n sage: DisjointUnionEnumeratedSets(Family([2,2],\n ....: lambda n: IntegerListsLex(n, length=2))).list()\n [[2, 0], [1, 1], [0, 2], [2, 0], [1, 1], [0, 2]]\n sage: DisjointUnionEnumeratedSets(Family([2,2],\n ....: lambda n: IntegerListsLex(n, length=1))).list()\n [[2], [2]]\n '
if (self.__class__ != other.__class__):
return False
if (self.backend != other.backend):
return False
a = self._element_constructor_
b = other._element_constructor_
if ismethod(a):
a = a.__func__
if ismethod(b):
b = b.__func__
return (a == b)
def __ne__(self, other):
'\n Return whether ``self != other``.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: D = IntegerListsLex(2, length=3); L = D.list()\n sage: E = IntegerListsLex(2, max_length=3)\n sage: C != D\n False\n sage: C != E\n True\n '
return (not (self == other))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: D = IntegerListsLex(2, max_length=3)\n sage: hash(C) == hash(C)\n True\n '
a = self._element_constructor_
if ismethod(a):
a = a.__func__
return hash((self.__class__, a))
def __iter__(self):
'\n Return an iterator for the elements of ``self``.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: list(C) # indirect doctest\n [[2, 0, 0], [1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1], [0, 0, 2]]\n '
return self._element_iter(self.backend._iter(), self._element_constructor_)
@staticmethod
def _element_iter(itr, constructor):
'\n Given an iterator ``itr`` and an element constructor\n ``constructor``, iterate over ``constructor(v)`` where `v`\n are the values of ``itr``.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: list(C._element_iter(C._iter(), tuple))\n [(2, 0, 0), (1, 1, 0), (1, 0, 1), (0, 2, 0), (0, 1, 1), (0, 0, 2)]\n '
for v in itr:
(yield constructor(v))
def __getattr__(self, name):
"\n Get an attribute of the implementation backend.\n\n Ideally, this would be done using multiple inheritance, but\n Python doesn't support that for built-in types.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(2, length=3)\n sage: C.min_length\n 3\n\n TESTS:\n\n Check that uninitialized instances do not lead to infinite\n recursion because there is no ``backend`` attribute::\n\n sage: from sage.combinat.integer_lists import IntegerLists\n sage: L = IntegerLists.__new__(IntegerLists)\n sage: L.foo\n Traceback (most recent call last):\n ...\n AttributeError: 'NoneType' object has no attribute 'foo'...\n "
return getattr(self.backend, name)
def __contains__(self, item):
'\n Return ``True`` if ``item`` meets the constraints imposed by\n the arguments.\n\n EXAMPLES::\n\n sage: C = IntegerListsLex(n=2, max_length=3, min_slope=0)\n sage: all(l in C for l in C)\n True\n '
return self.backend._contains(item)
def _element_constructor_default(self, l):
'\n Default element constructor\n\n EXAMPLES::\n\n sage: L = IntegerListsLex(4)\n sage: L._element_constructor_default([1,2,3])\n [1, 2, 3]\n\n We construct a variant of :class:`IntegerLists` with a custom\n element class::\n\n sage: class MyElt(list):\n ....: def __init__(self, parent, x):\n ....: list.__init__(self, x)\n sage: from sage.combinat.integer_lists import IntegerLists\n sage: class MyIntegersLists(IntegerLists):\n ....: Element = MyElt\n sage: L = MyIntegersLists(5)\n sage: L._element_constructor_\n <bound method IntegerLists._element_constructor_default of Integer lists of sum 5 satisfying certain constraints>\n '
return self.element_class(self, l)
def _element_constructor_nocheck(self, l):
'\n A variant of the standard element constructor that passes\n ``check=False`` to the element class.\n\n EXAMPLES::\n\n sage: L = IntegerListsLex(4, max_slope=0)\n sage: L._element_constructor_nocheck([1,2,3])\n [1, 2, 3]\n\n When relevant, this is assigned to\n ``self._element_constructor_`` by :meth:`__init__`, to avoid\n overhead when constructing elements from trusted data in the\n iterator::\n\n sage: L._element_constructor_\n <bound method IntegerLists._element_constructor_nocheck of ...>\n sage: L._element_constructor_([1,2,3])\n [1, 2, 3]\n '
return self.element_class(self, l, check=False)
|
def IntegerListsNN(**kwds):
'\n Lists of nonnegative integers with constraints.\n\n This function returns the union of ``IntegerListsLex(n, **kwds)``\n where `n` ranges over all nonnegative integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_lists.nn import IntegerListsNN\n sage: L = IntegerListsNN(max_length=3, max_slope=-1)\n sage: L\n Disjoint union of Lazy family (<lambda>(i))_{i in Non negative integer semiring}\n sage: it = iter(L)\n sage: for _ in range(20):\n ....: print(next(it))\n []\n [1]\n [2]\n [3]\n [2, 1]\n [4]\n [3, 1]\n [5]\n [4, 1]\n [3, 2]\n [6]\n [5, 1]\n [4, 2]\n [3, 2, 1]\n [7]\n [6, 1]\n [5, 2]\n [4, 3]\n [4, 2, 1]\n [8]\n '
return DisjointUnionEnumeratedSets(Family(NN, (lambda i: IntegerListsLex(i, **kwds))))
|
class IntegerMatrices(UniqueRepresentation, Parent):
'\n The class of non-negative integer matrices with\n prescribed row sums and column sums.\n\n An *integer matrix* `m` with column sums `c := (c_1,...,c_k)` and row\n sums `l := (l_1,...,l_n)` where `c_1+...+c_k` is equal to `l_1+...+l_n`,\n is a `n \\times k` matrix `m = (m_{i,j})` such that\n `m_{1,j}+\\dots+m_{n,j} = c_j`, for all `j` and\n `m_{i,1}+\\dots+m_{i,k} = l_i`, for all `i`.\n\n EXAMPLES:\n\n There are `6` integer matrices with row sums `[3,2,2]` and column sums\n `[2,5]`::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([3,2,2], [2,5]); IM\n Non-negative integer matrices with row sums [3, 2, 2] and column sums [2, 5]\n sage: IM.list()\n [\n [2 1] [1 2] [1 2] [0 3] [0 3] [0 3]\n [0 2] [1 1] [0 2] [2 0] [1 1] [0 2]\n [0 2], [0 2], [1 1], [0 2], [1 1], [2 0]\n ]\n sage: IM.cardinality()\n 6\n\n '
@staticmethod
def __classcall__(cls, row_sums, column_sums):
'\n Normalize the inputs so that they are hashable.\n\n INPUT:\n\n - ``row_sums`` -- list, tuple, or anything defining a Composition\n - ``column_sums`` -- list, tuple, or anything defining a Composition\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([4,4,5], [3,7,1,2]); IM\n Non-negative integer matrices with row sums [4, 4, 5] and column sums [3, 7, 1, 2]\n sage: IM = IntegerMatrices((4,4,5), (3,7,1,2)); IM\n Non-negative integer matrices with row sums [4, 4, 5] and column sums [3, 7, 1, 2]\n sage: IM = IntegerMatrices(Composition([4,4,5]), Composition([3,7,1,2])); IM\n Non-negative integer matrices with row sums [4, 4, 5] and column sums [3, 7, 1, 2]\n\n '
from sage.combinat.composition import Composition
row_sums = Composition(row_sums)
column_sums = Composition(column_sums)
return super().__classcall__(cls, row_sums, column_sums)
def __init__(self, row_sums, column_sums):
'\n Constructor of this class; for documentation, see\n :class:`IntegerMatrices`.\n\n INPUT:\n\n - ``row_sums`` -- Composition\n - ``column_sums`` -- Composition\n\n TESTS::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([3,2,2], [2,5]); IM\n Non-negative integer matrices with row sums [3, 2, 2] and column sums [2, 5]\n sage: TestSuite(IM).run()\n '
self._row_sums = row_sums
self._col_sums = column_sums
Parent.__init__(self, category=FiniteEnumeratedSets())
def _repr_(self):
"\n TESTS::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IntegerMatrices([3,2,2], [2,5])._repr_()\n 'Non-negative integer matrices with row sums [3, 2, 2] and column sums [2, 5]'\n "
return ('Non-negative integer matrices with row sums %s and column sums %s' % (self._row_sums, self._col_sums))
def __iter__(self):
'\n An iterator for the integer matrices with the prescribed row sums and\n columns sums.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IntegerMatrices([2,2], [1,2,1]).list()\n [\n [1 1 0] [1 0 1] [0 2 0] [0 1 1]\n [0 1 1], [0 2 0], [1 0 1], [1 1 0]\n ]\n sage: IntegerMatrices([0,0],[0,0,0]).list()\n [\n [0 0 0]\n [0 0 0]\n ]\n sage: IntegerMatrices([1,1],[1,1]).list()\n [\n [1 0] [0 1]\n [0 1], [1 0]\n ]\n\n '
for x in integer_matrices_generator(self._row_sums, self._col_sums):
(yield matrix(ZZ, x))
def __contains__(self, x):
'\n Tests if ``x`` is an element of ``self``.\n\n INPUT:\n\n - ``x`` -- matrix\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([4], [1,2,1])\n sage: matrix([[1, 2, 1]]) in IM\n True\n sage: matrix(QQ, [[1, 2, 1]]) in IM\n True\n sage: matrix([[2, 1, 1]]) in IM\n False\n\n TESTS::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([4], [1,2,1])\n sage: [1, 2, 1] in IM\n False\n sage: matrix([[-1, 3, 1]]) in IM\n False\n '
from sage.structure.element import is_Matrix
if (not is_Matrix(x)):
return False
row_sums = ([ZZ.zero()] * x.nrows())
col_sums = ([ZZ.zero()] * x.ncols())
for i in range(x.nrows()):
for j in range(x.ncols()):
x_ij = x[(i, j)]
if ((x_ij not in ZZ) or (x_ij < 0)):
return False
row_sums[i] += x_ij
col_sums[j] += x_ij
if (row_sums[i] != self._row_sums[i]):
return False
if (col_sums != self._col_sums):
return False
return True
def cardinality(self):
'\n The number of integer matrices with the prescribed row sums and columns\n sums.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IntegerMatrices([2,5], [3,2,2]).cardinality()\n 6\n sage: IntegerMatrices([1,1,1,1,1], [1,1,1,1,1]).cardinality()\n 120\n sage: IntegerMatrices([2,2,2,2], [2,2,2,2]).cardinality()\n 282\n sage: IntegerMatrices([4], [3]).cardinality()\n 0\n sage: len(IntegerMatrices([0,0], [0]).list())\n 1\n\n This method computes the cardinality using symmetric functions. Below\n are the same examples, but computed by generating the actual matrices::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: len(IntegerMatrices([2,5], [3,2,2]).list())\n 6\n sage: len(IntegerMatrices([1,1,1,1,1], [1,1,1,1,1]).list())\n 120\n sage: len(IntegerMatrices([2,2,2,2], [2,2,2,2]).list())\n 282\n sage: len(IntegerMatrices([4], [3]).list())\n 0\n sage: len(IntegerMatrices([0], [0]).list())\n 1\n\n '
from sage.combinat.sf.sf import SymmetricFunctions
from sage.combinat.partition import Partition
h = SymmetricFunctions(ZZ).homogeneous()
row_partition = Partition(sorted(self._row_sums, reverse=True))
col_partition = Partition(sorted(self._col_sums, reverse=True))
return h[row_partition].scalar(h[col_partition])
def row_sums(self):
'\n The row sums of the integer matrices in ``self``.\n\n OUTPUT:\n\n - Composition\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([3,2,2], [2,5])\n sage: IM.row_sums()\n [3, 2, 2]\n '
return self._row_sums
def column_sums(self):
'\n The column sums of the integer matrices in ``self``.\n\n OUTPUT:\n\n - Composition\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([3,2,2], [2,5])\n sage: IM.column_sums()\n [2, 5]\n '
return self._col_sums
def to_composition(self, x):
'\n The composition corresponding to the integer matrix.\n\n This is the composition obtained by reading the entries of the matrix\n from left to right along each row, and reading the rows from top to\n bottom, ignore zeros.\n\n INPUT:\n\n - ``x`` -- matrix\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: IM = IntegerMatrices([3,2,2], [2,5]); IM\n Non-negative integer matrices with row sums [3, 2, 2] and column sums [2, 5]\n sage: IM.list()\n [\n [2 1] [1 2] [1 2] [0 3] [0 3] [0 3]\n [0 2] [1 1] [0 2] [2 0] [1 1] [0 2]\n [0 2], [0 2], [1 1], [0 2], [1 1], [2 0]\n ]\n sage: for m in IM: print(IM.to_composition(m))\n [2, 1, 2, 2]\n [1, 2, 1, 1, 2]\n [1, 2, 2, 1, 1]\n [3, 2, 2]\n [3, 1, 1, 1, 1]\n [3, 2, 2]\n '
from sage.combinat.composition import Composition
return Composition([entry for row in x for entry in row if (entry != 0)])
|
def integer_matrices_generator(row_sums, column_sums):
'\n Recursively generate the integer matrices with the prescribed row sums and\n column sums.\n\n INPUT:\n\n - ``row_sums`` -- list or tuple\n - ``column_sums`` -- list or tuple\n\n OUTPUT:\n\n - an iterator producing a list of lists\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_matrices import integer_matrices_generator\n sage: iter = integer_matrices_generator([3,2,2], [2,5]); iter\n <generator object ...integer_matrices_generator at ...>\n sage: for m in iter: print(m)\n [[2, 1], [0, 2], [0, 2]]\n [[1, 2], [1, 1], [0, 2]]\n [[1, 2], [0, 2], [1, 1]]\n [[0, 3], [2, 0], [0, 2]]\n [[0, 3], [1, 1], [1, 1]]\n [[0, 3], [0, 2], [2, 0]]\n '
column_sums = list(column_sums)
if (sum(row_sums) != sum(column_sums)):
return
if (not row_sums):
(yield [])
elif (len(row_sums) == 1):
(yield [column_sums])
else:
I = IntegerListsLex(n=row_sums[0], length=len(column_sums), ceiling=column_sums)
for comp in I.backend._iter():
t = [(column_sums[i] - ci) for (i, ci) in enumerate(comp)]
for mat in integer_matrices_generator(row_sums[1:], t):
(yield ([list(comp)] + mat))
|
def is_gale_ryser(r, s):
"\n Tests whether the given sequences satisfy the condition\n of the Gale-Ryser theorem.\n\n Given a binary matrix `B` of dimension `n\\times m`, the\n vector of row sums is defined as the vector whose\n `i^{\\mbox{th}}` component is equal to the sum of the `i^{\\mbox{th}}`\n row in `A`. The vector of column sums is defined similarly.\n\n If, given a binary matrix, these two vectors are easy to compute,\n the Gale-Ryser theorem lets us decide whether, given two\n non-negative vectors `r,s`, there exists a binary matrix\n whose row/column sums vectors are `r` and `s`.\n\n This functions answers accordingly.\n\n INPUT:\n\n - ``r``, ``s`` -- lists of non-negative integers.\n\n ALGORITHM:\n\n Without loss of generality, we can assume that:\n\n - The two given sequences do not contain any `0` ( which would\n correspond to an empty column/row )\n\n - The two given sequences are ordered in decreasing order\n (reordering the sequence of row (resp. column) sums amounts to\n reordering the rows (resp. columns) themselves in the matrix,\n which does not alter the columns (resp. rows) sums.\n\n We can then assume that `r` and `s` are partitions\n (see the corresponding class :class:`Partition`)\n\n If `r^*` denote the conjugate of `r`, the Gale-Ryser theorem\n asserts that a binary Matrix satisfying the constraints exists\n if and only if `s \\preceq r^*`, where `\\preceq` denotes\n the domination order on partitions.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_vector import is_gale_ryser\n sage: is_gale_ryser([4,2,2], [3,3,1,1]) # needs sage.combinat\n True\n sage: is_gale_ryser([4,2,1,1], [3,3,1,1]) # needs sage.combinat\n True\n sage: is_gale_ryser([3,2,1,1], [3,3,1,1]) # needs sage.combinat\n False\n\n REMARK: In the literature, what we are calling a\n Gale-Ryser sequence sometimes goes by the (rather\n generic-sounding) term ''realizable sequence''.\n "
if ([x for x in r if (x < 0)] or [x for x in s if (x < 0)]):
return False
from sage.combinat.partition import Partition
r2 = Partition(sorted([x for x in r if (x > 0)], reverse=True))
s2 = Partition(sorted([x for x in s if (x > 0)], reverse=True))
if ((len(r2) == 0) and (len(s2) == 0)):
return True
rstar = Partition(r2).conjugate()
return ((len(rstar) <= len(s2)) and (sum(r2) == sum(s2)) and rstar.dominates(s))
|
def gale_ryser_theorem(p1, p2, algorithm='gale', *, solver=None, integrality_tolerance=0.001):
'\n Returns the binary matrix given by the Gale-Ryser theorem.\n\n The Gale Ryser theorem asserts that if `p_1,p_2` are two\n partitions of `n` of respective lengths `k_1,k_2`, then there is\n a binary `k_1\\times k_2` matrix `M` such that `p_1` is the vector\n of row sums and `p_2` is the vector of column sums of `M`, if\n and only if the conjugate of `p_2` dominates `p_1`.\n\n INPUT:\n\n - ``p1, p2``-- list of integers representing the vectors\n of row/column sums\n\n - ``algorithm`` -- two possible string values:\n\n - ``\'ryser\'`` implements the construction due to Ryser [Ryser63]_.\n - ``\'gale\'`` (default) implements the construction due to Gale [Gale57]_.\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear Programming\n (MILP) solver to be used. If set to ``None``, the default one is used. For\n more information on MILP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over an\n inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.\n\n OUTPUT:\n\n A binary matrix if it exists, ``None`` otherwise.\n\n Gale\'s Algorithm:\n\n (Gale [Gale57]_): A matrix satisfying the constraints of its\n sums can be defined as the solution of the following\n Linear Program, which Sage knows how to solve.\n\n .. MATH::\n\n \\forall i&\\sum_{j=1}^{k_2} b_{i,j}=p_{1,j}\\\\\n \\forall i&\\sum_{j=1}^{k_1} b_{j,i}=p_{2,j}\\\\\n &b_{i,j}\\mbox{ is a binary variable}\n\n Ryser\'s Algorithm:\n\n (Ryser [Ryser63]_): The construction of an `m \\times n` matrix\n `A=A_{r,s}`, due to Ryser, is described as follows. The\n construction works if and only if have `s\\preceq r^*`.\n\n * Construct the `m \\times n` matrix `B` from `r` by defining\n the `i`-th row of `B` to be the vector whose first `r_i`\n entries are `1`, and the remainder are 0\'s, `1 \\leq i \\leq m`.\n This maximal matrix `B` with row sum `r` and ones left\n justified has column sum `r^{*}`.\n\n * Shift the last `1` in certain rows of `B` to column `n` in\n order to achieve the sum `s_n`. Call this `B` again.\n\n * The `1`\'s in column `n` are to appear in those\n rows in which `A` has the largest row sums, giving\n preference to the bottom-most positions in case of ties.\n * Note: When this step automatically "fixes" other columns,\n one must skip ahead to the first column index\n with a wrong sum in the step below.\n\n * Proceed inductively to construct columns `n-1`, ..., `2`, `1`.\n Note: when performing the induction on step `k`, we consider\n the row sums of the first `k` columns.\n\n * Set `A = B`. Return `A`.\n\n EXAMPLES:\n\n Computing the matrix for `p_1=p_2=2+2+1`::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.combinat.integer_vector import gale_ryser_theorem\n sage: p1 = [2,2,1]\n sage: p2 = [2,2,1]\n sage: print(gale_ryser_theorem(p1, p2)) # not tested\n [1 1 0]\n [1 0 1]\n [0 1 0]\n sage: A = gale_ryser_theorem(p1, p2)\n sage: rs = [sum(x) for x in A.rows()]\n sage: cs = [sum(x) for x in A.columns()]\n sage: p1 == rs; p2 == cs\n True\n True\n\n Or for a non-square matrix with `p_1=3+3+2+1` and `p_2=3+2+2+1+1`,\n using Ryser\'s algorithm::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.combinat.integer_vector import gale_ryser_theorem\n sage: p1 = [3,3,1,1]\n sage: p2 = [3,3,1,1]\n sage: gale_ryser_theorem(p1, p2, algorithm="ryser")\n [1 1 1 0]\n [1 1 0 1]\n [1 0 0 0]\n [0 1 0 0]\n sage: p1 = [4,2,2]\n sage: p2 = [3,3,1,1]\n sage: gale_ryser_theorem(p1, p2, algorithm="ryser")\n [1 1 1 1]\n [1 1 0 0]\n [1 1 0 0]\n sage: p1 = [4,2,2,0]\n sage: p2 = [3,3,1,1,0,0]\n sage: gale_ryser_theorem(p1, p2, algorithm="ryser")\n [1 1 1 1 0 0]\n [1 1 0 0 0 0]\n [1 1 0 0 0 0]\n [0 0 0 0 0 0]\n sage: p1 = [3,3,2,1]\n sage: p2 = [3,2,2,1,1]\n sage: print(gale_ryser_theorem(p1, p2, algorithm="gale")) # not tested\n [1 1 1 0 0]\n [1 1 0 0 1]\n [1 0 1 0 0]\n [0 0 0 1 0]\n\n With `0` in the sequences, and with unordered inputs::\n\n sage: from sage.combinat.integer_vector import gale_ryser_theorem\n sage: gale_ryser_theorem([3,3,0,1,1,0], [3,1,3,1,0], algorithm="ryser") # needs sage.combinat sage.modules\n [1 1 1 0 0]\n [1 0 1 1 0]\n [0 0 0 0 0]\n [1 0 0 0 0]\n [0 0 1 0 0]\n [0 0 0 0 0]\n sage: p1 = [3,1,1,1,1]; p2 = [3,2,2,0]\n sage: gale_ryser_theorem(p1, p2, algorithm="ryser") # needs sage.combinat sage.modules\n [1 1 1 0]\n [1 0 0 0]\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n\n TESTS:\n\n This test created a random bipartite graph on `n+m` vertices. Its\n adjacency matrix is binary, and it is used to create some\n "random-looking" sequences which correspond to an existing matrix. The\n ``gale_ryser_theorem`` is then called on these sequences, and the output\n checked for correction.::\n\n sage: def test_algorithm(algorithm, low=10, high=50):\n ....: n,m = randint(low,high), randint(low,high)\n ....: g = graphs.RandomBipartite(n, m, .3)\n ....: s1 = sorted(g.degree([(0,i) for i in range(n)]), reverse = True)\n ....: s2 = sorted(g.degree([(1,i) for i in range(m)]), reverse = True)\n ....: m = gale_ryser_theorem(s1, s2, algorithm = algorithm)\n ....: ss1 = sorted(map(lambda x : sum(x) , m.rows()), reverse = True)\n ....: ss2 = sorted(map(lambda x : sum(x) , m.columns()), reverse = True)\n ....: if ((ss1 != s1) or (ss2 != s2)):\n ....: print("Algorithm %s failed with this input:" % algorithm)\n ....: print(s1, s2)\n\n sage: for algorithm in ["gale", "ryser"]: # long time # needs sage.combinat sage.modules\n ....: for i in range(50):\n ....: test_algorithm(algorithm, 3, 10)\n\n Null matrix::\n\n sage: gale_ryser_theorem([0,0,0],[0,0,0,0], algorithm="gale") # needs sage.combinat sage.modules\n [0 0 0 0]\n [0 0 0 0]\n [0 0 0 0]\n sage: gale_ryser_theorem([0,0,0],[0,0,0,0], algorithm="ryser") # needs sage.combinat sage.modules\n [0 0 0 0]\n [0 0 0 0]\n [0 0 0 0]\n\n REFERENCES:\n\n .. [Ryser63] \\H. J. Ryser, Combinatorial Mathematics,\n Carus Monographs, MAA, 1963.\n .. [Gale57] \\D. Gale, A theorem on flows in networks, Pacific J. Math.\n 7(1957)1073-1082.\n '
from sage.matrix.constructor import matrix
if (not is_gale_ryser(p1, p2)):
return False
if (algorithm == 'ryser'):
from sage.combinat.permutation import Permutation
tmp = sorted(enumerate(p1), reverse=True, key=(lambda x: x[1]))
r = [x[1] for x in tmp]
r_permutation = [(x - 1) for x in Permutation([(x[0] + 1) for x in tmp]).inverse()]
m = len(r)
tmp = sorted(enumerate(p2), reverse=True, key=(lambda x: x[1]))
s = [x[1] for x in tmp]
s_permutation = [(x - 1) for x in Permutation([(x[0] + 1) for x in tmp]).inverse()]
cols = []
for t in reversed(s):
c = ([0] * m)
i = 0
while t:
k = (i + 1)
while ((k < m) and (r[i] == r[k])):
k += 1
if (t >= (k - i)):
for j in range(i, k):
r[j] -= 1
c[j] = 1
t -= (k - i)
else:
for j in range((k - t), k):
r[j] -= 1
c[j] = 1
t = 0
i = k
cols.append(c)
A0 = matrix(list(reversed(cols))).transpose()
A0 = A0.matrix_from_rows_and_columns(r_permutation, s_permutation)
return A0
elif (algorithm == 'gale'):
from sage.numerical.mip import MixedIntegerLinearProgram
(k1, k2) = (len(p1), len(p2))
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
for (i, c) in enumerate(p1):
p.add_constraint((p.sum([b[(i, j)] for j in range(k2)]) == c))
for (i, c) in enumerate(p2):
p.add_constraint((p.sum([b[(j, i)] for j in range(k1)]) == c))
p.set_objective(None)
p.solve()
b = p.get_values(b, convert=ZZ, tolerance=integrality_tolerance)
M = [([0] * k2) for i in range(k1)]
for i in range(k1):
for j in range(k2):
M[i][j] = b[(i, j)]
return matrix(M)
else:
raise ValueError('the only two algorithms available are "gale" and "ryser"')
|
def _default_function(l, default, i):
'\n EXAMPLES::\n\n sage: from sage.combinat.integer_vector import _default_function\n sage: import functools\n sage: f = functools.partial(_default_function, [1,2,3], 99)\n sage: f(-1)\n 99\n sage: f(0)\n 1\n sage: f(1)\n 2\n sage: f(2)\n 3\n sage: f(3)\n 99\n '
try:
if (i < 0):
return default
return l[i]
except IndexError:
return default
|
def list2func(l, default=None):
"\n Given a list ``l``, return a function that takes in a value ``i`` and\n return ``l[i]``. If default is not ``None``, then the function will\n return the default value for out of range ``i``'s.\n\n EXAMPLES::\n\n sage: f = sage.combinat.integer_vector.list2func([1,2,3])\n sage: f(0)\n 1\n sage: f(1)\n 2\n sage: f(2)\n 3\n sage: f(3)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n\n ::\n\n sage: f = sage.combinat.integer_vector.list2func([1,2,3], 0)\n sage: f(2)\n 3\n sage: f(3)\n 0\n "
if (default is None):
return (lambda i: l[i])
else:
from functools import partial
return partial(_default_function, l, default)
|
class IntegerVector(ClonableArray):
'\n An integer vector.\n '
def check(self):
"\n Check to make sure this is a valid integer vector by making sure\n all entries are non-negative.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: elt = IV([1,2,1])\n sage: elt.check()\n\n Check :trac:`34510`::\n\n sage: IV3 = IntegerVectors(n=3)\n sage: IV3([2,2])\n Traceback (most recent call last):\n ...\n ValueError: [2, 2] doesn't satisfy correct constraints\n sage: IVk3 = IntegerVectors(k=3)\n sage: IVk3([2,2])\n Traceback (most recent call last):\n ...\n ValueError: [2, 2] doesn't satisfy correct constraints\n sage: IV33 = IntegerVectors(n=3, k=3)\n sage: IV33([2,2])\n Traceback (most recent call last):\n ...\n ValueError: [2, 2] doesn't satisfy correct constraints\n "
if any(((x < 0) for x in self)):
raise ValueError('all entries must be non-negative')
if (self not in self.parent()):
raise ValueError(f"{self} doesn't satisfy correct constraints")
def trim(self):
'\n Remove trailing zeros from the integer vector.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: IV([5,3,5,1,0,0]).trim()\n [5, 3, 5, 1]\n sage: IV([5,0,5,1,0]).trim()\n [5, 0, 5, 1]\n sage: IV([4,3,3]).trim()\n [4, 3, 3]\n sage: IV([0,0,0]).trim()\n []\n\n sage: IV = IntegerVectors(k=4)\n sage: v = IV([4,3,2,0]).trim(); v\n [4, 3, 2]\n sage: v.parent()\n Integer vectors\n '
P = IntegerVectors()
v = list(self)
if all(((i == 0) for i in v)):
return P.element_class(P, [], check=False)
while (not v[(- 1)]):
v = v[:(- 1)]
return P.element_class(P, v, check=False)
def specht_module(self, base_ring=None):
'\n Return the Specht module corresponding to ``self``.\n\n EXAMPLES::\n\n sage: SM = IntegerVectors()([2,0,1,0,2]).specht_module(QQ); SM # needs sage.combinat sage.modules\n Specht module of [(0, 0), (0, 1), (2, 0), (4, 0), (4, 1)] over Rational Field\n sage: s = SymmetricFunctions(QQ).s() # needs sage.combinat sage.modules\n sage: s(SM.frobenius_image()) # needs sage.combinat sage.modules\n s[2, 2, 1]\n '
from sage.combinat.specht_module import SpechtModule
from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra
if (base_ring is None):
from sage.rings.rational_field import QQ
base_ring = QQ
R = SymmetricGroupAlgebra(base_ring, sum(self))
return SpechtModule(R, self)
def specht_module_dimension(self, base_ring=None):
'\n Return the dimension of the Specht module corresponding to ``self``.\n\n INPUT:\n\n - ``BR`` -- (default: `\\QQ`) the base ring\n\n EXAMPLES::\n\n sage: IntegerVectors()([2,0,1,0,2]).specht_module_dimension() # needs sage.combinat sage.modules\n 5\n sage: IntegerVectors()([2,0,1,0,2]).specht_module_dimension(GF(2)) # needs sage.combinat sage.modules sage.rings.finite_rings\n 5\n '
from sage.combinat.specht_module import specht_module_rank
return specht_module_rank(self, base_ring)
|
class IntegerVectors(Parent, metaclass=ClasscallMetaclass):
'\n The class of (non-negative) integer vectors.\n\n INPUT:\n\n - ``n`` -- if set to an integer, returns the combinatorial class\n of integer vectors whose sum is ``n``; if set to ``None``\n (default), no such constraint is defined\n\n - ``k`` -- the length of the vectors; set to ``None`` (default) if\n you do not want such a constraint\n\n .. NOTE::\n\n The entries are non-negative integers.\n\n EXAMPLES:\n\n If ``n`` is not specified, it returns the class of all integer vectors::\n\n sage: IntegerVectors()\n Integer vectors\n sage: [] in IntegerVectors()\n True\n sage: [1,2,1] in IntegerVectors()\n True\n sage: [1, 0, 0] in IntegerVectors()\n True\n\n Entries are non-negative::\n\n sage: [-1, 2] in IntegerVectors()\n False\n\n If ``n`` is specified, then it returns the class of all integer vectors\n which sum to ``n``::\n\n sage: IV3 = IntegerVectors(3); IV3\n Integer vectors that sum to 3\n\n Note that trailing zeros are ignored so that ``[3, 0]`` does not show\n up in the following list (since ``[3]`` does)::\n\n sage: IntegerVectors(3, max_length=2).list()\n [[3], [2, 1], [1, 2], [0, 3]]\n\n If ``n`` and ``k`` are both specified, then it returns the class\n of integer vectors that sum to ``n`` and are of length ``k``::\n\n sage: IV53 = IntegerVectors(5,3); IV53\n Integer vectors of length 3 that sum to 5\n sage: IV53.cardinality()\n 21\n sage: IV53.first()\n [5, 0, 0]\n sage: IV53.last()\n [0, 0, 5]\n sage: IV53.random_element().parent() is IV53\n True\n\n Further examples::\n\n sage: IntegerVectors(-1, 0, min_part=1).list()\n []\n sage: IntegerVectors(-1, 2, min_part=1).list()\n []\n sage: IntegerVectors(0, 0, min_part=1).list()\n [[]]\n sage: IntegerVectors(3, 0, min_part=1).list()\n []\n sage: IntegerVectors(0, 1, min_part=1).list()\n []\n sage: IntegerVectors(2, 2, min_part=1).list()\n [[1, 1]]\n sage: IntegerVectors(2, 3, min_part=1).list()\n []\n sage: IntegerVectors(4, 2, min_part=1).list()\n [[3, 1], [2, 2], [1, 3]]\n\n ::\n\n sage: IntegerVectors(0, 3, outer=[0,0,0]).list()\n [[0, 0, 0]]\n sage: IntegerVectors(1, 3, outer=[0,0,0]).list()\n []\n sage: IntegerVectors(2, 3, outer=[0,2,0]).list()\n [[0, 2, 0]]\n sage: IntegerVectors(2, 3, outer=[1,2,1]).list()\n [[1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1]]\n sage: IntegerVectors(2, 3, outer=[1,1,1]).list()\n [[1, 1, 0], [1, 0, 1], [0, 1, 1]]\n sage: IntegerVectors(2, 5, outer=[1,1,1,1,1]).list()\n [[1, 1, 0, 0, 0],\n [1, 0, 1, 0, 0],\n [1, 0, 0, 1, 0],\n [1, 0, 0, 0, 1],\n [0, 1, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [0, 1, 0, 0, 1],\n [0, 0, 1, 1, 0],\n [0, 0, 1, 0, 1],\n [0, 0, 0, 1, 1]]\n\n ::\n\n sage: iv = [ IntegerVectors(n,k) for n in range(-2, 7) for k in range(7) ]\n sage: all(map(lambda x: x.cardinality() == len(x.list()), iv))\n True\n sage: essai = [[1,1,1], [2,5,6], [6,5,2]]\n sage: iv = [ IntegerVectors(x[0], x[1], max_part = x[2]-1) for x in essai ]\n sage: all(map(lambda x: x.cardinality() == len(x.list()), iv))\n True\n\n An example showing the same output by using IntegerListsLex::\n\n sage: IntegerVectors(4, max_length=2).list()\n [[4], [3, 1], [2, 2], [1, 3], [0, 4]]\n sage: list(IntegerListsLex(4, max_length=2))\n [[4], [3, 1], [2, 2], [1, 3], [0, 4]]\n\n .. SEEALSO::\n\n :class:`sage.combinat.integer_lists.invlex.IntegerListsLex`\n '
@staticmethod
def __classcall_private__(cls, n=None, k=None, **kwargs):
"\n Choose the correct parent based upon input.\n\n EXAMPLES::\n\n sage: IV1 = IntegerVectors(3, 2)\n sage: IV2 = IntegerVectors(3, 2)\n sage: IV1 is IV2\n True\n\n TESTS::\n\n sage: IV2 = IntegerVectors(3, 2, length=2)\n Traceback (most recent call last):\n ...\n ValueError: k and length both specified\n\n :trac:`29524`::\n\n sage: IntegerVectors(3, 3/1)\n Traceback (most recent call last):\n ...\n TypeError: 'k' must be an integer or a tuple, got Rational\n "
if ('length' in kwargs):
if (k is not None):
raise ValueError('k and length both specified')
k = kwargs.pop('length')
if kwargs:
return IntegerVectorsConstraints(n, k, **kwargs)
if (k is None):
if (n is None):
return IntegerVectors_all()
return IntegerVectors_n(n)
if (n is None):
return IntegerVectors_k(k)
if isinstance(k, numbers.Integral):
return IntegerVectors_nk(n, k)
elif isinstance(k, (tuple, list)):
return IntegerVectors_nnondescents(n, tuple(k))
else:
raise TypeError("'k' must be an integer or a tuple, got {}".format(type(k).__name__))
def __init__(self, category=None):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: TestSuite(IV).run()\n '
if (category is None):
category = EnumeratedSets()
Parent.__init__(self, category=category)
def _element_constructor_(self, lst):
'\n Construct an element of ``self`` from ``lst``.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: elt = IV([3, 1, 0, 3, 2]); elt\n [3, 1, 0, 3, 2]\n sage: elt.parent()\n Integer vectors\n\n sage: IV9 = IntegerVectors(9)\n sage: elt9 = IV9(elt)\n sage: elt9.parent()\n Integer vectors that sum to 9\n '
return self.element_class(self, lst)
Element = IntegerVector
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: [] in IntegerVectors()\n True\n sage: [3,2,2,1] in IntegerVectors()\n True\n '
if isinstance(x, IntegerVector):
return True
if (not isinstance(x, Sequence)):
return False
for i in x:
if (i not in ZZ):
return False
if (i < 0):
return False
return True
def _unrank_helper(self, x, rtn):
'\n Return the element at rank ``x`` by iterating through all integer vectors beginning with ``rtn``.\n\n INPUT:\n\n - ``x`` - a nonnegative integer\n - ``rtn`` - a list of nonnegative integers\n\n\n EXAMPLES::\n\n sage: IV = IntegerVectors(k=5)\n sage: IV._unrank_helper(10, [2,0,0,0,0])\n [1, 0, 0, 0, 1]\n\n sage: IV = IntegerVectors(n=7)\n sage: IV._unrank_helper(100, [7,0,0,0])\n [2, 0, 0, 5]\n\n sage: IV = IntegerVectors(n=12, k=7)\n sage: IV._unrank_helper(1000, [12,0,0,0,0,0,0])\n [5, 3, 1, 1, 1, 1, 0]\n '
ptr = 0
while True:
current_rank = self.rank(rtn)
if (current_rank < x):
rtn[(ptr + 1)] = rtn[ptr]
rtn[ptr] = 0
ptr += 1
elif (current_rank > x):
rtn[ptr] -= 1
rtn[(ptr - 1)] += 1
else:
return self._element_constructor_(rtn)
|
class IntegerVectors_all(UniqueRepresentation, IntegerVectors):
'\n Class of all integer vectors.\n '
def __init__(self):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: TestSuite(IV).run()\n '
IntegerVectors.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
'\n EXAMPLES::\n\n sage: IntegerVectors()\n Integer vectors\n '
return 'Integer vectors'
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: it = IV.__iter__()\n sage: [next(it) for x in range(10)]\n [[], [1], [2], [2, 0], [1, 1], [0, 2], [3], [3, 0], [2, 1], [1, 2]]\n '
(yield self.element_class(self, []))
n = 1
while True:
for k in range(1, (n + 1)):
for v in integer_vectors_nk_fast_iter(n, k):
(yield self.element_class(self, v, check=False))
n += 1
|
class IntegerVectors_n(UniqueRepresentation, IntegerVectors):
'\n Integer vectors that sum to `n`.\n '
def __init__(self, n):
'\n TESTS::\n\n sage: IV = IntegerVectors(3)\n sage: TestSuite(IV).run()\n '
self.n = n
if (self.n == 0):
IntegerVectors.__init__(self, category=EnumeratedSets())
else:
IntegerVectors.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
'\n TESTS::\n\n sage: IV = IntegerVectors(3)\n sage: IV\n Integer vectors that sum to 3\n '
return 'Integer vectors that sum to {}'.format(self.n)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = IntegerVectors(3).__iter__()\n sage: [next(it) for x in range(10)]\n [[3],\n [3, 0],\n [2, 1],\n [1, 2],\n [0, 3],\n [3, 0, 0],\n [2, 1, 0],\n [2, 0, 1],\n [1, 2, 0],\n [1, 1, 1]]\n '
if (not self.n):
(yield self.element_class(self, []))
k = 1
while True:
for iv in integer_vectors_nk_fast_iter(self.n, k):
(yield self.element_class(self, iv, check=False))
k += 1
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: [0] in IntegerVectors(0)\n True\n sage: [3] in IntegerVectors(3)\n True\n sage: [3] in IntegerVectors(2)\n False\n sage: [3,2,2,1] in IntegerVectors(9)\n False\n sage: [3,2,2,1] in IntegerVectors(8)\n True\n '
if (not IntegerVectors.__contains__(self, x)):
return False
return (sum(x) == self.n)
def rank(self, x):
'\n Return the rank of a given element.\n\n INPUT:\n\n - ``x`` -- a list with ``sum(x) == n``\n\n EXAMPLES::\n\n sage: IntegerVectors(n=5).rank([5,0])\n 1\n sage: IntegerVectors(n=5).rank([3,2])\n 3\n '
if (sum(x) != self.n):
raise ValueError('argument is not a member of IntegerVectors({},{})'.format(self.n, None))
(n, k, s) = (self.n, len(x), 0)
r = binomial(((k + n) - 1), (n + 1))
for i in range((k - 1)):
s += x[((k - 1) - i)]
r += binomial((s + i), (i + 1))
return r
def unrank(self, x):
'\n Return the element at given rank x.\n\n INPUT:\n\n - ``x`` -- an integer.\n\n EXAMPLES::\n\n sage: IntegerVectors(n=5).unrank(2)\n [4, 1]\n sage: IntegerVectors(n=10).unrank(10)\n [1, 9]\n '
rtn = [self.n]
while (self.rank(rtn) <= x):
rtn.append(0)
rtn.pop()
return IntegerVectors._unrank_helper(self, x, rtn)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: IntegerVectors(n=0).cardinality()\n 1\n sage: IntegerVectors(n=10).cardinality()\n +Infinity\n '
if (self.n == 0):
return Integer(1)
return PlusInfinity()
|
class IntegerVectors_k(UniqueRepresentation, IntegerVectors):
'\n Integer vectors of length `k`.\n '
def __init__(self, k):
'\n TESTS::\n\n sage: IV = IntegerVectors(k=2)\n sage: TestSuite(IV).run()\n '
self.k = k
if (self.k == 0):
IntegerVectors.__init__(self, category=EnumeratedSets())
else:
IntegerVectors.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
'\n TESTS::\n\n sage: IV = IntegerVectors(k=2)\n sage: IV\n Integer vectors of length 2\n '
return 'Integer vectors of length {}'.format(self.k)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = IntegerVectors(k=2).__iter__()\n sage: [next(it) for x in range(10)]\n [[0, 0],\n [1, 0],\n [0, 1],\n [2, 0],\n [1, 1],\n [0, 2],\n [3, 0],\n [2, 1],\n [1, 2],\n [0, 3]]\n '
n = 0
while True:
for iv in integer_vectors_nk_fast_iter(n, self.k):
(yield self.element_class(self, iv, check=False))
n += 1
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: [] in IntegerVectors(k=0)\n True\n sage: [3] in IntegerVectors(k=1)\n True\n sage: [3] in IntegerVectors(k=2)\n False\n sage: [3,2,2,1] in IntegerVectors(k=3)\n False\n sage: [3,2,2,1] in IntegerVectors(k=4)\n True\n '
if (not IntegerVectors.__contains__(self, x)):
return False
return (len(x) == self.k)
def rank(self, x):
'\n Return the rank of a given element.\n\n INPUT:\n\n - ``x`` -- a list with ``len(x) == k``\n\n EXAMPLES::\n\n sage: IntegerVectors(k=5).rank([0,0,0,0,0])\n 0\n sage: IntegerVectors(k=5).rank([1,1,0,0,0])\n 7\n '
if (len(x) != self.k):
raise ValueError('argument is not a member of IntegerVectors({},{})'.format(None, self.k))
(n, k, s) = (sum(x), self.k, 0)
r = binomial(((n + k) - 1), k)
for i in range((k - 1)):
s += x[((k - 1) - i)]
r += binomial((s + i), (i + 1))
return r
def unrank(self, x):
'\n Return the element at given rank x.\n\n INPUT:\n\n - ``x`` -- an integer such that x < self.cardinality()``\n\n EXAMPLES::\n\n sage: IntegerVectors(k=5).unrank(10)\n [1, 0, 0, 0, 1]\n sage: IntegerVectors(k=5).unrank(15)\n [0, 0, 2, 0, 0]\n sage: IntegerVectors(k=0).unrank(0)\n []\n '
if ((self.k == 0) and (x != 0)):
raise IndexError(f'Index {x} is out of range for the IntegerVector.')
rtn = ([0] * self.k)
if ((self.k == 0) and (x == 0)):
return rtn
while (self.rank(rtn) <= x):
rtn[0] += 1
rtn[0] -= 1
return IntegerVectors._unrank_helper(self, x, rtn)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: IntegerVectors(k=0).cardinality()\n 1\n sage: IntegerVectors(k=10).cardinality()\n +Infinity\n '
if (self.k == 0):
return Integer(1)
return PlusInfinity()
|
class IntegerVectors_nk(UniqueRepresentation, IntegerVectors):
'\n Integer vectors of length `k` that sum to `n`.\n\n AUTHORS:\n\n - Martin Albrecht\n - Mike Hansen\n '
def __init__(self, n, k):
'\n TESTS::\n\n sage: IV = IntegerVectors(2, 3)\n sage: TestSuite(IV).run()\n '
self.n = n
self.k = k
IntegerVectors.__init__(self, category=FiniteEnumeratedSets())
def _list_rec(self, n, k):
'\n Return a list of a exponent tuples of length ``size`` such\n that the degree of the associated monomial is `D`.\n\n INPUT:\n\n - ``n`` -- degree (must be 0)\n\n - ``k`` -- length of exponent tuples (must be 0)\n\n EXAMPLES::\n\n sage: IV = IntegerVectors(2,3)\n sage: IV._list_rec(2,3)\n [(2, 0, 0), (1, 1, 0), (1, 0, 1), (0, 2, 0), (0, 1, 1), (0, 0, 2)]\n '
res = []
if (k == 1):
return [(n,)]
for nbar in range((n + 1)):
n_diff = (n - nbar)
for rest in self._list_rec(nbar, (k - 1)):
res.append(((n_diff,) + rest))
return res
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors(2, 3)\n sage: list(IV)\n [[2, 0, 0], [1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1], [0, 0, 2]]\n sage: list(IntegerVectors(3, 0))\n []\n sage: list(IntegerVectors(3, 1))\n [[3]]\n sage: list(IntegerVectors(0, 1))\n [[0]]\n sage: list(IntegerVectors(0, 2))\n [[0, 0]]\n sage: list(IntegerVectors(2, 2))\n [[2, 0], [1, 1], [0, 2]]\n sage: IntegerVectors(0, 0).list()\n [[]]\n sage: IntegerVectors(1, 0).list()\n []\n sage: IntegerVectors(0, 1).list()\n [[0]]\n sage: IntegerVectors(2, 2).list()\n [[2, 0], [1, 1], [0, 2]]\n sage: IntegerVectors(-1,0).list()\n []\n sage: IntegerVectors(-1,2).list()\n []\n '
if (self.n < 0):
return
if (not self.k):
if (not self.n):
(yield self.element_class(self, [], check=False))
return
elif (self.k == 1):
(yield self.element_class(self, [self.n], check=False))
return
for nbar in range((self.n + 1)):
n = (self.n - nbar)
for rest in integer_vectors_nk_fast_iter(nbar, (self.k - 1)):
(yield self.element_class(self, ([n] + rest), check=False))
def _repr_(self):
'\n TESTS::\n\n sage: IV = IntegerVectors(2,3)\n sage: IV\n Integer vectors of length 3 that sum to 2\n '
return 'Integer vectors of length {} that sum to {}'.format(self.k, self.n)
def __contains__(self, x):
"\n TESTS::\n\n sage: IV = IntegerVectors(2, 3)\n sage: all(i in IV for i in IV)\n True\n sage: [0,1,2] in IV\n False\n sage: [2.0, 0, 0] in IV\n True\n sage: [0,1,0,1] in IV\n False\n sage: [0,1,1] in IV\n True\n sage: [-1,2,1] in IV\n False\n\n sage: [0] in IntegerVectors(0, 1)\n True\n sage: [] in IntegerVectors(0, 0)\n True\n sage: [] in IntegerVectors(0, 1)\n False\n sage: [] in IntegerVectors(1, 0)\n False\n sage: [3] in IntegerVectors(2, 1)\n False\n sage: [3] in IntegerVectors(3, 1)\n True\n sage: [3,2,2,1] in IntegerVectors(9, 5)\n False\n sage: [3,2,2,1] in IntegerVectors(8, 5)\n False\n sage: [3,2,2,1] in IntegerVectors(8, 4)\n True\n\n Check :trac:`34510`::\n\n sage: IV33 = IntegerVectors(n=3, k=3)\n sage: IV33([0])\n Traceback (most recent call last):\n ...\n ValueError: [0] doesn't satisfy correct constraints\n "
if (not IntegerVectors.__contains__(self, x)):
return False
if (len(x) != self.k):
return False
if (sum(x) != self.n):
return False
if ((len(x) > 0) and (min(x) < 0)):
return False
return True
def rank(self, x):
'\n Return the rank of a given element.\n\n INPUT:\n\n - ``x`` -- a list with ``sum(x) == n`` and ``len(x) == k``\n\n TESTS::\n\n sage: IV = IntegerVectors(4,5)\n sage: list(range(IV.cardinality())) == [IV.rank(x) for x in IV]\n True\n '
if (x not in self):
raise ValueError('argument is not a member of IntegerVectors({},{})'.format(self.n, self.k))
(k, s, r) = (self.k, 0, 0)
for i in range((k - 1)):
s += x[((k - 1) - i)]
r += binomial((s + i), (i + 1))
return r
def unrank(self, x):
'\n Return the element at given rank x.\n\n INPUT:\n\n - ``x`` -- an integer such that ``x < self.cardinality()``\n\n EXAMPLES::\n\n sage: IntegerVectors(4,5).unrank(30)\n [1, 0, 1, 0, 2]\n sage: IntegerVectors(2,3).unrank(5)\n [0, 0, 2]\n '
if (x >= self.cardinality()):
raise IndexError(f'Index {x} is out of range for the IntegerVector.')
rtn = ([0] * self.k)
rtn[0] = self.n
return IntegerVectors._unrank_helper(self, x, rtn)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: IntegerVectors(3,5).cardinality()\n 35\n sage: IntegerVectors(99, 3).cardinality()\n 5050\n sage: IntegerVectors(10^9 - 1, 3).cardinality()\n 500000000500000000\n '
(n, k) = (self.n, self.k)
return Integer(binomial(((n + k) - 1), n))
|
class IntegerVectors_nnondescents(UniqueRepresentation, IntegerVectors):
'\n Integer vectors graded by two parameters.\n\n The grading parameters on the integer vector `v` are:\n\n - `n` -- the sum of the parts of `v`,\n\n - `c` -- the non descents composition of `v`.\n\n In other words: the length of `v` equals `c_1 + \\cdots + c_k`, and `v`\n is decreasing in the consecutive blocs of length `c_1, \\ldots, c_k`,\n\n INPUT:\n\n - ``n`` -- the positive integer `n`\n - ``comp`` -- the composition `c`\n\n Those are the integer vectors of sum `n` that are lexicographically\n maximal (for the natural left-to-right reading) in their orbit by the\n Young subgroup `S_{c_1} \\times \\cdots \\times S_{c_k}`. In particular,\n they form a set of orbit representative of integer vectors with\n respect to this Young subgroup.\n '
@staticmethod
def __classcall_private__(cls, n, comp):
'\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: IntegerVectors(4, [2,1]) is IntegerVectors(int(4), (2,1))\n True\n '
return super().__classcall__(cls, n, tuple(comp))
def __init__(self, n, comp):
'\n EXAMPLES::\n\n sage: IV = IntegerVectors(4, [2])\n sage: TestSuite(IV).run()\n '
self.n = n
self.comp = comp
IntegerVectors.__init__(self, category=FiniteEnumeratedSets())
def _repr_(self):
'\n EXAMPLES::\n\n sage: IntegerVectors(4, [2])\n Integer vectors of 4 with non-descents composition [2]\n '
return 'Integer vectors of {} with non-descents composition {}'.format(self.n, list(self.comp))
def __iter__(self):
'\n TESTS::\n\n sage: IntegerVectors(0, []).list()\n [[]]\n sage: IntegerVectors(5, []).list()\n []\n sage: IntegerVectors(0, [1]).list()\n [[0]]\n sage: IntegerVectors(4, [1]).list()\n [[4]]\n sage: IntegerVectors(4, [2]).list()\n [[4, 0], [3, 1], [2, 2]]\n sage: IntegerVectors(4, [2,2]).list()\n [[4, 0, 0, 0],\n [3, 1, 0, 0],\n [2, 2, 0, 0],\n [3, 0, 1, 0],\n [2, 1, 1, 0],\n [2, 0, 2, 0],\n [2, 0, 1, 1],\n [1, 1, 2, 0],\n [1, 1, 1, 1],\n [1, 0, 3, 0],\n [1, 0, 2, 1],\n [0, 0, 4, 0],\n [0, 0, 3, 1],\n [0, 0, 2, 2]]\n sage: IntegerVectors(5, [1,1,1]).list()\n [[5, 0, 0],\n [4, 1, 0],\n [4, 0, 1],\n [3, 2, 0],\n [3, 1, 1],\n [3, 0, 2],\n [2, 3, 0],\n [2, 2, 1],\n [2, 1, 2],\n [2, 0, 3],\n [1, 4, 0],\n [1, 3, 1],\n [1, 2, 2],\n [1, 1, 3],\n [1, 0, 4],\n [0, 5, 0],\n [0, 4, 1],\n [0, 3, 2],\n [0, 2, 3],\n [0, 1, 4],\n [0, 0, 5]]\n sage: IntegerVectors(0, [2,3]).list()\n [[0, 0, 0, 0, 0]]\n '
for iv in IntegerVectors(self.n, len(self.comp)):
blocks = [IntegerVectors(iv[i], val, max_slope=0).list() for (i, val) in enumerate(self.comp)]
for parts in product(*blocks):
res = []
for part in parts:
res += part
(yield self.element_class(self, res, check=False))
|
class IntegerVectorsConstraints(IntegerVectors):
'\n Class of integer vectors subject to various constraints.\n '
def __init__(self, n=None, k=None, **constraints):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: TestSuite(IntegerVectors(min_slope=0)).run()\n sage: TestSuite(IntegerVectors(3, max_slope=0)).run()\n sage: TestSuite(IntegerVectors(3, max_length=4)).run()\n sage: TestSuite(IntegerVectors(k=2, max_part=4)).run()\n sage: TestSuite(IntegerVectors(k=2, min_part=2, max_part=4)).run()\n sage: TestSuite(IntegerVectors(3, 2, max_slope=0)).run()\n '
self.n = n
self.k = k
if ((k is not None) and (self.k >= 0)):
constraints['length'] = self.k
if ('outer' in constraints):
constraints['ceiling'] = constraints['outer']
del constraints['outer']
if ('inner' in constraints):
constraints['floor'] = constraints['inner']
del constraints['inner']
self.constraints = constraints
if (n is not None):
if ((k is not None) or ('max_length' in constraints)):
category = FiniteEnumeratedSets()
else:
category = EnumeratedSets()
elif ((k is not None) and ('max_part' in constraints)):
category = FiniteEnumeratedSets()
else:
category = EnumeratedSets()
IntegerVectors.__init__(self, category=category)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: IntegerVectors(min_slope=0)\n Integer vectors with constraints: min_slope=0\n\n sage: IntegerVectors(3, max_length=2)\n Integer vectors that sum to 3 with constraints: max_length=2\n\n sage: IntegerVectors(2, 3, min_slope=0)\n Integer vectors that sum to 2 with constraints: length=3, min_slope=0\n '
if (self.n is not None):
base = 'Integer vectors that sum to {} with constraints: '.format(self.n)
else:
base = 'Integer vectors with constraints: '
return (base + ', '.join(('{}={}'.format(key, self.constraints[key]) for key in sorted(self.constraints))))
def __eq__(self, rhs):
'\n EXAMPLES::\n\n sage: IntegerVectors(min_slope=0) == IntegerVectors(min_slope=0)\n True\n sage: IntegerVectors(2, min_slope=0) == IntegerVectors(2, min_slope=0)\n True\n sage: IntegerVectors(2, 3, min_slope=0) == IntegerVectors(2, 3, min_slope=0)\n True\n '
if isinstance(rhs, IntegerVectorsConstraints):
return ((self.n == rhs.n) and (self.k == rhs.k) and (self.constraints == rhs.constraints))
return False
def __ne__(self, rhs):
'\n EXAMPLES::\n\n sage: IntegerVectors(min_slope=0) != IntegerVectors(min_slope=3)\n True\n '
return (not self.__eq__(rhs))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: hash(IntegerVectors(min_slope=0)) == hash(IntegerVectors(min_slope=0))\n True\n sage: hash(IntegerVectors(2, min_slope=0)) == hash(IntegerVectors(2, min_slope=0))\n True\n sage: hash(IntegerVectors(2, 3, min_slope=0)) == hash(IntegerVectors(2, 3, min_slope=0))\n True\n sage: hash(IntegerVectors(min_slope=0)) != hash(IntegerVectors(min_slope=3))\n True\n '
return hash((self.n, self.k, tuple(self.constraints.items())))
def __contains__(self, x):
'\n TESTS::\n\n sage: [3,2,2,1] in IntegerVectors(8, 4, min_part=1) # needs sage.combinat\n True\n sage: [3,2,2,1] in IntegerVectors(8, 4, min_part=2) # needs sage.combinat\n False\n\n sage: [0,3,0,1,2] in IntegerVectors(6, max_length=3) # needs sage.combinat\n False\n '
if (isinstance(x, IntegerVector) and (x.parent() is self)):
return True
if (not IntegerVectors.__contains__(self, x)):
return False
if ((self.k is not None) and (len(x) != self.k)):
return False
if ((self.n is not None) and (sum(x) != self.n)):
return False
from sage.combinat.misc import check_integer_list_constraints
return check_integer_list_constraints(x, singleton=True, **self.constraints)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: IntegerVectors(3, 3, min_part=1).cardinality()\n 1\n sage: IntegerVectors(5, 3, min_part=1).cardinality()\n 6\n sage: IntegerVectors(13, 4, max_part=4).cardinality()\n 20\n sage: IntegerVectors(k=4, max_part=3).cardinality()\n 256\n sage: IntegerVectors(k=3, min_part=2, max_part=4).cardinality()\n 27\n sage: IntegerVectors(13, 4, min_part=2, max_part=4).cardinality()\n 16\n '
if (self.k is None):
if (self.n is None):
return PlusInfinity()
if (('max_length' not in self.constraints) and (self.constraints.get('min_part', 0) <= 0)):
return PlusInfinity()
elif (('max_part' in self.constraints) and (self.constraints['max_part'] != PlusInfinity())):
if ((self.n is None) and (len(self.constraints) == 2) and ('min_part' in self.constraints) and (self.constraints['min_part'] >= 0)):
num = ((self.constraints['max_part'] - self.constraints['min_part']) + 1)
return Integer((num ** self.k))
if (len(self.constraints) == 1):
m = self.constraints['max_part']
if (self.n is None):
return Integer(((m + 1) ** self.k))
if (m >= self.n):
return Integer(binomial(((self.n + self.k) - 1), self.n))
(n, k) = (self.n, self.k)
return Integer(sum((((((- 1) ** i) * binomial((((n + k) - 1) - (i * (m + 1))), (k - 1))) * binomial(k, i)) for i in range(((self.n // (m + 1)) + 1)))))
return ZZ.sum((ZZ.one() for x in self))
def __iter__(self):
'\n EXAMPLES::\n\n sage: IntegerVectors(-1, 0, min_part=1).list()\n []\n sage: IntegerVectors(-1, 2, min_part=1).list()\n []\n sage: IntegerVectors(0, 0, min_part=1).list()\n [[]]\n sage: IntegerVectors(3, 0, min_part=1).list()\n []\n sage: IntegerVectors(0, 1, min_part=1).list()\n []\n sage: IntegerVectors(2, 2, min_part=1).list()\n [[1, 1]]\n sage: IntegerVectors(2, 3, min_part=1).list()\n []\n sage: IntegerVectors(4, 2, min_part=1).list()\n [[3, 1], [2, 2], [1, 3]]\n\n ::\n\n sage: IntegerVectors(0, 3, outer=[0,0,0]).list()\n [[0, 0, 0]]\n sage: IntegerVectors(1, 3, outer=[0,0,0]).list()\n []\n sage: IntegerVectors(2, 3, outer=[0,2,0]).list()\n [[0, 2, 0]]\n sage: IntegerVectors(2, 3, outer=[1,2,1]).list()\n [[1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1]]\n sage: IntegerVectors(2, 3, outer=[1,1,1]).list()\n [[1, 1, 0], [1, 0, 1], [0, 1, 1]]\n sage: IntegerVectors(2, 5, outer=[1,1,1,1,1]).list()\n [[1, 1, 0, 0, 0],\n [1, 0, 1, 0, 0],\n [1, 0, 0, 1, 0],\n [1, 0, 0, 0, 1],\n [0, 1, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [0, 1, 0, 0, 1],\n [0, 0, 1, 1, 0],\n [0, 0, 1, 0, 1],\n [0, 0, 0, 1, 1]]\n\n ::\n\n sage: iv = [ IntegerVectors(n, k) for n in range(-2, 7) for k in range(7) ]\n sage: all(map(lambda x: x.cardinality() == len(x.list()), iv))\n True\n sage: essai = [[1,1,1], [2,5,6], [6,5,2]]\n sage: iv = [ IntegerVectors(x[0], x[1], max_part=x[2]-1) for x in essai ]\n sage: all(map(lambda x: x.cardinality() == len(x.list()), iv))\n True\n '
if (self.n is None):
if ((self.k is not None) and ('max_part' in self.constraints)):
n_list = range(((self.constraints['max_part'] + 1) * self.k))
else:
n_list = NN
else:
n_list = [self.n]
for n in n_list:
for x in IntegerListsLex(n, check=False, **self.constraints):
(yield self.element_class(self, x, check=False))
|
def integer_vectors_nk_fast_iter(n, k):
'\n A fast iterator for integer vectors of ``n`` of length ``k`` which\n yields Python lists filled with Sage Integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_vector import integer_vectors_nk_fast_iter\n sage: list(integer_vectors_nk_fast_iter(3, 2))\n [[3, 0], [2, 1], [1, 2], [0, 3]]\n sage: list(integer_vectors_nk_fast_iter(2, 2))\n [[2, 0], [1, 1], [0, 2]]\n sage: list(integer_vectors_nk_fast_iter(1, 2))\n [[1, 0], [0, 1]]\n\n We check some corner cases::\n\n sage: list(integer_vectors_nk_fast_iter(5, 1))\n [[5]]\n sage: list(integer_vectors_nk_fast_iter(1, 1))\n [[1]]\n sage: list(integer_vectors_nk_fast_iter(2, 0))\n []\n sage: list(integer_vectors_nk_fast_iter(0, 2))\n [[0, 0]]\n sage: list(integer_vectors_nk_fast_iter(0, 0))\n [[]]\n '
if ((n < 0) or (k < 0)):
return
if (not k):
if (not n):
(yield [])
return
n = Integer(n)
if (k == 1):
(yield [n])
return
zero = ZZ.zero()
one = ZZ.one()
k = int(k)
pos = 0
rem = zero
cur = ([n] + ([zero] * (k - 1)))
(yield list(cur))
while (pos >= 0):
if (not cur[pos]):
pos -= 1
continue
cur[pos] -= one
rem += one
if (not rem):
(yield list(cur))
elif (pos == (k - 2)):
cur[(pos + 1)] = rem
(yield list(cur))
cur[(pos + 1)] = zero
else:
pos += 1
cur[pos] = rem
rem = zero
(yield list(cur))
|
class WeightedIntegerVectors(Parent, UniqueRepresentation):
'\n The class of integer vectors of `n` weighted by ``weight``, that is, the\n nonnegative integer vectors `(v_1, \\ldots, v_{\\ell})`\n satisfying `\\sum_{i=1}^{\\ell} v_i w_i = n` where `\\ell` is\n ``length(weight)`` and `w_i` is ``weight[i]``.\n\n INPUT:\n\n - ``n`` -- a non negative integer (optional)\n\n - ``weight`` -- a tuple (or list or iterable) of positive integers\n\n EXAMPLES::\n\n sage: WeightedIntegerVectors(8, [1,1,2])\n Integer vectors of 8 weighted by [1, 1, 2]\n sage: WeightedIntegerVectors(8, [1,1,2]).first()\n [0, 0, 4]\n sage: WeightedIntegerVectors(8, [1,1,2]).last()\n [8, 0, 0]\n sage: WeightedIntegerVectors(8, [1,1,2]).cardinality()\n 25\n sage: w = WeightedIntegerVectors(8, [1,1,2]).random_element()\n sage: w.parent() is WeightedIntegerVectors(8, [1,1,2])\n True\n\n sage: WeightedIntegerVectors([1,1,2])\n Integer vectors weighted by [1, 1, 2]\n sage: WeightedIntegerVectors([1,1,2]).cardinality()\n +Infinity\n sage: WeightedIntegerVectors([1,1,2]).first()\n [0, 0, 0]\n\n TESTS::\n\n sage: WeightedIntegerVectors(None,None)\n Traceback (most recent call last):\n ...\n ValueError: the weights must be specified\n\n .. TODO::\n\n Should the order of the arguments ``n`` and ``weight`` be\n exchanged to simplify the logic?\n '
@staticmethod
def __classcall_private__(cls, n=None, weight=None):
'\n Normalize inputs to ensure a unique representation.\n\n TESTS::\n\n sage: W = WeightedIntegerVectors(8, [1,1,2])\n sage: W2 = WeightedIntegerVectors(int(8), (1,1,2))\n sage: W is W2\n True\n '
if (weight is None):
if (n is None):
raise ValueError('the weights must be specified')
if (n in ZZ):
weight = (n,)
else:
weight = tuple(n)
n = None
weight = tuple(weight)
if (n is None):
return WeightedIntegerVectors_all(weight)
return super().__classcall__(cls, n, weight)
def __init__(self, n, weight):
'\n TESTS::\n\n sage: WIV = WeightedIntegerVectors(8, [1,1,2])\n sage: TestSuite(WIV).run()\n '
self._n = n
self._weights = weight
Parent.__init__(self, category=FiniteEnumeratedSets())
Element = IntegerVector
def _element_constructor_(self, lst):
'\n Construct an element of ``self`` from ``lst``.\n\n EXAMPLES::\n\n sage: WIV = WeightedIntegerVectors(3, [2,1,1])\n sage: elt = WIV([1, 1, 0]); elt\n [1, 1, 0]\n sage: elt.parent() is WIV\n True\n sage: WIV([1, 1, 0])\n [1, 1, 0]\n sage: WIV([1, 2, 0])\n Traceback (most recent call last):\n ...\n ValueError: cannot convert [1, 2, 0] into Integer vectors of 3\n weighted by [2, 1, 1]\n\n '
if isinstance(lst, IntegerVector):
if (lst.parent() is self):
return lst
if (lst not in self):
raise ValueError(('cannot convert %s into %s' % (lst, self)))
return self.element_class(self, lst)
def _repr_(self):
'\n TESTS::\n\n sage: WeightedIntegerVectors(8, [1,1,2])\n Integer vectors of 8 weighted by [1, 1, 2]\n '
return ('Integer vectors of %s weighted by %s' % (self._n, list(self._weights)))
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: [] in WeightedIntegerVectors(0, [])\n True\n sage: [] in WeightedIntegerVectors(1, [])\n False\n sage: [3,0,0] in WeightedIntegerVectors(6, [2,1,1])\n True\n sage: [1] in WeightedIntegerVectors(1, [1])\n True\n sage: [1] in WeightedIntegerVectors(2, [2])\n True\n sage: [2] in WeightedIntegerVectors(4, [2])\n True\n sage: [2, 0] in WeightedIntegerVectors(4, [2, 2])\n True\n sage: [2, 1] in WeightedIntegerVectors(4, [2, 2])\n False\n sage: [2, 1] in WeightedIntegerVectors(6, [2, 2])\n True\n sage: [2, 1, 0] in WeightedIntegerVectors(6, [2, 2])\n False\n sage: [0] in WeightedIntegerVectors(0, [])\n False\n '
if (not isinstance(x, (list, IntegerVector, Permutation))):
return False
if (len(self._weights) != len(x)):
return False
s = 0
for (i, val) in enumerate(x):
if ((not isinstance(val, (int, Integer))) and (val not in ZZ)):
return False
s += (x[i] * self._weights[i])
return (s == self._n)
def _recfun(self, n, l):
'\n EXAMPLES::\n\n sage: w = WeightedIntegerVectors(3, [2,1,1])\n sage: list(w._recfun(3, [1,1,2]))\n [[0, 1, 1], [1, 0, 1], [0, 3, 0], [1, 2, 0], [2, 1, 0], [3, 0, 0]]\n '
w = l[(- 1)]
l = l[:(- 1)]
if (l == []):
d = (int(n) // int(w))
if ((n % w) == 0):
(yield [d])
return
for d in range((int(n) // int(w)), (- 1), (- 1)):
for x in self._recfun((n - (d * w)), l):
(yield (x + [d]))
def __iter__(self):
'\n TESTS::\n\n sage: WeightedIntegerVectors(7, [2,2]).list()\n []\n sage: WeightedIntegerVectors(3, [2,1,1]).list()\n [[1, 0, 1], [1, 1, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0]]\n\n ::\n\n sage: ivw = [ WeightedIntegerVectors(k, [1,1,1]) for k in range(11) ]\n sage: iv = [ IntegerVectors(k, 3) for k in range(11) ]\n sage: all(sorted(map(list, iv[k])) == sorted(map(list, ivw[k])) for k in range(11))\n True\n\n ::\n\n sage: ivw = [ WeightedIntegerVectors(k, [2,3,7]) for k in range(11) ]\n sage: all(i.cardinality() == len(i.list()) for i in ivw)\n True\n '
if (not self._weights):
if (self._n == 0):
(yield self.element_class(self, []))
return
perm = Word(self._weights).standard_permutation()
perm = [(len(self._weights) - i) for i in perm]
l = [x for x in sorted(self._weights, reverse=True)]
for x in iterator_fast(self._n, l):
(yield self.element_class(self, [x[i] for i in perm]))
|
class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets):
'\n Set of weighted integer vectors.\n\n EXAMPLES::\n\n sage: W = WeightedIntegerVectors([3,1,1,2,1]); W\n Integer vectors weighted by [3, 1, 1, 2, 1]\n sage: W.cardinality()\n +Infinity\n\n sage: W12 = W.graded_component(12)\n sage: W12.an_element()\n [4, 0, 0, 0, 0]\n sage: W12.last()\n [0, 12, 0, 0, 0]\n sage: W12.cardinality()\n 441\n sage: for w in W12: print(w)\n [4, 0, 0, 0, 0]\n [3, 0, 0, 1, 1]\n [3, 0, 1, 1, 0]\n ...\n [0, 11, 1, 0, 0]\n [0, 12, 0, 0, 0]\n '
def __init__(self, weight):
'\n TESTS::\n\n sage: C = WeightedIntegerVectors([2,1,3])\n sage: C.category()\n Category of facade infinite enumerated sets with grading\n sage: TestSuite(C).run()\n '
self._weights = weight
from sage.sets.family import Family
from sage.sets.non_negative_integers import NonNegativeIntegers
from functools import partial
F = Family(NonNegativeIntegers(), partial(WeightedIntegerVectors, weight=weight))
cat = (SetsWithGrading(), InfiniteEnumeratedSets())
DisjointUnionEnumeratedSets.__init__(self, F, facade=True, keepkey=False, category=cat)
def _repr_(self):
'\n EXAMPLES::\n\n sage: WeightedIntegerVectors([2,1,3])\n Integer vectors weighted by [2, 1, 3]\n '
return ('Integer vectors weighted by %s' % list(self._weights))
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: [] in WeightedIntegerVectors([])\n True\n sage: [3,0,0] in WeightedIntegerVectors([2,1,1])\n True\n sage: [3,0] in WeightedIntegerVectors([2,1,1])\n False\n sage: [3,-1,0] in WeightedIntegerVectors([2,1,1])\n False\n '
return (isinstance(x, (list, IntegerVector, Permutation)) and (len(x) == len(self._weights)) and all((((i in ZZ) and (i >= 0)) for i in x)))
def subset(self, size=None):
'\n EXAMPLES::\n\n sage: C = WeightedIntegerVectors([2,1,3])\n sage: C.subset(4)\n Integer vectors of 4 weighted by [2, 1, 3]\n '
if (size is None):
return self
return self._family[size]
def grading(self, x):
'\n EXAMPLES::\n\n sage: C = WeightedIntegerVectors([2,1,3])\n sage: C.grading((2,1,1))\n 8\n '
return sum(((exp * deg) for (exp, deg) in zip(x, self._weights)))
|
def iterator_fast(n, l):
"\n Iterate over all ``l`` weighted integer vectors with total weight ``n``.\n\n INPUT:\n\n - ``n`` -- an integer\n - ``l`` -- the weights in weakly decreasing order\n\n EXAMPLES::\n\n sage: from sage.combinat.integer_vector_weighted import iterator_fast\n sage: list(iterator_fast(3, [2,1,1]))\n [[1, 1, 0], [1, 0, 1], [0, 3, 0], [0, 2, 1], [0, 1, 2], [0, 0, 3]]\n sage: list(iterator_fast(2, [2]))\n [[1]]\n\n Test that :trac:`20491` is fixed::\n\n sage: type(list(iterator_fast(2, [2]))[0][0])\n <class 'sage.rings.integer.Integer'>\n "
if (n < 0):
return
zero = ZZ.zero()
one = ZZ.one()
if (not l):
if (n == 0):
(yield [])
return
if (len(l) == 1):
if ((n % l[0]) == 0):
(yield [(n // l[0])])
return
k = 0
cur = [((n // l[k]) + one)]
rem = (n - (cur[(- 1)] * l[k]))
while cur:
cur[(- 1)] -= one
rem += l[k]
if (rem == zero):
(yield (cur + ([zero] * (len(l) - len(cur)))))
elif ((cur[(- 1)] < zero) or (rem < zero)):
rem += (cur.pop() * l[k])
k -= 1
elif (len(l) == (len(cur) + 1)):
if ((rem % l[(- 1)]) == zero):
(yield (cur + [(rem // l[(- 1)])]))
else:
k += 1
cur.append(((rem // l[k]) + one))
rem -= (cur[(- 1)] * l[k])
|
class IntegerVectorsModPermutationGroup(UniqueRepresentation):
"\n Return an enumerated set containing integer vectors which are\n maximal in their orbit under the action of the permutation group\n ``G`` for the lexicographic order.\n\n In Sage, a permutation group `G` is viewed as a subgroup of the\n symmetric group `S_n` of degree `n` and `n` is said to be the degree\n of `G`. Any integer vector `v` is said to be canonical if it\n is maximal in its orbit under the action of `G`. `v` is\n canonical if and only if\n\n .. MATH::\n\n v = \\max_{\\text{lex order}} \\{g \\cdot v | g \\in G \\}\n\n The action of `G` is on position. This means for example that the\n simple transposition `s_1 = (1, 2)` swaps the first and the second\n entries of any integer vector `v = [a_1, a_2, a_3, \\dots , a_n]`\n\n .. MATH::\n\n s_1 \\cdot v = [a_2, a_1, a_3, \\dots , a_n]\n\n This function returns a parent which contains, from each orbit\n orbit under the action of the permutation group `G`, a single\n canonical vector. The canonical vector is the one that is maximal\n within the orbit according to lexicographic order.\n\n INPUT:\n\n - ``G`` - a permutation group\n - ``sum`` - (default: None) - a nonnegative integer\n - ``max_part`` - (default: None) - a nonnegative integer setting the\n maximum value for every element\n - ``sgs`` - (default: None) - a strong generating system of the\n group `G`. If you do not provide it, it will be calculated at the\n creation of the parent\n\n OUTPUT:\n\n - If ``sum`` and ``max_part`` are None, it returns the infinite\n enumerated set of all integer vectors (lists of integers) maximal\n in their orbit for the lexicographic order. Exceptionally, if\n the domain of ``G`` is empty, the result is a finite enumerated\n set that contains one element, namely the empty vector.\n\n - If ``sum`` is an integer, it returns a finite enumerated set\n containing all integer vectors maximal in their orbit for the\n lexicographic order and whose entries sum to ``sum``.\n\n EXAMPLES:\n\n Here is the set enumerating integer vectors modulo the action of the cyclic\n group of `3` elements::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]))\n sage: I.category()\n Category of infinite enumerated quotients of sets\n sage: I.cardinality()\n +Infinity\n sage: I.list()\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: p = iter(I)\n sage: for i in range(10): next(p)\n [0, 0, 0]\n [1, 0, 0]\n [2, 0, 0]\n [1, 1, 0]\n [3, 0, 0]\n [2, 1, 0]\n [2, 0, 1]\n [1, 1, 1]\n [4, 0, 0]\n [3, 1, 0]\n\n The method\n :meth:`~sage.combinat.integer_vectors_mod_permgroup.IntegerVectorsModPermutationGroup_All.is_canonical`\n tests if an integer vector is maximal in its orbit. This method\n is also used in the containment test::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.is_canonical([5,2,0,4])\n True\n sage: I.is_canonical([5,0,6,4])\n False\n sage: I.is_canonical([1,1,1,1])\n True\n sage: [2,3,1,0] in I\n False\n sage: [5,0,5,0] in I\n True\n sage: 'Bla' in I\n False\n sage: I.is_canonical('bla')\n Traceback (most recent call last):\n ...\n AssertionError: bla should be a list or an integer vector\n\n If you give a value to the extra argument ``sum``, the set returned\n will be a finite set containing only canonical vectors whose entries\n sum to ``sum``.::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), sum=6)\n sage: I.cardinality()\n 10\n sage: I.list()\n [[6, 0, 0], [5, 1, 0], [5, 0, 1], [4, 2, 0], [4, 1, 1],\n [4, 0, 2], [3, 3, 0], [3, 2, 1], [3, 1, 2], [2, 2, 2]]\n sage: I.category()\n Join of Category of finite enumerated sets\n and Category of subquotients of finite sets\n and Category of quotients of sets\n\n To get the orbit of any integer vector `v` under the action of the group,\n use the method :meth:`~sage.combinat.integer_vectors_mod_permgroup.IntegerVectorsModPermutationGroup_All.orbit`;\n we convert the returned set of vectors into a list in increasing lexicographic order,\n to get a reproducible test::\n\n sage: sorted(I.orbit([6,0,0]))\n [[0, 0, 6], [0, 6, 0], [6, 0, 0]]\n sage: sorted(I.orbit([5,1,0]))\n [[0, 5, 1], [1, 0, 5], [5, 1, 0]]\n sage: I.orbit([2,2,2])\n {[2, 2, 2]}\n\n Even without constraints, for an empty domain the result is\n a singleton set::\n\n sage: G = PermutationGroup([], domain=[])\n sage: sgs = tuple(tuple(s) for s in G.strong_generating_system())\n sage: list(IntegerVectorsModPermutationGroup(G, sgs=sgs))\n [[]]\n\n\n .. WARNING::\n\n Because of :issue:`36527`, permutation groups that have\n different domains but similar generators can be erroneously\n treated as the same group. This will silently produce\n erroneous results. To avoid this issue, compute a strong\n generating system for the group as::\n\n sgs = tuple(tuple(s) for s in G.strong_generating_system())\n\n and provide it as the optional ``sgs`` argument to the\n constructor.\n\n TESTS:\n\n Let us check that canonical integer vectors of the symmetric group\n are just nonincreasing lists of integers::\n\n sage: I = IntegerVectorsModPermutationGroup(SymmetricGroup(5)) # long time\n sage: p = iter(I) # long time\n sage: for i in range(100): # long time\n ....: v = list(next(p))\n ....: assert sorted(v, reverse=True) == v\n\n We now check that there are as many canonical vectors under the\n symmetric group `S_n` whose entries sum to `d` as there are\n partitions of `d` of at most `n` parts::\n\n sage: I = IntegerVectorsModPermutationGroup(SymmetricGroup(5)) # long time\n sage: for i in range(10): # long time\n ....: d1 = I.subset(i).cardinality()\n ....: d2 = Partitions(i, max_length=5).cardinality()\n ....: print(d1)\n ....: assert d1 == d2\n 1\n 1\n 2\n 3\n 5\n 7\n 10\n 13\n 18\n 23\n\n Another corner case is trivial groups. For the trivial group ``G``\n acting on a list of length `n`, all integer vectors of length `n`\n are canonical::\n\n sage: # long time\n sage: G = PermutationGroup([[(6,)]])\n sage: G.cardinality()\n 1\n sage: sgs = tuple(tuple(s) for s in G.strong_generating_system())\n sage: I = IntegerVectorsModPermutationGroup(G, sgs=sgs)\n sage: for i in range(10):\n ....: d1 = I.subset(i).cardinality()\n ....: d2 = IntegerVectors(i,6).cardinality()\n ....: print(d1)\n ....: assert d1 == d2\n 1\n 6\n 21\n 56\n 126\n 252\n 462\n 792\n 1287\n 2002\n\n "
@staticmethod
def __classcall__(cls, G, sum=None, max_part=None, sgs=None):
'\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]))\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), None)\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), 2)\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), -2)\n Traceback (most recent call last):\n ...\n ValueError: Value -2 in not in Non negative integer semiring.\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), 8, max_part=5)\n '
if ((sum is None) and (max_part is None)):
if G.domain():
return IntegerVectorsModPermutationGroup_All(G, sgs=sgs)
else:
return IntegerVectorsModPermutationGroup_with_constraints(G, 0, max_part=(- 1), sgs=sgs)
else:
if (sum is not None):
assert (sum == NN(sum))
if (max_part is not None):
assert (max_part == NN(max_part))
return IntegerVectorsModPermutationGroup_with_constraints(G, sum, max_part, sgs=sgs)
|
class IntegerVectorsModPermutationGroup_All(UniqueRepresentation, RecursivelyEnumeratedSet_forest):
'\n A class for integer vectors enumerated up to the action of a\n permutation group.\n\n A Sage permutation group is viewed as a subgroup of the symmetric\n group `S_n` for a certain `n`. This group has a natural action by\n position on vectors of length `n`. This class implements a set\n which keeps a single vector for each orbit. We say that a vector\n is canonical if it is the maximum in its orbit under the action of\n the permutation group for the lexicographic order.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]])); I\n Integer vectors of length 4 enumerated up to the action of\n Permutation Group with generators [(1,2,3,4)]\n sage: I.cardinality()\n +Infinity\n sage: TestSuite(I).run()\n sage: it = iter(I)\n sage: [next(it), next(it), next(it), next(it), next(it)]\n [[0, 0, 0, 0],\n [1, 0, 0, 0],\n [2, 0, 0, 0],\n [1, 1, 0, 0],\n [1, 0, 1, 0]]\n sage: x = next(it); x\n [3, 0, 0, 0]\n sage: I.first()\n [0, 0, 0, 0]\n\n TESTS::\n\n sage: TestSuite(I).run()\n '
def __init__(self, G, sgs=None):
'\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I\n Integer vectors of length 4 enumerated up to the action of\n Permutation Group with generators [(1,2,3,4)]\n sage: I.category()\n Category of infinite enumerated quotients of sets\n sage: TestSuite(I).run()\n '
RecursivelyEnumeratedSet_forest.__init__(self, algorithm='breadth', category=InfiniteEnumeratedSets().Quotients())
self._permgroup = G
self.n = G.degree()
if (sgs is None):
self._sgs = G.strong_generating_system()
else:
self._sgs = [list(x) for x in list(sgs)]
def _repr_(self):
'\n TESTS::\n\n sage: IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]))\n Integer vectors of length 3 enumerated up to the action of Permutation Group with generators [(1,2,3)]\n '
return ('Integer vectors of length %s enumerated up to the action of %r' % (self.n, self._permgroup))
def ambient(self):
'\n Return the ambient space from which ``self`` is a quotient.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: S.ambient()\n Integer vectors of length 4\n '
return IntegerVectors(length=self.n)
def lift(self, elt):
"\n Lift the element ``elt`` inside the ambient space from which ``self`` is a quotient.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: v = S.lift(S([4,3,0,1])); v\n [4, 3, 0, 1]\n sage: type(v)\n <class 'list'>\n "
return list(elt)
def retract(self, elt):
'\n Return the canonical representative of the orbit of the\n integer ``elt`` under the action of the permutation group\n defining ``self``.\n\n If the element ``elt`` is already maximal in its orbit for\n the lexicographic order, ``elt`` is thus the good\n representative for its orbit.\n\n EXAMPLES::\n\n sage: [0,0,0,0] in IntegerVectors(0,4)\n True\n sage: [1,0,0,0] in IntegerVectors(1,4)\n True\n sage: [0,1,0,0] in IntegerVectors(1,4)\n True\n sage: [1,0,1,0] in IntegerVectors(2,4)\n True\n sage: [0,1,0,1] in IntegerVectors(2,4)\n True\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: S.retract([0,0,0,0])\n [0, 0, 0, 0]\n sage: S.retract([1,0,0,0])\n [1, 0, 0, 0]\n sage: S.retract([0,1,0,0])\n [1, 0, 0, 0]\n sage: S.retract([1,0,1,0])\n [1, 0, 1, 0]\n sage: S.retract([0,1,0,1])\n [1, 0, 1, 0]\n '
assert (len(elt) == self.n), ('%s is a quotient set of %s' % (self, self.ambient()))
intarray = self.element_class(self, elt, check=False)
return self.element_class(self, canonical_representative_of_orbit_of(self._sgs, intarray), check=False)
def roots(self):
'\n Returns the root of generation of ``self``. This method is\n required to build the tree structure of ``self`` which\n inherits from the class :class:`~sage.sets.recursively_enumerated_set.RecursivelyEnumeratedSet_forest`.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.roots()\n [[0, 0, 0, 0]]\n '
return [self.element_class(self, (self.n * [0]), check=False)]
def children(self, x):
'\n Returns the list of children of the element ``x``. This method\n is required to build the tree structure of ``self`` which\n inherits from the class :class:`~sage.sets.recursively_enumerated_set.RecursivelyEnumeratedSet_forest`.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.children(I([2,1,0,0], check=False))\n [[2, 2, 0, 0], [2, 1, 1, 0], [2, 1, 0, 1]]\n '
return canonical_children(self._sgs, x, (- 1))
def permutation_group(self):
'\n Returns the permutation group given to define ``self``.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.permutation_group()\n Permutation Group with generators [(1,2,3,4)]\n '
return self._permgroup
def is_canonical(self, v, check=True):
'\n Returns ``True`` if the integer list ``v`` is maximal in its\n orbit under the action of the permutation group given to\n define ``self``. Such integer vectors are said to be\n canonical. A vector `v` is canonical if and only if\n\n .. MATH::\n\n v = \\max_{\\text{lex order}} \\{g \\cdot v | g \\in G \\}\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.is_canonical([4,3,2,1])\n True\n sage: I.is_canonical([4,0,0,1])\n True\n sage: I.is_canonical([4,0,3,3])\n True\n sage: I.is_canonical([4,0,4,4])\n False\n '
if check:
assert isinstance(v, (ClonableIntArray, list)), ('%s should be a list or an integer vector' % v)
assert (self.n == len(v)), ('%s should be of length %s' % (v, self.n))
for p in v:
assert (p == NN(p)), ('Elements of %s should be integers' % v)
return is_canonical(self._sgs, self.element_class(self, list(v), check=False))
def __contains__(self, v):
'\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: [2,2,0,0] in I\n True\n sage: [2,0,1,0] in I\n True\n sage: [2,0,0,1] in I\n True\n sage: [2,0,0,2] in I\n False\n sage: [2,0,0,2,12] in I\n False\n '
try:
return self.is_canonical(self.element_class(self, list(v), check=False), check=False)
except Exception:
return False
def __call__(self, v, check=True):
'\n Returns an element of ``self`` constructed from ``v`` if\n possible.\n\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I([3,2,1,0])\n [3, 2, 1, 0]\n '
try:
if (v.parent() is self):
return v
else:
raise ValueError(('%s should be a Python list of integer' % v))
except Exception:
return self.element_class(self, list(v), check=check)
def orbit(self, v):
'\n Returns the orbit of the integer vector ``v`` under the action of the\n permutation group defining ``self``. The result is a set.\n\n EXAMPLES:\n\n In order to get reproducible doctests, we convert the returned sets\n into lists in increasing lexicographic order::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: sorted(I.orbit([2,2,0,0]))\n [[0, 0, 2, 2], [0, 2, 2, 0], [2, 0, 0, 2], [2, 2, 0, 0]]\n sage: sorted(I.orbit([2,1,0,0]))\n [[0, 0, 2, 1], [0, 2, 1, 0], [1, 0, 0, 2], [2, 1, 0, 0]]\n sage: sorted(I.orbit([2,0,1,0]))\n [[0, 1, 0, 2], [0, 2, 0, 1], [1, 0, 2, 0], [2, 0, 1, 0]]\n sage: sorted(I.orbit([2,0,2,0]))\n [[0, 2, 0, 2], [2, 0, 2, 0]]\n sage: I.orbit([1,1,1,1])\n {[1, 1, 1, 1]}\n '
assert isinstance(v, (list, ClonableIntArray)), ('%s should be a Python list or an element of %s' % (v, self))
try:
if (v.parent() is self):
return orbit(self._sgs, v)
raise TypeError
except Exception:
return orbit(self._sgs, self.element_class(self, v, check=False))
def subset(self, sum=None, max_part=None):
'\n Returns the subset of ``self`` containing integer vectors\n whose entries sum to ``sum``.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: S.subset(4)\n Integer vectors of length 4 and of sum 4 enumerated up to\n the action of Permutation Group with generators\n [(1,2,3,4)]\n '
return IntegerVectorsModPermutationGroup_with_constraints(self.permutation_group(), sum, max_part)
class Element(ClonableIntArray):
'\n Element class for the set of integer vectors of given sum enumerated modulo\n the action of a permutation group. These vectors are clonable lists of integers\n which must satisfy conditions coming from the parent appearing in the method\n :meth:`~sage.structure.list_clone.ClonableIntArray.check`.\n\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: v = I.element_class(I, [4,3,2,1]); v\n [4, 3, 2, 1]\n sage: TestSuite(v).run()\n sage: I.element_class(I, [4,3,2,5])\n Traceback (most recent call last):\n ...\n AssertionError\n '
def check(self):
'\n Checks that ``self`` verify the invariants needed for\n living in ``self.parent()``.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: v = I.an_element()\n sage: v.check()\n sage: w = I([0,4,0,0], check=False); w\n [0, 4, 0, 0]\n sage: w.check()\n Traceback (most recent call last):\n ...\n AssertionError\n '
assert self.parent().is_canonical(self)
|
class IntegerVectorsModPermutationGroup_with_constraints(UniqueRepresentation, RecursivelyEnumeratedSet_forest):
'\n This class models finite enumerated sets of integer vectors with\n constraint enumerated up to the action of a permutation group.\n Integer vectors are enumerated modulo the action of the\n permutation group. To implement that, we keep a single integer\n vector by orbit under the action of the permutation\n group. Elements chosen are vectors maximal in their orbit for the\n lexicographic order.\n\n For more information see :class:`IntegerVectorsModPermutationGroup`.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: max_part=1)\n sage: I.list()\n [[0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 0],\n [1, 1, 1, 1]]\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=6, max_part=4)\n sage: I.list()\n [[4, 2, 0, 0], [4, 1, 1, 0], [4, 1, 0, 1], [4, 0, 2, 0], [4, 0, 1, 1],\n [4, 0, 0, 2], [3, 3, 0, 0], [3, 2, 1, 0], [3, 2, 0, 1], [3, 1, 2, 0],\n [3, 1, 1, 1], [3, 1, 0, 2], [3, 0, 3, 0], [3, 0, 2, 1], [3, 0, 1, 2],\n [2, 2, 2, 0], [2, 2, 1, 1], [2, 1, 2, 1]]\n\n Here is the enumeration of unlabeled graphs over 5 vertices::\n\n sage: G = IntegerVectorsModPermutationGroup(TransitiveGroup(10,12), max_part=1)\n sage: G.cardinality()\n 34\n\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),4)\n sage: TestSuite(I).run()\n '
def __init__(self, G, d, max_part, sgs=None):
'\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 6, max_part=4)\n '
RecursivelyEnumeratedSet_forest.__init__(self, algorithm='breadth', category=(FiniteEnumeratedSets(), FiniteEnumeratedSets().Quotients()))
self._permgroup = G
self.n = G.degree()
self._sum = d
if (max_part is None):
self._max_part = (- 1)
else:
self._max_part = max_part
if (sgs is None):
self._sgs = G.strong_generating_system()
else:
self._sgs = [list(x) for x in list(sgs)]
def _repr_(self):
'\n TESTS::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]])); S\n Integer vectors of length 4 enumerated up to the action of Permutation Group with generators [(1,2,3,4)]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 6); S\n Integer vectors of length 4 and of sum 6 enumerated up to the action of Permutation Group with generators [(1,2,3,4)]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 6, max_part=4); S\n Vectors of length 4 and of sum 6 whose entries are in {0, ..., 4} enumerated up to the action of Permutation Group with generators [(1,2,3,4)]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), max_part=4); S\n Integer vectors of length 4 whose entries are in {0, ..., 4} enumerated up to the action of Permutation Group with generators [(1,2,3,4)]\n '
if (self._sum is not None):
if (self._max_part >= 0):
return ('Vectors of length %s and of sum %s whose entries are in {0, ..., %s} enumerated up to the action of %s' % (self.n, self._sum, self._max_part, self.permutation_group()))
else:
return ('Integer vectors of length %s and of sum %s enumerated up to the action of %s' % (self.n, self._sum, self.permutation_group()))
else:
return ('Integer vectors of length %s whose entries are in {0, ..., %s} enumerated up to the action of %s' % (self.n, self._max_part, self.permutation_group()))
def roots(self):
'\n Return the root of generation of ``self``.\n\n This method is\n required to build the tree structure of ``self`` which\n inherits from the class\n :class:`~sage.sets.recursively_enumerated_set.RecursivelyEnumeratedSet_forest`.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.roots()\n [[0, 0, 0, 0]]\n '
return [self.element_class(self, (self.n * [0]), check=False)]
def children(self, x):
'\n Return the list of children of the element ``x``.\n\n This method\n is required to build the tree structure of ``self`` which\n inherits from the class\n :class:`~sage.sets.recursively_enumerated_set.RecursivelyEnumeratedSet_forest`.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]))\n sage: I.children(I([2,1,0,0], check=False))\n [[2, 2, 0, 0], [2, 1, 1, 0], [2, 1, 0, 1]]\n '
return canonical_children(self._sgs, x, (- 1))
def permutation_group(self):
'\n Return the permutation group given to define ``self``.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3)]]), 5)\n sage: I.permutation_group()\n Permutation Group with generators [(1,2,3)]\n '
return self._permgroup
def __contains__(self, v):
'\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),6)\n sage: [6,0,0,0] in I\n True\n sage: [5,0,1,0] in I\n True\n sage: [0,5,1,0] in I\n False\n sage: [3,0,1,3] in I\n False\n sage: [3,3,1,0] in I\n False\n '
try:
return (self(v).parent() is self)
except Exception:
return False
def __call__(self, v, check=True):
'\n Make `v` an element living in ``self``.\n\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 4)\n sage: v = I([2,1,0,1]); v\n [2, 1, 0, 1]\n sage: v.parent()\n Integer vectors of length 4 and of sum 4 enumerated up to\n the action of Permutation Group with generators\n [(1,2,3,4)]\n '
try:
if (v.parent() is self):
return v
else:
raise ValueError(('%s should be a Python list of integer' % v))
except Exception:
return self.element_class(self, list(v), check=check)
def __iter__(self):
'\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),4)\n sage: for i in I: i\n [4, 0, 0, 0]\n [3, 1, 0, 0]\n [3, 0, 1, 0]\n [3, 0, 0, 1]\n [2, 2, 0, 0]\n [2, 1, 1, 0]\n [2, 1, 0, 1]\n [2, 0, 2, 0]\n [2, 0, 1, 1]\n [1, 1, 1, 1]\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), sum=7, max_part=3)\n sage: for i in I: i\n [3, 3, 1, 0]\n [3, 3, 0, 1]\n [3, 2, 2, 0]\n [3, 2, 1, 1]\n [3, 2, 0, 2]\n [3, 1, 3, 0]\n [3, 1, 2, 1]\n [3, 1, 1, 2]\n [3, 0, 2, 2]\n [2, 2, 2, 1]\n\n Check that :issue:`36681` is fixed::\n\n sage: G = PermutationGroup([], domain=[])\n sage: I = IntegerVectorsModPermutationGroup(G, sum=0)\n sage: list(iter(I))\n [[]]\n\n Check that :issue:`36681` is fixed::\n\n sage: G = PermutationGroup([], domain=[])\n sage: I = IntegerVectorsModPermutationGroup(G, sum=3)\n sage: list(iter(I))\n []\n\n '
if (self.n == 0):
if ((self._sum is not None) and (self._sum > 0)):
return iter(())
else:
return iter([self([])])
if (self._max_part < 0):
return self.elements_of_depth_iterator(self._sum)
else:
SF = RecursivelyEnumeratedSet_forest((self(([0] * self.n), check=False),), (lambda x: [self(y, check=False) for y in canonical_children(self._sgs, x, self._max_part)]), algorithm='breadth')
if (self._sum is None):
return iter(SF)
else:
return SF.elements_of_depth_iterator(self._sum)
def cardinality(self):
'\n Return the number of integer vectors in the set.\n\n The algorithm utilises :wikipedia:`Cycle Index Theorem <Cycle_index>`, allowing\n for a faster than a plain enumeration computation.\n\n EXAMPLES:\n\n With a trivial group all vectors are canonical::\n\n sage: G = PermutationGroup([], domain=[1,2,3])\n sage: IntegerVectorsModPermutationGroup(G, 5).cardinality()\n 21\n sage: IntegerVectors(5, 3).cardinality()\n 21\n\n With two interchangeable elements, the smaller one\n ranges from zero to ``sum//2``::\n\n sage: G = PermutationGroup([(1,2)])\n sage: IntegerVectorsModPermutationGroup(G, 1000).cardinality()\n 501\n\n Binary vectors up to full symmetry are first some ones and\n then some zeros::\n\n sage: G = SymmetricGroup(10)\n sage: I = IntegerVectorsModPermutationGroup(G, max_part=1)\n sage: I.cardinality()\n 11\n\n Binary vectors of constant weight, up to PGL(2,17), which\n is 3-transitive, but not 4-transitive::\n\n sage: G=PGL(2,17)\n sage: I = IntegerVectorsModPermutationGroup(G, sum=3, max_part=1)\n sage: I.cardinality()\n 1\n sage: I = IntegerVectorsModPermutationGroup(G, sum=4, max_part=1)\n sage: I.cardinality()\n 3\n\n TESTS:\n\n Check that :issue:`36681` is fixed::\n\n sage: G = PermutationGroup([], domain=[])\n sage: sgs = tuple(tuple(t) for t in G.strong_generating_system())\n sage: V = IntegerVectorsModPermutationGroup(G, sum=1, sgs=sgs)\n sage: V.cardinality()\n 0\n\n The case when both ``sum`` and ``max_part`` are specified::\n\n sage: G = PermutationGroup([(1,2,3)])\n sage: I = IntegerVectorsModPermutationGroup(G, sum=10, max_part=5)\n sage: I.cardinality()\n 7\n\n All permutation groups of degree 4::\n\n sage: for G in SymmetricGroup(4).subgroups():\n ....: sgs = tuple(tuple(t) for t in G.strong_generating_system())\n ....: I1 = IntegerVectorsModPermutationGroup(G, sum=10, sgs=sgs)\n ....: assert I1.cardinality() == len(list(I1))\n ....: I2 = IntegerVectorsModPermutationGroup(G, max_part=3, sgs=sgs)\n ....: assert I2.cardinality() == len(list(I2))\n ....: I3 = IntegerVectorsModPermutationGroup(G, sum=10, max_part=3, sgs=sgs)\n ....: assert I3.cardinality() == len(list(I3))\n\n Symmetric group with sums 0 and 1::\n\n sage: S10 = SymmetricGroup(10)\n sage: IntegerVectorsModPermutationGroup(S10, 0).cardinality()\n 1\n sage: IntegerVectorsModPermutationGroup(S10, 1).cardinality()\n 1\n\n Trivial group with sums 1 and 100::\n\n sage: T10 = PermutationGroup([], domain=range(1, 11))\n sage: IntegerVectorsModPermutationGroup(T10, 1).cardinality()\n 10\n sage: IntegerVectorsModPermutationGroup(T10, 100).cardinality()\n 4263421511271\n\n '
G = self._permgroup
k = G.degree()
d = self._sum
m = self._max_part
if (m == (- 1)):
m = d
if (k == 0):
if ((d == 0) or (d is None)):
return Integer(1)
else:
return Integer(0)
if ((d == 0) or (m == 0)):
return Integer(1)
if (d == 1):
return Integer(len(G.orbits()))
if ((d is not None) and (m >= d) and G.is_trivial()):
return Integer(binomial(((d + k) - 1), (k - 1)))
Z = G.cycle_index()
if (d is None):
result = sum(((coeff * ((m + 1) ** len(cycle_type))) for (cycle_type, coeff) in Z))
return Integer(result)
R = PowerSeriesRing(QQ, 'x', default_prec=(d + 1))
x = R.gen()
funcount = sum(((coeff * prod((((1 - (x ** ((m + 1) * cycle_len))) / (1 - (x ** cycle_len))) for cycle_len in cycle_type))) for (cycle_type, coeff) in Z))
return Integer(funcount[d])
def is_canonical(self, v, check=True):
'\n Return ``True`` if the integer list ``v`` is maximal in its\n orbit under the action of the permutation group given to\n define ``self``. Such integer vectors are said to be\n canonical. A vector `v` is canonical if and only if\n\n .. MATH::\n\n v = \\max_{\\text{lex order}} \\{g \\cdot v | g \\in G \\}\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: max_part=3)\n sage: I.is_canonical([3,0,0,0])\n True\n sage: I.is_canonical([1,0,2,0])\n False\n sage: I.is_canonical([2,0,1,0])\n True\n '
if check:
assert isinstance(v, (ClonableIntArray, list)), ('%s should be a list or an integer vector' % v)
assert (self.n == len(v)), ('%s should be of length %s' % (v, self.n))
for p in v:
assert (p == NN(p)), ('Elements of %s should be integers' % v)
return is_canonical(self._sgs, self.element_class(self, list(v), check=False))
def ambient(self):
'\n Return the ambient space from which ``self`` is a quotient.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 6)\n sage: S.ambient()\n Integer vectors that sum to 6\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: 6, max_part=12)\n sage: S.ambient()\n Integer vectors that sum to 6 with constraints: max_part=12\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: max_part=12)\n sage: S.ambient()\n Integer vectors with constraints: max_part=12\n '
if (self._sum is not None):
if (self._max_part <= (- 1)):
return IntegerVectors(n=self._sum)
else:
return IntegerVectors(n=self._sum, max_part=self._max_part)
else:
return IntegerVectors(max_part=self._max_part)
def lift(self, elt):
'\n Lift the element ``elt`` inside the ambient space from which ``self`` is a quotient.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: max_part=1)\n sage: v = S.lift([1,0,1,0]); v\n [1, 0, 1, 0]\n sage: v in IntegerVectors(2,4,max_part=1)\n True\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=6)\n sage: v = S.lift(S.list()[5]); v\n [4, 1, 1, 0]\n sage: v in IntegerVectors(n=6)\n True\n '
return list(elt)
def retract(self, elt):
'\n Return the canonical representative of the orbit of the\n integer ``elt`` under the action of the permutation group\n defining ``self``.\n\n If the element ``elt`` is already maximal in its orbits for\n the lexicographic order, ``elt`` is thus the good\n representative for its orbit.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=2, max_part=1)\n sage: S.retract([1,1,0,0])\n [1, 1, 0, 0]\n sage: S.retract([1,0,1,0])\n [1, 0, 1, 0]\n sage: S.retract([1,0,0,1])\n [1, 1, 0, 0]\n sage: S.retract([0,1,1,0])\n [1, 1, 0, 0]\n sage: S.retract([0,1,0,1])\n [1, 0, 1, 0]\n sage: S.retract([0,0,1,1])\n [1, 1, 0, 0]\n '
assert (len(elt) == self.n), ('%s is a quotient set of %s' % (self, self.ambient()))
if (self._sum is not None):
assert (sum(elt) == self._sum), ('%s is a quotient set of %s' % (self, self.ambient()))
if (self._max_part >= 0):
assert (max(elt) <= self._max_part), ('%s is a quotient set of %s' % (self, self.ambient()))
intarray = self.element_class(self, elt, check=False)
return self.element_class(self, canonical_representative_of_orbit_of(self._sgs, intarray), check=False)
def an_element(self):
'\n Return an element of ``self``.\n\n Raises an :class:`EmptySetError` when ``self`` is empty.\n\n EXAMPLES::\n\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=0, max_part=1)\n sage: S.an_element()\n [0, 0, 0, 0]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=1, max_part=1)\n sage: S.an_element()\n [1, 0, 0, 0]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=2, max_part=1)\n sage: S.an_element()\n [1, 1, 0, 0]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=3, max_part=1)\n sage: S.an_element()\n [1, 1, 1, 0]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=4, max_part=1)\n sage: S.an_element()\n [1, 1, 1, 1]\n sage: S = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]),\n ....: sum=5, max_part=1)\n sage: S.an_element()\n Traceback (most recent call last):\n ...\n EmptySetError\n '
if (self._max_part < 0):
return self(([self._sum] + ((self.n - 1) * [0])), check=False)
else:
try:
v = iter(self)
return next(v)
except StopIteration:
from sage.categories.sets_cat import EmptySetError
raise EmptySetError
def orbit(self, v):
'\n Return the orbit of the vector ``v`` under the action of the\n permutation group defining ``self``. The result is a set.\n\n INPUT:\n\n - ``v`` -- an element of ``self`` or any list of length the\n degree of the permutation group.\n\n EXAMPLES:\n\n We convert the result in a list in increasing lexicographic\n order, to get a reproducible doctest::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 4)\n sage: I.orbit([1,1,1,1])\n {[1, 1, 1, 1]}\n sage: sorted(I.orbit([3,0,0,1]))\n [[0, 0, 1, 3], [0, 1, 3, 0], [1, 3, 0, 0], [3, 0, 0, 1]]\n '
assert isinstance(v, (list, ClonableIntArray)), ('%s should be a Python list or an element of %s' % (v, self))
try:
if (v.parent() is self):
return orbit(self._sgs, v)
except Exception:
return orbit(self._sgs, self.element_class(self, v, check=False))
class Element(ClonableIntArray):
'\n Element class for the set of integer vectors with constraints enumerated\n modulo the action of a permutation group. These vectors are clonable lists\n of integers which must satisfy conditions coming from the parent as in\n the method :meth:`~sage.combinat.integer_vectors_mod_permgroup.IntegerVectorsModPermutationGroup_with_constraints.Element.check`.\n\n TESTS::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 4)\n sage: v = I.element_class(I, [3,1,0,0]); v\n [3, 1, 0, 0]\n sage: TestSuite(v).run()\n sage: v = I.element_class(I, [3,2,0,0])\n Traceback (most recent call last):\n ...\n AssertionError: [3, 2, 0, 0] should be an integer vector of sum 4\n '
def check(self):
'\n Check that ``self`` meets the constraints of being an element of ``self.parent()``.\n\n EXAMPLES::\n\n sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 4)\n sage: v = I.an_element()\n sage: v.check()\n sage: w = I([0,4,0,0], check=False); w\n [0, 4, 0, 0]\n sage: w.check()\n Traceback (most recent call last):\n ...\n AssertionError\n '
if (self.parent()._sum is not None):
assert (sum(self) == self.parent()._sum), ('%s should be an integer vector of sum %s' % (self, self.parent()._sum))
if (self.parent()._max_part >= 0):
assert (max(self) <= self.parent()._max_part), ('Entries of %s must be inferior to %s' % (self, self.parent()._max_part))
assert self.parent().is_canonical(self)
|
class TamariIntervalPoset(Element, metaclass=InheritComparisonClasscallMetaclass):
'\n The class of Tamari interval-posets.\n\n An interval-poset is a labelled poset of size `n`, with labels\n `1, 2, \\ldots, n`, satisfying the following conditions:\n\n - if `a < c` (as integers) and `a` precedes `c` in the poset, then,\n for all `b` such that `a < b < c`, `b` precedes `c`,\n\n - if `a < c` (as integers) and `c` precedes `a` in the poset, then,\n for all `b` such that `a < b < c`, `b` precedes `a`.\n\n We use the word "precedes" here to distinguish the poset order and\n the natural order on numbers. "Precedes" means "is smaller than\n with respect to the poset structure"; this does not imply a\n covering relation.\n\n Interval-posets of size `n` are in bijection with intervals of\n the Tamari lattice of binary trees of size `n`. Specifically, if\n `P` is an interval-poset of size `n`, then the set of linear\n extensions of `P` (as permutations in `S_n`) is an interval in the\n right weak order (see\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`),\n and is in fact the preimage of an interval in the Tamari lattice (of\n binary trees of size `n`) under the operation which sends a\n permutation to its right-to-left binary search tree\n (:meth:`~sage.combinat.permutation.Permutation.binary_search_tree`\n with the ``left_to_right`` variable set to ``False``)\n without its labelling.\n\n INPUT:\n\n - ``size`` -- an integer, the size of the interval-posets (number of\n vertices)\n\n - ``relations`` -- a list (or tuple) of pairs ``(a,b)`` (themselves\n lists or tuples), each representing a relation of the form\n \'`a` precedes `b`\' in the poset.\n\n - ``check`` -- (default: ``True``) whether to check the interval-poset\n condition or not.\n\n .. WARNING::\n\n The ``relations`` input can be a list or tuple, but not an\n iterator (nor should its entries be iterators).\n\n NOTATION:\n\n Here and in the following, the signs `<` and `>` always refer to\n the natural ordering on integers, whereas the word "precedes" refers\n to the order of the interval-poset. "Minimal" and "maximal" refer\n to the natural ordering on integers.\n\n The *increasing relations* of an interval-poset `P` mean the pairs\n `(a, b)` of elements of `P` such that `a < b` as integers and `a`\n precedes `b` in `P`. The *initial forest* of `P` is the poset\n obtained by imposing (only) the increasing relations on the ground\n set of `P`. It is a sub-interval poset of `P`, and is a forest with\n its roots on top. This forest is usually given the structure of a\n planar forest by ordering brother nodes by their labels; it then has\n the property that if its nodes are traversed in post-order\n (see :meth:`~sage.combinat.abstract_tree.AbstractTree.post_order_traversal`,\n and traverse the trees of the forest from left to right as well),\n then the labels encountered are `1, 2, \\ldots, n` in this order.\n\n The *decreasing relations* of an interval-poset `P` mean the pairs\n `(a, b)` of elements of `P` such that `b < a` as integers and `a`\n precedes `b` in `P`. The *final forest* of `P` is the poset\n obtained by imposing (only) the decreasing relations on the ground\n set of `P`. It is a sub-interval poset of `P`, and is a forest with\n its roots on top. This forest is usually given the structure of a\n planar forest by ordering brother nodes by their labels; it then has\n the property that if its nodes are traversed in pre-order\n (see :meth:`~sage.combinat.abstract_tree.AbstractTree.pre_order_traversal`,\n and traverse the trees of the forest from left to right as well),\n then the labels encountered are `1, 2, \\ldots, n` in this order.\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(0,[])\n The Tamari interval of size 0 induced by relations []\n sage: TamariIntervalPoset(3,[])\n The Tamari interval of size 3 induced by relations []\n sage: TamariIntervalPoset(3,[(1,2)])\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: TamariIntervalPoset(3,[(1,2),(2,3)])\n The Tamari interval of size 3 induced by relations [(1, 2), (2, 3)]\n sage: TamariIntervalPoset(3,[(1,2),(2,3),(1,3)])\n The Tamari interval of size 3 induced by relations [(1, 2), (2, 3)]\n sage: TamariIntervalPoset(3,[(1,2),(3,2)])\n The Tamari interval of size 3 induced by relations [(1, 2), (3, 2)]\n sage: TamariIntervalPoset(3,[[1,2],[2,3]])\n The Tamari interval of size 3 induced by relations [(1, 2), (2, 3)]\n sage: TamariIntervalPoset(3,[[1,2],[2,3],[1,2],[1,3]])\n The Tamari interval of size 3 induced by relations [(1, 2), (2, 3)]\n\n sage: TamariIntervalPoset(3,[(3,4)])\n Traceback (most recent call last):\n ...\n ValueError: the relations do not correspond to the size of the poset\n\n sage: TamariIntervalPoset(2,[(2,1),(1,2)])\n Traceback (most recent call last):\n ...\n ValueError: The graph is not directed acyclic\n\n sage: TamariIntervalPoset(3,[(1,3)])\n Traceback (most recent call last):\n ...\n ValueError: this does not satisfy the Tamari interval-poset condition\n\n It is also possible to transform a poset directly into an interval-poset::\n\n sage: TIP = TamariIntervalPosets()\n sage: p = Poset(([1,2,3], [(1,2)]))\n sage: TIP(p)\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: TIP(Poset({1: []}))\n The Tamari interval of size 1 induced by relations []\n sage: TIP(Poset({}))\n The Tamari interval of size 0 induced by relations []\n '
@staticmethod
def __classcall_private__(cls, *args, **opts) -> TIP:
"\n Ensure that interval-posets created by the enumerated sets and\n directly are the same and that they are instances of\n :class:`TamariIntervalPoset`.\n\n TESTS::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.parent()\n Interval-posets\n sage: type(ip)\n <class 'sage.combinat.interval_posets.TamariIntervalPosets_all_with_category.element_class'>\n\n sage: ip2 = TamariIntervalPosets()(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip2.parent() is ip.parent()\n True\n sage: type(ip) is type(ip2)\n True\n\n sage: ip3 = TamariIntervalPosets(4)([(2,4),(3,4),(2,1),(3,1)])\n sage: ip3.parent() is ip.parent()\n False\n sage: type(ip3) is type(ip)\n True\n "
P = TamariIntervalPosets_all()
return P.element_class(P, *args, **opts)
def __init__(self, parent, size, relations=None, check=True):
'\n TESTS::\n\n sage: TamariIntervalPoset(3,[(1,2),(3,2)]).parent()\n Interval-posets\n sage: P = Poset(DiGraph([(4,1),(3,1),(2,1)]))\n sage: TamariIntervalPoset(P).parent()\n Interval-posets\n '
if (relations is None):
relations = []
if isinstance(size, FinitePoset):
self._poset = size
self._size = size.cardinality()
else:
self._size = size
self._poset = Poset((list(range(1, (size + 1))), relations))
if (self._poset.cardinality() != size):
raise ValueError('the relations do not correspond to the size of the poset')
if (check and (not TamariIntervalPosets.check_poset(self._poset))):
raise ValueError('this does not satisfy the Tamari interval-poset condition')
Element.__init__(self, parent)
self._cover_relations = tuple(self._poset.cover_relations())
self._latex_options = {}
def set_latex_options(self, D):
'\n Set the latex options for use in the ``_latex_`` function.\n\n The default values are set in the ``__init__`` function.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package\n\n - ``line_width`` -- (default: 1 * ``tikz_scale``) value representing the\n line width\n\n - ``color_decreasing`` -- (default: red) the color for decreasing\n relations\n\n - ``color_increasing`` -- (default: blue) the color for increasing\n relations\n\n - ``hspace`` -- (default: 1) the difference between horizontal\n coordinates of adjacent vertices\n\n - ``vspace`` -- (default: 1) the difference between vertical\n coordinates of adjacent vertices\n\n INPUT:\n\n - ``D`` -- a dictionary with a list of latex parameters to change\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.latex_options()["color_decreasing"]\n \'red\'\n sage: ip.set_latex_options({"color_decreasing":\'green\'})\n sage: ip.latex_options()["color_decreasing"]\n \'green\'\n sage: ip.set_latex_options({"color_increasing":\'black\'})\n sage: ip.latex_options()["color_increasing"]\n \'black\'\n\n To change the default options for all interval-posets, use the\n parent\'s latex options::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip2 = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.latex_options()["color_decreasing"]\n \'red\'\n sage: ip2.latex_options()["color_decreasing"]\n \'red\'\n sage: TamariIntervalPosets.options(latex_color_decreasing=\'green\')\n sage: ip.latex_options()["color_decreasing"]\n \'green\'\n sage: ip2.latex_options()["color_decreasing"]\n \'green\'\n\n Next we set a local latex option and show the global option does not\n override it::\n\n sage: ip.set_latex_options({"color_decreasing": \'black\'})\n sage: ip.latex_options()["color_decreasing"]\n \'black\'\n sage: TamariIntervalPosets.options(latex_color_decreasing=\'blue\')\n sage: ip.latex_options()["color_decreasing"]\n \'black\'\n sage: ip2.latex_options()["color_decreasing"]\n \'blue\'\n sage: TamariIntervalPosets.options._reset()\n '
for opt in D:
self._latex_options[opt] = D[opt]
def latex_options(self) -> dict:
"\n Return the latex options for use in the ``_latex_`` function as a\n dictionary.\n\n The default values are set using the options.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package\n\n - ``line_width`` -- (default: 1) value representing the line width\n (additionally scaled by ``tikz_scale``)\n\n - ``color_decreasing`` -- (default: ``'red'``) the color for\n decreasing relations\n\n - ``color_increasing`` -- (default: ``'blue'``) the color for\n increasing relations\n\n - ``hspace`` -- (default: 1) the difference between horizontal\n coordinates of adjacent vertices\n\n - ``vspace`` -- (default: 1) the difference between vertical\n coordinates of adjacent vertices\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.latex_options()['color_decreasing']\n 'red'\n sage: ip.latex_options()['hspace']\n 1\n "
d = self._latex_options.copy()
if ('tikz_scale' not in d):
d['tikz_scale'] = self.parent().options['latex_tikz_scale']
if ('line_width' not in d):
d['line_width'] = (self.parent().options['latex_line_width_scalar'] * d['tikz_scale'])
if ('color_decreasing' not in d):
d['color_decreasing'] = self.parent().options['latex_color_decreasing']
if ('color_increasing' not in d):
d['color_increasing'] = self.parent().options['latex_color_increasing']
if ('hspace' not in d):
d['hspace'] = self.parent().options['latex_hspace']
if ('vspace' not in d):
d['vspace'] = self.parent().options['latex_vspace']
return d
def _find_node_positions(self, hspace=1, vspace=1) -> dict[(int, list)]:
'\n Compute a nice embedding.\n\n If `x` precedes `y`, then `y` will always be placed on top of `x`\n and/or to the right of `x`.\n Decreasing relations tend to be drawn vertically and increasing\n relations horizontally.\n The algorithm tries to avoid superposition but on big\n interval-posets, it might happen.\n\n OUTPUT:\n\n a dictionary {vertex: (x,y)}\n\n EXAMPLES::\n\n sage: ti = TamariIntervalPosets(4)[2]\n sage: list(ti._find_node_positions().values())\n [[0, 0], [0, -1], [0, -2], [1, -2]]\n '
node_positions = {}
to_draw = [(1, 0)]
current_parent = [self.increasing_parent(1)]
parenty = [0]
x = 0
y = 0
for i in range(2, (self.size() + 1)):
decreasing_parent = self.decreasing_parent(i)
increasing_parent = self.increasing_parent(i)
while (to_draw and ((decreasing_parent is None) or (decreasing_parent < to_draw[(- 1)][0]))):
n = to_draw.pop()
node_positions[n[0]] = [x, n[1]]
if (i != current_parent[(- 1)]):
if ((not self.le(i, (i - 1))) and (decreasing_parent is not None)):
x += hspace
if (current_parent[(- 1)] is not None):
y -= vspace
else:
y -= vspace
if (increasing_parent != current_parent[(- 1)]):
current_parent.append(increasing_parent)
parenty.append(y)
nodey = y
else:
current_parent.pop()
x += hspace
nodey = parenty.pop()
if ((not current_parent) or (increasing_parent != current_parent[(- 1)])):
current_parent.append(increasing_parent)
parenty.append(nodey)
to_draw.append((i, nodey))
for n in to_draw:
node_positions[n[0]] = [x, n[1]]
return node_positions
def plot(self, **kwds):
'\n Return a picture.\n\n The picture represents the Hasse diagram, where the covers are\n colored in blue if they are increasing and in red if they are\n decreasing.\n\n This uses the same coordinates as the latex view.\n\n EXAMPLES::\n\n sage: ti = TamariIntervalPosets(4)[2]\n sage: ti.plot() # needs sage.plot\n Graphics object consisting of 6 graphics primitives\n\n TESTS::\n\n sage: ti = TamariIntervalPoset(3, [[2,1], [2,3]])\n sage: ti.plot() # needs sage.plot\n Graphics object consisting of 6 graphics primitives\n '
c0 = 'blue'
c1 = 'red'
G = self.poset().hasse_diagram()
G.set_pos(self._find_node_positions())
for (a, b) in G.edges(sort=False, labels=False):
if (a < b):
G.set_edge_label(a, b, 0)
else:
G.set_edge_label(a, b, 1)
return G.plot(color_by_label={0: c0, 1: c1}, **kwds)
def _latex_(self) -> str:
"\n A latex representation of ``self`` using the tikzpicture package.\n\n This picture shows the union of the Hasse diagrams of the\n initial and final forests.\n\n If `x` precedes `y`, then `y` will always be placed on top of `x`\n and/or to the right of `x`.\n Decreasing relations tend to be drawn vertically and increasing\n relations horizontally.\n The algorithm tries to avoid superposition but on big\n interval-posets, it might happen.\n\n You can use ``self.set_latex_options()`` to change default latex\n options. Or you can use the parent's options.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: latex(ip)\n \\begin{tikzpicture}[scale=1]\n \\node(T1) at (1,0) {1};\n \\node(T2) at (0,-1) {2};\n \\node(T3) at (1,-2) {3};\n \\node(T4) at (2,-1) {4};\n \\draw[line width = 0.5, color=red] (T3) -- (T1);\n \\draw[line width = 0.5, color=red] (T2) -- (T1);\n \\draw[line width = 0.5, color=blue] (T2) -- (T4);\n \\draw[line width = 0.5, color=blue] (T3) -- (T4);\n \\end{tikzpicture}\n\n TESTS::\n\n sage: ip = TamariIntervalPoset(0,[])\n sage: latex(ip)\n \\begin{tikzpicture}[scale=1]\n \\node(T0) at (0,0){$\\emptyset$};\\end{tikzpicture}\n "
latex.add_package_to_preamble_if_available('tikz')
latex_options = self.latex_options()
start = (('\\begin{tikzpicture}[scale=' + str(latex_options['tikz_scale'])) + ']\n')
end = '\\end{tikzpicture}'
vspace = latex_options['vspace']
hspace = latex_options['hspace']
def draw_node(j, x, y) -> str:
'\n Internal method to draw vertices\n '
return (((((((('\\node(T' + str(j)) + ') at (') + str(x)) + ',') + str(y)) + ') {') + str(j)) + '};\n')
def draw_increasing(i, j) -> str:
'\n Internal method to draw increasing relations\n '
return (((((((('\\draw[line width = ' + str(latex_options['line_width'])) + ', color=') + latex_options['color_increasing']) + '] (T') + str(i)) + ') -- (T') + str(j)) + ');\n')
def draw_decreasing(i, j) -> str:
'\n Internal method to draw decreasing relations\n '
return (((((((('\\draw[line width = ' + str(latex_options['line_width'])) + ', color=') + latex_options['color_decreasing']) + '] (T') + str(i)) + ') -- (T') + str(j)) + ');\n')
if (self.size() == 0):
nodes = '\\node(T0) at (0,0){$\\emptyset$};'
relations = ''
else:
positions = self._find_node_positions(hspace, vspace)
nodes = ''
relations = ''
for i in range(1, (self.size() + 1)):
nodes += draw_node(i, *positions[i])
for (i, j) in self.decreasing_cover_relations():
relations += draw_decreasing(i, j)
for (i, j) in self.increasing_cover_relations():
relations += draw_increasing(i, j)
return (((start + nodes) + relations) + end)
def poset(self) -> FinitePoset:
'\n Return ``self`` as a labelled poset.\n\n An interval-poset is indeed constructed from a labelled poset which\n is stored internally. This method allows to access the poset and\n all the associated methods.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(3,2),(2,4),(3,4)])\n sage: pos = ip.poset(); pos\n Finite poset containing 4 elements\n sage: pos.maximal_chains()\n [[3, 2, 4], [1, 2, 4]]\n sage: pos.maximal_elements()\n [4]\n sage: pos.is_lattice()\n False\n '
return self._poset
def _mul_(self, other: TIP) -> TIP:
'\n Return the associative product of ``self`` and ``other``.\n\n This is defined by taking the disjoint union of the relations\n of ``self`` with the relations of ``other`` shifted by `n`,\n where `n` is the size of ``self``.\n\n EXAMPLES::\n\n sage: T1 = TamariIntervalPoset(1,[])\n sage: T2 = TamariIntervalPoset(2,[[1,2]])\n sage: T1*T1\n The Tamari interval of size 2 induced by relations []\n sage: T2*T1\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: T1*T2\n The Tamari interval of size 3 induced by relations [(2, 3)]\n sage: T2*T2\n The Tamari interval of size 4 induced by relations [(1, 2), (3, 4)]\n\n TESTS::\n\n sage: U = TamariIntervalPoset(0,[])\n sage: U*T1 == T1\n True\n sage: T2*U == T2\n True\n '
n = self._size
m = other.size()
relations = self._poset.cover_relations()
relations.extend([((i + n), (j + n)) for (i, j) in other._poset.cover_relations_iterator()])
P = FinitePoset(DiGraph([list(range(1, ((n + m) + 1))), relations], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
def factor(self) -> list[TamariIntervalPoset]:
'\n Return the unique decomposition as a list of connected components.\n\n EXAMPLES::\n\n sage: factor(TamariIntervalPoset(2,[])) # indirect doctest\n [The Tamari interval of size 1 induced by relations [],\n The Tamari interval of size 1 induced by relations []]\n\n .. SEEALSO:: :meth:`is_connected`\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: T = TamariIntervalPosets(20).random_element()\n sage: facs = factor(T)\n sage: all(U.is_connected() for U in facs)\n True\n sage: T == prod(facs)\n True\n '
hasse = self.poset().hasse_diagram()
cc = hasse.connected_components_subgraphs()
resu = []
for comp in sorted(cc, key=min):
shift = (1 - min(comp))
comp.relabel((lambda i: (i + shift)))
resu.append(TamariIntervalPoset(len(comp), comp.edges(sort=False, labels=False)))
return resu
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: len(set(hash(u) for u in TamariIntervalPosets(4)))\n 68\n '
pair = (self.size(), tuple((tuple(e) for e in self._cover_relations)))
return hash(pair)
@cached_method
def increasing_cover_relations(self) -> list[tuple[(int, int)]]:
'\n Return the cover relations of the initial forest of ``self``.\n\n This is the poset formed by keeping only the relations of the form\n `a` precedes `b` with `a < b`.\n\n The initial forest of ``self`` is a forest with its roots\n being on top. It is also called the increasing poset of ``self``.\n\n .. WARNING::\n\n This method computes the cover relations of the initial\n forest. This is not identical with the cover relations of\n ``self`` which happen to be increasing!\n\n .. SEEALSO::\n\n :meth:`initial_forest`\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(4,[(1,2),(3,2),(2,4),(3,4)]).increasing_cover_relations()\n [(1, 2), (2, 4), (3, 4)]\n sage: TamariIntervalPoset(3,[(1,2),(1,3),(2,3)]).increasing_cover_relations()\n [(1, 2), (2, 3)]\n '
relations = []
size = self.size()
for i in range(1, size):
for j in range((i + 1), (size + 1)):
if self.le(i, j):
relations.append((i, j))
break
return relations
def increasing_roots(self) -> list[int]:
'\n Return the root vertices of the initial forest of ``self``.\n\n These are the vertices `a` of ``self`` such that there is no\n `b > a` with `a` precedes `b`.\n\n OUTPUT:\n\n The list of all roots of the initial forest of ``self``, in\n decreasing order.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.increasing_roots()\n [6, 5, 2]\n sage: ip.initial_forest().increasing_roots()\n [6, 5, 2]\n\n TESTS::\n\n sage: TamariIntervalPoset(0,[]).increasing_roots()\n []\n '
size = self.size()
if (size == 0):
return []
roots = [size]
root = size
for i in range((size - 1), 0, (- 1)):
if (not self.le(i, root)):
roots.append(i)
root = i
return roots
def increasing_children(self, v) -> list[int]:
'\n Return the children of ``v`` in the initial forest of ``self``.\n\n INPUT:\n\n - ``v`` -- an integer representing a vertex of ``self``\n (between 1 and ``size``)\n\n OUTPUT:\n\n The list of all children of ``v`` in the initial forest of\n ``self``, in decreasing order.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.increasing_children(2)\n [1]\n sage: ip.increasing_children(5)\n [4, 3]\n sage: ip.increasing_children(1)\n []\n '
children = []
root = None
for i in range((v - 1), 0, (- 1)):
if (not self.le(i, v)):
break
if ((root is None) or (not self.le(i, root))):
children.append(i)
root = i
return children
def increasing_parent(self, v) -> (None | int):
'\n Return the vertex parent of ``v`` in the initial forest of ``self``.\n\n This is the lowest (as integer!) vertex `b > v` such that `v`\n precedes `b`. If there is no such vertex (that is, `v` is an\n increasing root), then ``None`` is returned.\n\n INPUT:\n\n - ``v`` -- an integer representing a vertex of ``self``\n (between 1 and ``size``)\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.increasing_parent(1)\n 2\n sage: ip.increasing_parent(3)\n 5\n sage: ip.increasing_parent(4)\n 5\n sage: ip.increasing_parent(5) is None\n True\n '
parent = None
for i in range(self.size(), v, (- 1)):
if self.le(v, i):
parent = i
return parent
@cached_method
def decreasing_cover_relations(self) -> list[tuple[(int, int)]]:
'\n Return the cover relations of the final forest of ``self``.\n\n This is the poset formed by keeping only the relations of the form\n `a` precedes `b` with `a > b`.\n\n The final forest of ``self`` is a forest with its roots\n being on top. It is also called the decreasing poset of ``self``.\n\n .. WARNING::\n\n This method computes the cover relations of the final\n forest. This is not identical with the cover relations of\n ``self`` which happen to be decreasing!\n\n .. SEEALSO::\n\n :meth:`final_forest`\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(4,[(2,1),(3,2),(3,4),(4,2)]).decreasing_cover_relations()\n [(4, 2), (3, 2), (2, 1)]\n sage: TamariIntervalPoset(4,[(2,1),(4,3),(2,3)]).decreasing_cover_relations()\n [(4, 3), (2, 1)]\n sage: TamariIntervalPoset(3,[(2,1),(3,1),(3,2)]).decreasing_cover_relations()\n [(3, 2), (2, 1)]\n '
relations = []
for i in range(self.size(), 1, (- 1)):
for j in range((i - 1), 0, (- 1)):
if self.le(i, j):
relations.append((i, j))
break
return relations
def decreasing_roots(self) -> list[int]:
'\n Return the root vertices of the final forest of ``self``.\n\n These are the vertices `b` such that there is no `a < b` with `b`\n preceding `a`.\n\n OUTPUT:\n\n The list of all roots of the final forest of ``self``, in\n increasing order.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.decreasing_roots()\n [1, 2]\n sage: ip.final_forest().decreasing_roots()\n [1, 2]\n '
if (self.size() == 0):
return []
roots = [1]
root = 1
for i in range(2, (self.size() + 1)):
if (not self.le(i, root)):
roots.append(i)
root = i
return roots
def decreasing_children(self, v) -> list[int]:
'\n Return the children of ``v`` in the final forest of ``self``.\n\n INPUT:\n\n - ``v`` -- an integer representing a vertex of ``self``\n (between 1 and ``size``)\n\n OUTPUT:\n\n The list of all children of ``v`` in the final forest of ``self``,\n in increasing order.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.decreasing_children(2)\n [3, 5]\n sage: ip.decreasing_children(3)\n [4]\n sage: ip.decreasing_children(1)\n []\n '
children = []
root = None
for i in range((v + 1), (self.size() + 1)):
if (not self.le(i, v)):
break
if ((root is None) or (not self.le(i, root))):
children.append(i)
root = i
return children
def decreasing_parent(self, v) -> (None | int):
'\n Return the vertex parent of ``v`` in the final forest of ``self``.\n\n This is the highest (as integer!) vertex `a < v` such that ``v``\n precedes ``a``. If there is no such vertex (that is, `v` is a\n decreasing root), then ``None`` is returned.\n\n INPUT:\n\n - ``v`` -- an integer representing a vertex of ``self`` (between\n 1 and ``size``)\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.decreasing_parent(4)\n 3\n sage: ip.decreasing_parent(3)\n 2\n sage: ip.decreasing_parent(5)\n 2\n sage: ip.decreasing_parent(2) is None\n True\n '
parent = None
for i in range(1, v):
if self.le(v, i):
parent = i
return parent
def le(self, e1, e2) -> bool:
'\n Return whether ``e1`` precedes or equals ``e2`` in ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.le(1,2)\n True\n sage: ip.le(1,3)\n True\n sage: ip.le(2,3)\n True\n sage: ip.le(3,4)\n False\n sage: ip.le(1,1)\n True\n '
return self._poset.le(e1, e2)
def lt(self, e1, e2) -> bool:
'\n Return whether ``e1`` strictly precedes ``e2`` in ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.lt(1,2)\n True\n sage: ip.lt(1,3)\n True\n sage: ip.lt(2,3)\n True\n sage: ip.lt(3,4)\n False\n sage: ip.lt(1,1)\n False\n '
return self._poset.lt(e1, e2)
def ge(self, e1, e2) -> bool:
'\n Return whether ``e2`` precedes or equals ``e1`` in ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.ge(2,1)\n True\n sage: ip.ge(3,1)\n True\n sage: ip.ge(3,2)\n True\n sage: ip.ge(4,3)\n False\n sage: ip.ge(1,1)\n True\n '
return self._poset.ge(e1, e2)
def gt(self, e1, e2) -> bool:
'\n Return whether ``e2`` strictly precedes ``e1`` in ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.gt(2,1)\n True\n sage: ip.gt(3,1)\n True\n sage: ip.gt(3,2)\n True\n sage: ip.gt(4,3)\n False\n sage: ip.gt(1,1)\n False\n '
return self._poset.gt(e1, e2)
def size(self) -> Integer:
'\n Return the size (number of vertices) of the interval-poset.\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(3,[(2,1),(3,1)]).size()\n 3\n '
return self._size
@cached_method
def cubical_coordinates(self) -> tuple[(int, ...)]:
'\n Return the cubical coordinates of ``self``.\n\n This provides a fast and natural way to order\n the set of interval-posets of a given size.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.cubical_coordinates()\n (-1, -2, 0)\n\n TESTS::\n\n sage: ip = TamariIntervalPoset(1,[])\n sage: ip.cubical_coordinates()\n ()\n sage: ip = TamariIntervalPoset(3,[])\n sage: ip.cubical_coordinates()\n (0, 0)\n sage: ip = TamariIntervalPosets(10).random_element() # needs sage.combinat\n sage: len(ip.cubical_coordinates()) # needs sage.combinat\n 9\n sage: sorted(ip.cubical_coordinates() for ip in TamariIntervalPosets(2)) # needs sage.combinat\n [(-1,), (0,), (1,)]\n\n REFERENCES:\n\n - [Com2019]_\n '
tup = ([0] * (self.size() - 1))
for (i, j) in self._poset.relations_iterator(strict=True):
if (i < j):
tup[(j - 2)] -= 1
else:
tup[(j - 1)] += 1
return tuple(tup)
def complement(self) -> TIP:
'\n Return the complement of the interval-poset ``self``.\n\n If `P` is a Tamari interval-poset of size `n`, then the\n *complement* of `P` is defined as the interval-poset `Q` whose\n base set is `[n] = \\{1, 2, \\ldots, n\\}` (just as for `P`), but\n whose order relation has `a` precede `b` if and only if\n `n + 1 - a` precedes `n + 1 - b` in `P`.\n\n In terms of the Tamari lattice, the *complement* is the symmetric\n of ``self``. It is formed from the left-right symmetrized of\n the binary trees of the interval (switching left and right\n subtrees, see\n :meth:`~sage.combinat.binary_tree.BinaryTree.left_right_symmetry`).\n In particular, initial intervals are sent to final intervals and\n vice-versa.\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(3, [(2, 1), (3, 1)]).complement()\n The Tamari interval of size 3 induced by relations [(1, 3), (2, 3)]\n sage: TamariIntervalPoset(0, []).complement()\n The Tamari interval of size 0 induced by relations []\n sage: ip = TamariIntervalPoset(4, [(1, 2), (2, 4), (3, 4)])\n sage: ip.complement() == TamariIntervalPoset(4, [(2, 1), (3, 1), (4, 3)])\n True\n sage: ip.lower_binary_tree() == ip.complement().upper_binary_tree().left_right_symmetry()\n True\n sage: ip.upper_binary_tree() == ip.complement().lower_binary_tree().left_right_symmetry()\n True\n sage: ip.is_initial_interval()\n True\n sage: ip.complement().is_final_interval()\n True\n '
N = (self._size + 1)
new_covers = [[(N - i), (N - j)] for (i, j) in self._poset.cover_relations_iterator()]
P = FinitePoset(DiGraph([list(range(1, N)), new_covers], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
def left_branch_involution(self) -> TIP:
'\n Return the image of ``self`` by the left-branch involution.\n\n OUTPUT: an interval-poset\n\n .. SEEALSO:: :meth:`rise_contact_involution`\n\n EXAMPLES::\n\n sage: tip = TamariIntervalPoset(8, [(1,2), (2,4), (3,4), (6,7), (3,2), (5,4), (6,4), (8,7)])\n sage: t = tip.left_branch_involution(); t\n The Tamari interval of size 8 induced by relations [(1, 6), (2, 6),\n (3, 5), (4, 5), (5, 6), (6, 8), (7, 8), (7, 6), (4, 3), (3, 1),\n (2, 1)]\n sage: t.left_branch_involution() == tip\n True\n\n REFERENCES:\n\n - [Pons2018]_\n '
gt = self.grafting_tree().left_border_symmetry()
return TamariIntervalPosets.from_grafting_tree(gt)
def rise_contact_involution(self) -> TIP:
'\n Return the image of ``self`` by the rise-contact involution.\n\n OUTPUT: an interval-poset\n\n This is defined by conjugating the complement involution\n by the left-branch involution.\n\n .. SEEALSO:: :meth:`left_branch_involution`, :meth:`complement`\n\n EXAMPLES::\n\n sage: tip = TamariIntervalPoset(8, [(1,2), (2,4), (3,4), (6,7), (3,2), (5,4), (6,4), (8,7)])\n sage: t = tip.rise_contact_involution(); t\n The Tamari interval of size 8 induced by relations [(2, 8), (3, 8),\n (4, 5), (5, 7), (6, 7), (7, 8), (8, 1), (7, 2), (6, 2), (5, 3),\n (4, 3), (3, 2), (2, 1)]\n sage: t.rise_contact_involution() == tip\n True\n sage: (tip.lower_dyck_word().number_of_touch_points() # needs sage.combinat\n ....: == t.upper_dyck_word().number_of_initial_rises())\n True\n sage: tip.number_of_tamari_inversions() == t.number_of_tamari_inversions()\n True\n\n REFERENCES:\n\n - [Pons2018]_\n '
t = self.left_branch_involution().complement()
return t.left_branch_involution()
def insertion(self, i) -> TIP:
'\n Return the Tamari insertion of an integer `i` into the\n interval-poset ``self``.\n\n If `P` is a Tamari interval-poset of size `n` and `i` is an\n integer with `1 \\leq i \\leq n+1`, then the Tamari insertion of\n `i` into `P` is defined as the Tamari interval-poset of size\n `n+1` which corresponds to the interval `[C_1, C_2]` on the\n Tamari lattice, where the binary trees `C_1` and `C_2` are\n defined as follows: We write the interval-poset `P` as\n `[B_1, B_2]` for two binary trees `B_1` and `B_2`. We label\n the vertices of each of these two trees with the integers\n `1, 2, \\ldots, i-1, i+1, i+2, \\ldots, n+1` in such a way that\n the trees are binary search trees (this labelling is unique).\n Then, we insert `i` into each of these trees (in the way as\n explained in\n :meth:`~sage.combinat.binary_tree.LabelledBinaryTree.binary_search_insert`).\n The shapes of the resulting two trees are denoted `C_1` and\n `C_2`.\n\n An alternative way to construct the insertion of `i` into\n `P` is by relabeling each vertex `u` of `P` satisfying\n `u \\geq i` (as integers) as `u+1`, and then adding a vertex\n `i` which should precede `i-1` and `i+1`.\n\n .. TODO::\n\n To study this, it would be more natural to define\n interval-posets on arbitrary ordered sets rather than just\n on `\\{1, 2, \\ldots, n\\}`.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4, [(2, 3), (4, 3)]); ip\n The Tamari interval of size 4 induced by relations [(2, 3), (4, 3)]\n sage: ip.insertion(1)\n The Tamari interval of size 5 induced by relations [(1, 2), (3, 4), (5, 4)]\n sage: ip.insertion(2)\n The Tamari interval of size 5 induced by relations [(2, 3), (3, 4), (5, 4), (2, 1)]\n sage: ip.insertion(3)\n The Tamari interval of size 5 induced by relations [(2, 4), (3, 4), (5, 4), (3, 2)]\n sage: ip.insertion(4)\n The Tamari interval of size 5 induced by relations [(2, 3), (4, 5), (5, 3), (4, 3)]\n sage: ip.insertion(5)\n The Tamari interval of size 5 induced by relations [(2, 3), (5, 4), (4, 3)]\n\n sage: ip = TamariIntervalPoset(0, [])\n sage: ip.insertion(1)\n The Tamari interval of size 1 induced by relations []\n\n sage: ip = TamariIntervalPoset(1, [])\n sage: ip.insertion(1)\n The Tamari interval of size 2 induced by relations [(1, 2)]\n sage: ip.insertion(2)\n The Tamari interval of size 2 induced by relations [(2, 1)]\n\n TESTS:\n\n Verifying that the two ways of computing insertion are\n equivalent::\n\n sage: def insert_alternative(T, i):\n ....: # Just another way to compute the insertion of i into T.\n ....: from sage.combinat.binary_tree import LabelledBinaryTree\n ....: B1 = T.lower_binary_tree().canonical_labelling()\n ....: B2 = T.upper_binary_tree().canonical_labelling()\n ....: C1 = B1.binary_search_insert(i)\n ....: C2 = B2.binary_search_insert(i)\n ....: return TamariIntervalPosets.from_binary_trees(C1, C2)\n\n We should have relabelled the trees to "make space" for a label i,\n but we did not, because it does not make a difference: The\n binary search insertion will go precisely the same, because\n an integer equal to the label of the root gets sent onto\n the left branch.\n\n sage: def test_equivalence(n):\n ....: for T in TamariIntervalPosets(n):\n ....: for i in range(1, n + 2):\n ....: if insert_alternative(T, i) != T.insertion(i):\n ....: print(T, i)\n ....: return False\n ....: return True\n sage: test_equivalence(3) # needs sage.combinat\n True\n\n sage: ti = TamariIntervalPosets(3).an_element()\n sage: ti.insertion(6)\n Traceback (most recent call last):\n ...\n ValueError: integer to be inserted not in the appropriate interval\n '
n = self._size
if (not (0 < i <= (n + 1))):
raise ValueError('integer to be inserted not in the appropriate interval')
def add1(u):
if (u >= i):
return (u + 1)
return u
rels = [(add1(a), add1(b)) for (a, b) in self.decreasing_cover_relations()]
rels += [(add1(a), add1(b)) for (a, b) in self.increasing_cover_relations()]
rels += [(k, (k - 1)) for k in [i] if (i > 1)]
rels += [(k, (k + 1)) for k in [i] if (i <= n)]
return TamariIntervalPoset((n + 1), rels)
def _repr_(self) -> str:
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: TamariIntervalPoset(3,[(2,1),(3,1)])\n The Tamari interval of size 3 induced by relations [(3, 1), (2, 1)]\n sage: TamariIntervalPoset(3,[(3,1),(2,1)])\n The Tamari interval of size 3 induced by relations [(3, 1), (2, 1)]\n sage: TamariIntervalPoset(3,[(2,3),(2,1)])\n The Tamari interval of size 3 induced by relations [(2, 3), (2, 1)]\n '
msg = 'The Tamari interval of size {} induced by relations {}'
return msg.format(self.size(), (self.increasing_cover_relations() + self.decreasing_cover_relations()))
def _ascii_art_(self):
'\n Return an ascii art picture of ``self``.\n\n This is a picture of the Hasse diagram. Vertices from `1` to `n`\n are placed on the diagonal from top-left to bottom-right.\n Then increasing covers are drawn above the diagonal\n and decreasing covers are drawn below the diagonal.\n\n EXAMPLES::\n\n sage: T = TamariIntervalPosets(5)[56]\n sage: ascii_art(T)\n O-----------+\n O--------+\n +--O--+ |\n O--+\n O\n sage: T.poset().cover_relations()\n [[3, 4], [3, 2], [4, 5], [2, 5], [1, 5]]\n '
n = self.size()
M = [[(' O ' if (i == j) else ' ') for i in range(n)] for j in range(n)]
def superpose(x, y, b):
i = (x - 1)
j = (y - 1)
a = M[i][j]
if (a == ' '):
M[i][j] = b
elif (a == '-+ '):
if (b == a):
pass
elif (b == '---'):
M[i][j] = '-+-'
elif (b == ' | '):
M[i][j] = '-+ '
elif (a == ' +-'):
if (b == a):
pass
elif (b == '---'):
M[i][j] = '-+-'
elif (b == ' | '):
M[i][j] = ' +-'
elif (a == '---'):
if (b == a):
pass
elif (b == '-+ '):
M[i][j] = '-+-'
elif (b == ' +-'):
M[i][j] = '-+-'
elif (a == ' | '):
if (b == a):
pass
elif (b == '-+ '):
M[i][j] = '-+ '
elif (b == ' +-'):
M[i][j] = ' +-'
def superpose_node(i, right=True):
i -= 1
if (M[i][i] == ' O '):
if right:
M[i][i] = ' O-'
else:
M[i][i] = '-O '
elif ((M[i][i] == ' O-') and (not right)):
M[i][i] = '-O-'
elif ((M[i][i] == '-O ') and right):
M[i][i] = '-O-'
for (i, j) in self.poset().hasse_diagram().edges(sort=True, labels=False):
if (i > j):
superpose_node(i, False)
superpose(i, j, ' +-')
for k in range((j + 1), i):
superpose(k, j, ' | ')
superpose(i, k, '---')
else:
superpose_node(i, True)
superpose(i, j, '-+ ')
for k in range((i + 1), j):
superpose(i, k, '---')
superpose(k, j, ' | ')
from sage.typeset.ascii_art import AsciiArt
return AsciiArt([''.join(ligne) for ligne in M])
def _unicode_art_(self):
'\n Return an unicode picture of ``self``.\n\n This is a picture of the Hasse diagram. Vertices from `1` to `n` are\n placed on the diagonal from top-left to bottom-right.\n Then increasing covers are drawn above the diagonal\n and decreasing covers are drawn below the diagonal.\n\n EXAMPLES::\n\n sage: T = TamariIntervalPosets(5)[56]\n sage: unicode_art(T)\n o───╮\n o──┤\n ╰o╮│\n o┤\n o\n sage: T.poset().cover_relations()\n [[3, 4], [3, 2], [4, 5], [2, 5], [1, 5]]\n '
n = self.size()
M = [[('o' if (i == j) else ' ') for i in range(n)] for j in range(n)]
def superpose(x, y, b):
i = (x - 1)
j = (y - 1)
a = M[i][j]
if (a == ' '):
M[i][j] = b
elif (a == '╮'):
if (b == a):
pass
elif (b == '─'):
M[i][j] = '┬'
elif (b == '│'):
M[i][j] = '┤'
elif (a == '╰'):
if (b == a):
pass
elif (b == '─'):
M[i][j] = '┴'
elif (b == '│'):
M[i][j] = '├'
elif (a == '─'):
if (b == a):
pass
elif (b == '╮'):
M[i][j] = '┬'
elif (b == '╰'):
M[i][j] = '┴'
elif (a == '│'):
if (b == a):
pass
elif (b == '╮'):
M[i][j] = '┤'
elif (b == '╰'):
M[i][j] = '├'
for (i, j) in self.poset().hasse_diagram().edges(sort=True, labels=False):
if (i > j):
superpose(i, j, '╰')
for k in range((j + 1), i):
superpose(k, j, '│')
superpose(i, k, '─')
else:
superpose(i, j, '╮')
for k in range((i + 1), j):
superpose(i, k, '─')
superpose(k, j, '│')
from sage.typeset.unicode_art import UnicodeArt
return UnicodeArt([''.join(ligne) for ligne in M])
def _richcmp_(self, other, op) -> bool:
'\n Comparison.\n\n The comparison is first by size, then\n using cubical coordinates.\n\n .. SEEALSO:: :meth:`cubical_coordinates`\n\n TESTS::\n\n sage: TamariIntervalPoset(0,[]) == TamariIntervalPoset(0,[])\n True\n sage: TamariIntervalPoset(1,[]) == TamariIntervalPoset(0,[])\n False\n sage: TamariIntervalPoset(3,[(1,2),(3,2)]) == TamariIntervalPoset(3,[(3,2),(1,2)])\n True\n sage: TamariIntervalPoset(3,[(1,2),(3,2)]) == TamariIntervalPoset(3,[(1,2)])\n False\n sage: TamariIntervalPoset(3,[(1,2),(3,2)]) != TamariIntervalPoset(3,[(3,2),(1,2)])\n False\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip2 = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip1 <= ip2\n False\n sage: ip1 <= ip1\n True\n sage: ip2 <= ip1\n True\n\n sage: ip1 != 33\n True\n '
if (not isinstance(other, TamariIntervalPoset)):
return NotImplemented
if (op == op_EQ):
return ((self.size() == other.size()) and (self._cover_relations == other._cover_relations))
if (op == op_NE):
return (not ((self.size() == other.size()) and (self._cover_relations == other._cover_relations)))
return richcmp((self.size(), self.cubical_coordinates()), (other.size(), other.cubical_coordinates()), op)
def __iter__(self) -> Iterator[int]:
'\n Iterate through the vertices of ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(3,2)])\n sage: [i for i in ip]\n [1, 2, 3, 4]\n '
return iter(range(1, (self.size() + 1)))
def contains_interval(self, other) -> bool:
'\n Return whether the interval represented by ``other`` is contained\n in ``self`` as an interval of the Tamari lattice.\n\n In terms of interval-posets, it means that all relations of ``self``\n are relations of ``other``.\n\n INPUT:\n\n - ``other`` -- an interval-poset\n\n EXAMPLES::\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip2 = TamariIntervalPoset(4,[(2,3)])\n sage: ip2.contains_interval(ip1)\n True\n sage: ip3 = TamariIntervalPoset(4,[(2,1)])\n sage: ip2.contains_interval(ip3)\n False\n sage: ip4 = TamariIntervalPoset(3,[(2,3)])\n sage: ip2.contains_interval(ip4)\n False\n '
if (other.size() != self.size()):
return False
return all((other.le(i, j) for (i, j) in self._cover_relations))
def lower_contains_interval(self, other) -> bool:
'\n Return whether the interval represented by ``other`` is contained\n in ``self`` as an interval of the Tamari lattice and if they share\n the same lower bound.\n\n As interval-posets, it means that ``other`` contains the relations\n of ``self`` plus some extra increasing relations.\n\n INPUT:\n\n - ``other`` -- an interval-poset\n\n EXAMPLES::\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip2 = TamariIntervalPoset(4,[(4,3)])\n sage: ip2.lower_contains_interval(ip1)\n True\n sage: ip2.contains_interval(ip1) and ip2.lower_binary_tree() == ip1.lower_binary_tree()\n True\n sage: ip3 = TamariIntervalPoset(4,[(4,3),(2,1)])\n sage: ip2.contains_interval(ip3)\n True\n sage: ip2.lower_binary_tree() == ip3.lower_binary_tree()\n False\n sage: ip2.lower_contains_interval(ip3)\n False\n\n TESTS::\n\n sage: ip1 = TamariIntervalPoset(3,[(1,2),(2,3)])\n sage: ip2 = TamariIntervalPoset(3,[(2,1),(3,2)])\n sage: ip2.lower_contains_interval(ip1)\n False\n '
if (not self.contains_interval(other)):
return False
return all((self.le(i, j) for (i, j) in other.decreasing_cover_relations()))
def upper_contains_interval(self, other) -> bool:
'\n Return whether the interval represented by ``other`` is contained\n in ``self`` as an interval of the Tamari lattice and if they share\n the same upper bound.\n\n As interval-posets, it means that ``other`` contains the relations\n of ``self`` plus some extra decreasing relations.\n\n INPUT:\n\n - ``other`` -- an interval-poset\n\n EXAMPLES::\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip2 = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip2.upper_contains_interval(ip1)\n True\n sage: ip2.contains_interval(ip1) and ip2.upper_binary_tree() == ip1.upper_binary_tree()\n True\n sage: ip3 = TamariIntervalPoset(4,[(1,2),(2,3),(3,4)])\n sage: ip2.upper_contains_interval(ip3)\n False\n sage: ip2.contains_interval(ip3)\n True\n sage: ip2.upper_binary_tree() == ip3.upper_binary_tree()\n False\n\n TESTS::\n\n sage: ip1 = TamariIntervalPoset(3,[(1,2),(2,3)])\n sage: ip2 = TamariIntervalPoset(3,[(2,1),(3,2)])\n sage: ip2.lower_contains_interval(ip1)\n False\n '
if (not self.contains_interval(other)):
return False
return all((self.le(i, j) for (i, j) in other.increasing_cover_relations()))
def is_linear_extension(self, perm) -> bool:
'\n Return whether the permutation ``perm`` is a linear extension\n of ``self``.\n\n INPUT:\n\n - ``perm`` -- a permutation of the size of ``self``\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip.is_linear_extension([1,4,2,3])\n True\n sage: ip.is_linear_extension(Permutation([1,4,2,3]))\n True\n sage: ip.is_linear_extension(Permutation([1,4,3,2]))\n False\n '
return self._poset.is_linear_extension(perm)
def contains_binary_tree(self, binary_tree) -> bool:
'\n Return whether the interval represented by ``self`` contains\n the binary tree ``binary_tree``.\n\n INPUT:\n\n - ``binary_tree`` -- a binary tree\n\n .. SEEALSO:: :meth:`contains_dyck_word`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.contains_binary_tree(BinaryTree([[None,[None,[]]],None]))\n True\n sage: ip.contains_binary_tree(BinaryTree([None,[[[],None],None]]))\n True\n sage: ip.contains_binary_tree(BinaryTree([[],[[],None]]))\n False\n sage: ip.contains_binary_tree(ip.lower_binary_tree())\n True\n sage: ip.contains_binary_tree(ip.upper_binary_tree())\n True\n sage: all(ip.contains_binary_tree(bt) for bt in ip.binary_trees())\n True\n '
return self.is_linear_extension(binary_tree.to_132_avoiding_permutation())
def contains_dyck_word(self, dyck_word) -> bool:
'\n Return whether the interval represented by ``self`` contains\n the Dyck word ``dyck_word``.\n\n INPUT:\n\n - ``dyck_word`` -- a Dyck word\n\n .. SEEALSO:: :meth:`contains_binary_tree`\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.contains_dyck_word(DyckWord([1,1,1,0,0,0,1,0]))\n True\n sage: ip.contains_dyck_word(DyckWord([1,1,0,1,0,1,0,0]))\n True\n sage: ip.contains_dyck_word(DyckWord([1,0,1,1,0,1,0,0]))\n False\n sage: ip.contains_dyck_word(ip.lower_dyck_word())\n True\n sage: ip.contains_dyck_word(ip.upper_dyck_word())\n True\n sage: all(ip.contains_dyck_word(bt) for bt in ip.dyck_words())\n True\n '
return self.contains_binary_tree(dyck_word.to_binary_tree_tamari())
def intersection(self, other: TIP) -> TIP:
'\n Return the interval-poset formed by combining the relations from\n both ``self`` and ``other``. It corresponds to the intersection\n of the two corresponding intervals of the Tamari lattice.\n\n INPUT:\n\n - ``other`` -- an interval-poset of the same size as ``self``\n\n EXAMPLES::\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip2 = TamariIntervalPoset(4,[(4,3)])\n sage: ip1.intersection(ip2)\n The Tamari interval of size 4 induced by relations [(1, 2), (2, 3), (4, 3)]\n sage: ip3 = TamariIntervalPoset(4,[(2,1)])\n sage: ip1.intersection(ip3)\n Traceback (most recent call last):\n ...\n ValueError: this intersection is empty, it does not correspond to an interval-poset\n sage: ip4 = TamariIntervalPoset(3,[(2,3)])\n sage: ip2.intersection(ip4)\n Traceback (most recent call last):\n ...\n ValueError: intersections are only possible on interval-posets of the same size\n '
if (other.size() != self.size()):
raise ValueError('intersections are only possible on interval-posets of the same size')
try:
return TamariIntervalPoset(self.size(), (self._cover_relations + other._cover_relations))
except ValueError:
raise ValueError('this intersection is empty, it does not correspond to an interval-poset')
def initial_forest(self) -> TIP:
'\n Return the initial forest of ``self``, i.e., the interval-poset\n formed from only the increasing relations of ``self``.\n\n .. SEEALSO:: :meth:`final_forest`\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(4,[(1,2),(3,2),(2,4),(3,4)]).initial_forest()\n The Tamari interval of size 4 induced by relations [(1, 2), (2, 4), (3, 4)]\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: ip.initial_forest() == ip\n True\n '
relations = self.increasing_cover_relations()
P = FinitePoset(DiGraph([list(range(1, (self._size + 1))), relations], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
def final_forest(self) -> TIP:
'\n Return the final forest of ``self``, i.e., the interval-poset\n formed with only the decreasing relations of ``self``.\n\n .. SEEALSO:: :meth:`initial_forest`\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(4,[(2,1),(3,2),(3,4),(4,2)]).final_forest()\n The Tamari interval of size 4 induced by relations [(4, 2), (3, 2), (2, 1)]\n sage: ip = TamariIntervalPoset(3,[(2,1),(3,1)])\n sage: ip.final_forest() == ip\n True\n '
relations = self.decreasing_cover_relations()
P = FinitePoset(DiGraph([list(range(1, (self._size + 1))), relations], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
def is_initial_interval(self) -> bool:
'\n Return if ``self`` corresponds to an initial interval of the Tamari\n lattice.\n\n This means that its lower end is the smallest element of the lattice.\n It consists of checking that ``self`` does not contain any decreasing\n relations.\n\n .. SEEALSO:: :meth:`is_final_interval`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4, [(1, 2), (2, 4), (3, 4)])\n sage: ip.is_initial_interval()\n True\n sage: ip.lower_dyck_word() # needs sage.combinat\n [1, 0, 1, 0, 1, 0, 1, 0]\n sage: ip = TamariIntervalPoset(4, [(1, 2), (2, 4), (3, 4), (3, 2)])\n sage: ip.is_initial_interval()\n False\n sage: ip.lower_dyck_word() # needs sage.combinat\n [1, 0, 1, 1, 0, 0, 1, 0]\n sage: all(DyckWord([1,0,1,0,1,0]).tamari_interval(dw) # needs sage.combinat\n ....: .is_initial_interval()\n ....: for dw in DyckWords(3))\n True\n '
return (not self.decreasing_cover_relations())
def is_final_interval(self) -> bool:
'\n Return if ``self`` corresponds to a final interval of the Tamari\n lattice.\n\n This means that its upper end is the largest element of the lattice.\n It consists of checking that ``self`` does not contain any increasing\n relations.\n\n .. SEEALSO:: :meth:`is_initial_interval`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4, [(4, 3), (3, 1), (2, 1)])\n sage: ip.is_final_interval()\n True\n sage: ip.upper_dyck_word() # needs sage.combinat\n [1, 1, 1, 1, 0, 0, 0, 0]\n sage: ip = TamariIntervalPoset(4, [(4, 3), (3, 1), (2, 1), (2, 3)])\n sage: ip.is_final_interval()\n False\n sage: ip.upper_dyck_word() # needs sage.combinat\n [1, 1, 0, 1, 1, 0, 0, 0]\n sage: all(dw.tamari_interval(DyckWord([1, 1, 1, 0, 0, 0])) # needs sage.combinat\n ....: .is_final_interval()\n ....: for dw in DyckWords(3))\n True\n '
return (not self.increasing_cover_relations())
def lower_binary_tree(self):
'\n Return the lowest binary tree in the interval of the Tamari\n lattice represented by ``self``.\n\n This is a binary tree. It is the shape of the unique binary\n search tree whose left-branch ordered forest (i.e., the result\n of applying\n :meth:`~sage.combinat.binary_tree.BinaryTree.to_ordered_tree_left_branch`\n and cutting off the root) is the final forest of ``self``.\n\n .. SEEALSO:: :meth:`lower_dyck_word`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.lower_binary_tree()\n [[., .], [[., [., .]], [., .]]]\n sage: TamariIntervalPosets.final_forest(ip.lower_binary_tree()) == ip.final_forest()\n True\n sage: ip == TamariIntervalPosets.from_binary_trees(ip.lower_binary_tree(),ip.upper_binary_tree())\n True\n '
return self.min_linear_extension().binary_search_tree_shape(left_to_right=False)
def lower_dyck_word(self):
'\n Return the lowest Dyck word in the interval of the Tamari lattice\n represented by ``self``.\n\n .. SEEALSO:: :meth:`lower_binary_tree`\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: ip = TamariIntervalPoset(6, [(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)]); ip\n The Tamari interval of size 6 induced by relations\n [(1, 2), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.lower_dyck_word()\n [1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0]\n sage: ldw_ff = TamariIntervalPosets.final_forest(ip.lower_dyck_word())\n sage: ldw_ff == ip.final_forest()\n True\n sage: ip == TamariIntervalPosets.from_dyck_words(ip.lower_dyck_word(),\n ....: ip.upper_dyck_word())\n True\n '
return self.lower_binary_tree().to_dyck_word_tamari()
def upper_binary_tree(self):
'\n Return the highest binary tree in the interval of the Tamari\n lattice represented by ``self``.\n\n This is a binary tree. It is the shape of the unique binary\n search tree whose right-branch ordered forest (i.e., the result\n of applying\n :meth:`~sage.combinat.binary_tree.BinaryTree.to_ordered_tree_right_branch`\n and cutting off the root) is the initial forest of ``self``.\n\n .. SEEALSO:: :meth:`upper_dyck_word`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.upper_binary_tree()\n [[., .], [., [[., .], [., .]]]]\n sage: TamariIntervalPosets.initial_forest(ip.upper_binary_tree()) == ip.initial_forest()\n True\n sage: ip == TamariIntervalPosets.from_binary_trees(ip.lower_binary_tree(),ip.upper_binary_tree())\n True\n '
return self.max_linear_extension().binary_search_tree_shape(left_to_right=False)
def upper_dyck_word(self):
'\n Return the highest Dyck word in the interval of the Tamari lattice\n represented by ``self``.\n\n .. SEEALSO:: :meth:`upper_binary_tree`\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)]); ip\n The Tamari interval of size 6 induced by relations\n [(1, 2), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.upper_dyck_word()\n [1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0]\n sage: udw_if = TamariIntervalPosets.initial_forest(ip.upper_dyck_word())\n sage: udw_if == ip.initial_forest()\n True\n sage: ip == TamariIntervalPosets.from_dyck_words(ip.lower_dyck_word(),\n ....: ip.upper_dyck_word())\n True\n '
return self.upper_binary_tree().to_dyck_word_tamari()
def subposet(self, start, end) -> TIP:
'\n Return the renormalized subposet of ``self`` consisting solely\n of integers from ``start`` (inclusive) to ``end`` (not inclusive).\n\n "Renormalized" means that these integers are relabelled\n `1,2,\\ldots,k` in the obvious way (i.e., by subtracting\n ``start - 1``).\n\n INPUT:\n\n - ``start`` -- an integer, the starting vertex (inclusive)\n - ``end`` -- an integer, the ending vertex (not inclusive)\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(3,5),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (3, 5), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.subposet(1,3)\n The Tamari interval of size 2 induced by relations [(1, 2)]\n sage: ip.subposet(1,4)\n The Tamari interval of size 3 induced by relations [(1, 2), (3, 2)]\n sage: ip.subposet(1,5)\n The Tamari interval of size 4 induced by relations [(1, 2), (4, 3), (3, 2)]\n sage: ip.subposet(1,7) == ip\n True\n sage: ip.subposet(1,1)\n The Tamari interval of size 0 induced by relations []\n\n TESTS::\n\n sage: ip.sub_poset(1,1)\n The Tamari interval of size 0 induced by relations []\n sage: ip = TamariIntervalPosets(4).an_element()\n sage: ip.subposet(2,9)\n Traceback (most recent call last):\n ...\n ValueError: invalid starting or ending value\n '
if ((start < 1) or (start > end) or (end > (self.size() + 1))):
raise ValueError('invalid starting or ending value')
if (start == end):
return TamariIntervalPoset(0, [])
relations = [(((i - start) + 1), ((j - start) + 1)) for (i, j) in self.increasing_cover_relations() if ((i >= start) and (j < end))]
relations.extend([(((j - start) + 1), ((i - start) + 1)) for (j, i) in self.decreasing_cover_relations() if ((i >= start) and (j < end))])
return TamariIntervalPoset((end - start), relations, check=False)
sub_poset = subposet
def min_linear_extension(self) -> Permutation:
'\n Return the minimal permutation for the right weak order which is\n a linear extension of ``self``.\n\n This is also the minimal permutation in the sylvester\n class of ``self.lower_binary_tree()`` and is a 312-avoiding\n permutation.\n\n The right weak order is also known as the right permutohedron\n order. See\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`\n for its definition.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip.min_linear_extension()\n [1, 2, 4, 3]\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)])\n sage: ip.min_linear_extension()\n [1, 4, 3, 6, 5, 2]\n sage: ip = TamariIntervalPoset(0,[])\n sage: ip.min_linear_extension()\n []\n sage: ip = TamariIntervalPoset(5, [(1, 4), (2, 4), (3, 4), (5, 4)]); ip\n The Tamari interval of size 5 induced by relations [(1, 4), (2, 4), (3, 4), (5, 4)]\n sage: ip.min_linear_extension()\n [1, 2, 3, 5, 4]\n '
final_forest = DiGraph([list(self), self.decreasing_cover_relations()], format='vertices_and_edges')
def add(perm: list, i):
'\n Internal recursive method to compute the min linear extension.\n '
for j in sorted(final_forest.neighbors_in(i)):
add(perm, j)
perm.append(i)
perm: list[int] = []
for i in sorted(final_forest.sinks()):
add(perm, i)
return Permutation(perm)
def max_linear_extension(self) -> Permutation:
'\n Return the maximal permutation for the right weak order which is\n a linear extension of ``self``.\n\n This is also the maximal permutation in the sylvester\n class of ``self.upper_binary_tree()`` and is a 132-avoiding\n permutation.\n\n The right weak order is also known as the right permutohedron\n order. See\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`\n for its definition.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip.max_linear_extension()\n [4, 1, 2, 3]\n sage: ip = TamariIntervalPoset(6,[(3,2),(4,3),(5,2),(6,5),(1,2),(4,5)]); ip\n The Tamari interval of size 6 induced by relations [(1, 2), (4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: ip.max_linear_extension()\n [6, 4, 5, 3, 1, 2]\n sage: ip = TamariIntervalPoset(0,[]); ip\n The Tamari interval of size 0 induced by relations []\n sage: ip.max_linear_extension()\n []\n sage: ip = TamariIntervalPoset(5, [(1, 4), (2, 4), (3, 4), (5, 4)]); ip\n The Tamari interval of size 5 induced by relations [(1, 4), (2, 4), (3, 4), (5, 4)]\n sage: ip.max_linear_extension()\n [5, 3, 2, 1, 4]\n '
initial_forest = DiGraph([list(self), self.increasing_cover_relations()], format='vertices_and_edges')
def add(perm: list, i):
'\n Internal recursive method to compute the max linear extension.\n '
for j in sorted(initial_forest.neighbors_in(i), reverse=True):
add(perm, j)
perm.append(i)
perm: list[int] = []
for i in sorted(initial_forest.sinks(), reverse=True):
add(perm, i)
return Permutation(perm)
def linear_extensions(self) -> Iterator[Permutation]:
'\n Return an iterator on the permutations which are linear\n extensions of ``self``.\n\n They form an interval of the right weak order (also called the\n right permutohedron order -- see\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`\n for a definition).\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(3, [(1,2),(3,2)])\n sage: list(ip.linear_extensions()) # needs sage.modules sage.rings.finite_rings\n [[3, 1, 2], [1, 3, 2]]\n sage: ip = TamariIntervalPoset(4, [(1,2),(2,3),(4,3)])\n sage: list(ip.linear_extensions()) # needs sage.modules sage.rings.finite_rings\n [[4, 1, 2, 3], [1, 2, 4, 3], [1, 4, 2, 3]]\n '
for ext in self._poset.linear_extensions():
(yield Permutation(ext))
def lower_contained_intervals(self) -> Iterator[TIP]:
'\n If ``self`` represents the interval `[t_1, t_2]` of the Tamari\n lattice, return an iterator on all intervals `[t_1,t]` with\n `t \\leq t_2` for the Tamari lattice.\n\n In terms of interval-posets, it corresponds to adding all possible\n relations of the form `n` precedes `m` with `n<m`.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: list(ip.lower_contained_intervals())\n [The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(1, 4), (2, 4), (3, 4), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(2, 3), (3, 4), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(1, 4), (2, 3), (3, 4), (3, 1), (2, 1)]]\n sage: ip = TamariIntervalPoset(4,[])\n sage: len(list(ip.lower_contained_intervals()))\n 14\n '
size = self._size
(yield self)
'\n we try to add links recursively in this order:\n 1 -> 2\n 2 -> 3\n 1 -> 3\n 3 -> 4\n 2 -> 4\n 1 -> 4\n ...\n ("Link" means "relation of the poset".)\n\n One useful feature of interval-posets is that if you add a single\n new relation -- say, `x` precedes `y` -- to an existing\n interval-poset and take the transitive closure, and if the axioms\n of an interval-poset are still satisfied for `(a,c) = (x,y)` and\n for `(a,c) = (y,x)`, then the transitive closure is an\n interval-poset (i.e., roughly speaking, the other new relations\n forced by `x` preceding `y` under transitive closure cannot\n invalidate the axioms). This is helpful when extending\n interval-posets, and is the reason why this and other iterators\n don\'t yield invalid interval-posets.\n '
def add_relations(poset, n, m):
'\n Internal recursive method to generate all possible intervals.\n At every step during the iteration, we have n < m and every\n i satisfying n < i < m satisfies that i precedes m in the\n poset ``poset`` (except when m > size).\n '
if (n <= 0):
n = m
m += 1
if (m > size):
return
if poset.le(n, m):
(yield from add_relations(poset, (n - 1), m))
elif poset.le(m, n):
(yield from add_relations(poset, m, (m + 1)))
else:
(yield from add_relations(poset, m, (m + 1)))
poset = TamariIntervalPoset(poset.size(), (poset._cover_relations + ((n, m),)))
(yield poset)
(yield from add_relations(poset, (n - 1), m))
(yield from add_relations(self, 1, 2))
def interval_cardinality(self) -> Integer:
'\n Return the cardinality of the interval, i.e., the number of elements\n (binary trees or Dyck words) in the interval represented by ``self``.\n\n Not to be confused with :meth:`size` which is the number of\n vertices.\n\n .. SEEALSO:: :meth:`binary_trees`\n\n EXAMPLES::\n\n sage: TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)]).interval_cardinality()\n 4\n sage: TamariIntervalPoset(4,[]).interval_cardinality()\n 14\n sage: TamariIntervalPoset(4,[(1,2),(2,3),(3,4)]).interval_cardinality()\n 1\n '
return len(list(self.lower_contained_intervals()))
def binary_trees(self) -> Iterator:
'\n Return an iterator on all the binary trees in the interval\n represented by ``self``.\n\n .. SEEALSO:: :meth:`interval_cardinality`\n\n EXAMPLES::\n\n sage: list(TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)]).binary_trees())\n [[., [[., [., .]], .]],\n [[., [., [., .]]], .],\n [., [[[., .], .], .]],\n [[., [[., .], .]], .]]\n sage: set(TamariIntervalPoset(4,[]).binary_trees()) == set(BinaryTrees(4))\n True\n '
for ip in self.lower_contained_intervals():
(yield ip.upper_binary_tree())
def dyck_words(self) -> Iterator:
'\n Return an iterator on all the Dyck words in the interval\n represented by ``self``.\n\n EXAMPLES::\n\n sage: list(TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)]).dyck_words()) # needs sage.combinat\n [[1, 1, 1, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0, 1, 0],\n [1, 1, 0, 1, 0, 1, 0, 0],\n [1, 1, 0, 1, 0, 0, 1, 0]]\n sage: set(TamariIntervalPoset(4,[]).dyck_words()) == set(DyckWords(4)) # needs sage.combinat\n True\n '
for ip in self.lower_contained_intervals():
(yield ip.upper_dyck_word())
def maximal_chain_tamari_intervals(self) -> Iterator[TIP]:
"\n Return an iterator on the upper contained intervals of one\n longest chain of the Tamari interval represented by ``self``.\n\n If ``self`` represents the interval `[T_1,T_2]` of the Tamari\n lattice, this returns intervals `[T',T_2]` with `T'` following\n one longest chain between `T_1` and `T_2`.\n\n To obtain a longest chain, we use the Tamari inversions of ``self``.\n The elements of the chain are obtained by adding one by one the\n relations `(b,a)` from each Tamari inversion `(a,b)` to ``self``,\n where the Tamari inversions are taken in lexicographic order.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: list(ip.maximal_chain_tamari_intervals())\n [The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (4, 1), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (4, 1), (3, 2), (2, 1)]]\n sage: ip = TamariIntervalPoset(4,[])\n sage: list(ip.maximal_chain_tamari_intervals())\n [The Tamari interval of size 4 induced by relations [],\n The Tamari interval of size 4 induced by relations [(2, 1)],\n The Tamari interval of size 4 induced by relations [(3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(4, 1), (3, 1), (2, 1)],\n The Tamari interval of size 4 induced by relations [(4, 1), (3, 2), (2, 1)],\n The Tamari interval of size 4 induced by relations [(4, 2), (3, 2), (2, 1)],\n The Tamari interval of size 4 induced by relations [(4, 3), (3, 2), (2, 1)]]\n "
(yield self)
n = self.size()
cover_relations = list(self._cover_relations)
for inv in self.tamari_inversions_iter():
cover_relations.append((inv[1], inv[0]))
(yield TamariIntervalPoset(n, cover_relations, check=False))
def maximal_chain_binary_trees(self) -> Iterator:
'\n Return an iterator on the binary trees forming a longest chain of\n ``self`` (regarding ``self`` as an interval of the Tamari\n lattice).\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: list(ip.maximal_chain_binary_trees())\n [[[., [[., .], .]], .], [., [[[., .], .], .]], [., [[., [., .]], .]]]\n sage: ip = TamariIntervalPoset(4,[])\n sage: list(ip.maximal_chain_binary_trees())\n [[[[[., .], .], .], .],\n [[[., [., .]], .], .],\n [[., [[., .], .]], .],\n [., [[[., .], .], .]],\n [., [[., [., .]], .]],\n [., [., [[., .], .]]],\n [., [., [., [., .]]]]]\n '
for it in self.maximal_chain_tamari_intervals():
(yield it.lower_binary_tree())
def maximal_chain_dyck_words(self) -> Iterator:
'\n Return an iterator on the Dyck words forming a longest chain of\n ``self`` (regarding ``self`` as an interval of the Tamari\n lattice).\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: list(ip.maximal_chain_dyck_words()) # needs sage.combinat\n [[1, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0, 0]]\n sage: ip = TamariIntervalPoset(4,[])\n sage: list(ip.maximal_chain_dyck_words()) # needs sage.combinat\n [[1, 0, 1, 0, 1, 0, 1, 0],\n [1, 1, 0, 0, 1, 0, 1, 0],\n [1, 1, 0, 1, 0, 0, 1, 0],\n [1, 1, 0, 1, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0, 0, 0]]\n '
for it in self.maximal_chain_tamari_intervals():
(yield it.lower_dyck_word())
def tamari_inversions(self) -> list[tuple[(int, int)]]:
'\n Return the Tamari inversions of ``self``.\n\n A Tamari inversion is\n a pair of vertices `(a,b)` with `a < b` such that:\n\n - the decreasing parent of `b` is strictly smaller than `a` (or\n does not exist), and\n - the increasing parent of `a` is strictly bigger than `b` (or\n does not exist).\n\n "Smaller" and "bigger" refer to the numerical values of the\n elements, not to the poset order.\n\n This method returns the list of all Tamari inversions in\n lexicographic order.\n\n The number of Tamari inversions is the length of the\n longest chain of the Tamari interval represented by ``self``.\n\n Indeed, when an interval consists of just one binary tree, it has\n no inversion. One can also prove that if a Tamari interval\n `I\' = [T_1\', T_2\']` is a proper subset of a Tamari interval\n `I = [T_1, T_2]`, then the inversion number of `I\'` is strictly\n lower than the inversion number of `I`. And finally, by adding\n the relation `(b,a)` to the interval-poset where `(a,b)` is the\n first inversion of `I` in lexicographic order, one reduces the\n inversion number by exactly `1`.\n\n .. SEEALSO::\n\n :meth:`tamari_inversions_iter`, :meth:`number_of_tamari_inversions`\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(3,[])\n sage: ip.tamari_inversions()\n [(1, 2), (1, 3), (2, 3)]\n sage: ip = TamariIntervalPoset(3,[(2,1)])\n sage: ip.tamari_inversions()\n [(1, 3), (2, 3)]\n sage: ip = TamariIntervalPoset(3,[(1,2)])\n sage: ip.tamari_inversions()\n [(2, 3)]\n sage: ip = TamariIntervalPoset(3,[(1,2),(3,2)])\n sage: ip.tamari_inversions()\n []\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.tamari_inversions()\n [(1, 4), (2, 3)]\n sage: ip = TamariIntervalPoset(4,[])\n sage: ip.tamari_inversions()\n [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n sage: all(not TamariIntervalPosets.from_binary_trees(bt,bt) # needs sage.combinat\n ....: .tamari_inversions()\n ....: for bt in BinaryTrees(3))\n True\n sage: all(not TamariIntervalPosets.from_binary_trees(bt,bt) # needs sage.combinat\n ....: .tamari_inversions()\n ....: for bt in BinaryTrees(4))\n True\n '
return list(self.tamari_inversions_iter())
def tamari_inversions_iter(self) -> Iterator[tuple[(int, int)]]:
'\n Iterate over the Tamari inversions of ``self``, in\n lexicographic order.\n\n See :meth:`tamari_inversions` for the definition of the terms\n involved.\n\n EXAMPLES::\n\n sage: T = TamariIntervalPoset(5, [[1,2],[3,4],[3,2],[5,2],[4,2]])\n sage: list(T.tamari_inversions_iter())\n [(4, 5)]\n\n sage: T = TamariIntervalPoset(8, [(2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (8, 7), (6, 4), (5, 4), (4, 3), (3, 2)])\n sage: list(T.tamari_inversions_iter())\n [(1, 2), (1, 7), (5, 6)]\n\n sage: T = TamariIntervalPoset(1, [])\n sage: list(T.tamari_inversions_iter())\n []\n\n sage: T = TamariIntervalPoset(0, [])\n sage: list(T.tamari_inversions_iter())\n []\n '
final_forest = DiGraph([list(self), self.decreasing_cover_relations()], format='vertices_and_edges')
initial_forest = DiGraph([list(self), self.increasing_cover_relations()], format='vertices_and_edges')
n1 = (self.size() + 1)
for a in range(1, self.size()):
try:
ipa = next(initial_forest.neighbor_out_iterator(a))
max_b_1 = ipa
except StopIteration:
max_b_1 = n1
for b in range((a + 1), max_b_1):
try:
dpb = next(final_forest.neighbor_out_iterator(b))
if (dpb < a):
(yield (a, b))
except StopIteration:
(yield (a, b))
def number_of_tamari_inversions(self) -> Integer:
'\n Return the number of Tamari inversions of ``self``.\n\n This is also the length the longest chain of the Tamari\n interval represented by ``self``.\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(2,4),(3,4),(2,1),(3,1)])\n sage: ip.number_of_tamari_inversions()\n 2\n sage: ip = TamariIntervalPoset(4,[])\n sage: ip.number_of_tamari_inversions()\n 6\n sage: ip = TamariIntervalPoset(3,[])\n sage: ip.number_of_tamari_inversions()\n 3\n '
return len(self.tamari_inversions())
def number_of_new_components(self) -> Integer:
'\n Return the number of terms in the decomposition in new interval-posets.\n\n Every interval-poset has a unique decomposition as a planar tree\n of new interval-posets, as explained in [Cha2008]_. This function\n just computes the number of terms, not the planar tree nor\n the terms themselves.\n\n .. SEEALSO:: :meth:`is_new`, :meth:`new_decomposition`\n\n EXAMPLES::\n\n sage: TIP4 = TamariIntervalPosets(4)\n sage: nb = [u.number_of_new_components() for u in TIP4]\n sage: [nb.count(i) for i in range(1, 5)]\n [12, 21, 21, 14]\n '
t_low = self.lower_binary_tree().to_tilting()
t_up = self.upper_binary_tree().to_tilting()
return sum((1 for p in t_low if (p in t_up)))
def new_decomposition(self) -> list[TIP]:
'\n Return the decomposition of the interval-poset into\n new interval-posets.\n\n Every interval-poset has a unique decomposition as a planar\n tree of new interval-posets, as explained in\n [Cha2008]_. This function computes the terms of this\n decomposition, but not the planar tree.\n\n For the number of terms, you can use instead the method\n :meth:`number_of_new_components`.\n\n OUTPUT:\n\n a list of new interval-posets.\n\n .. SEEALSO::\n\n :meth:`number_of_new_components`, :meth:`is_new`\n\n EXAMPLES::\n\n sage: ex = TamariIntervalPosets(4)[11]\n sage: ex.number_of_new_components()\n 3\n sage: ex.new_decomposition() # needs sage.combinat\n [The Tamari interval of size 1 induced by relations [],\n The Tamari interval of size 2 induced by relations [],\n The Tamari interval of size 1 induced by relations []]\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: ex = TamariIntervalPosets(4).random_element()\n sage: dec = ex.new_decomposition()\n sage: len(dec) == ex.number_of_new_components()\n True\n sage: all(u.is_new() for u in dec)\n True\n '
from sage.combinat.binary_tree import BinaryTree
t_low = self.lower_binary_tree().to_tilting()
t_up = self.upper_binary_tree().to_tilting()
common = [p for p in t_low if (p in t_up)]
def extract_tree(x, y, tilt, common):
'\n Extract a tree with root at position xy (recursive).\n '
left_tree = None
for k in range((y - 1), x, (- 1)):
if ((x, k) in tilt):
if ((x, k) not in common):
left_tree = extract_tree(x, k, tilt, common)
break
right_tree = None
for k in range((x + 1), y):
if ((k, y) in tilt):
if ((k, y) not in common):
right_tree = extract_tree(k, y, tilt, common)
break
return BinaryTree([left_tree, right_tree], check=False)
tip = self.parent()
return [tip.from_binary_trees(extract_tree(cx, cy, t_low, common), extract_tree(cx, cy, t_up, common)) for (cx, cy) in common]
def decomposition_to_triple(self) -> (None | tuple[(TIP, TIP, int)]):
'\n Decompose an interval-poset into a triple (``left``, ``right``, ``r``).\n\n For the inverse method, see\n :meth:`TamariIntervalPosets.recomposition_from_triple`.\n\n OUTPUT:\n\n a triple (``left``, ``right``, ``r``) where ``left`` and\n ``right`` are interval-posets and ``r`` (an integer) is the\n parameter of the decomposition.\n\n EXAMPLES::\n\n sage: tip = TamariIntervalPoset(8, [(1,2), (2,4), (3,4), (6,7), (3,2), (5,4), (6,4), (8,7)])\n sage: tip.decomposition_to_triple()\n (The Tamari interval of size 3 induced by relations [(1, 2), (3, 2)],\n The Tamari interval of size 4 induced by relations [(2, 3), (4, 3)],\n 2)\n sage: tip == TamariIntervalPosets.recomposition_from_triple(*tip.decomposition_to_triple())\n True\n\n TESTS::\n\n sage: tip = TamariIntervalPoset(0, [])\n sage: tip.decomposition_to_triple()\n\n REFERENCES:\n\n - [CP2015]_\n '
n = self.size()
if (n == 0):
return None
root = self.increasing_roots()[(- 1)]
r = len(self.decreasing_children(root))
left = self.subposet(1, root)
right = self.subposet((root + 1), (n + 1))
return (left, right, r)
def grafting_tree(self) -> LabelledBinaryTree:
'\n Return the grafting tree of the interval-poset.\n\n For the inverse method,\n see :meth:`TamariIntervalPosets.from_grafting_tree`.\n\n EXAMPLES::\n\n sage: tip = TamariIntervalPoset(8, [(1,2), (2,4), (3,4), (6,7), (3,2), (5,4), (6,4), (8,7)])\n sage: tip.grafting_tree()\n 2[1[0[., .], 0[., .]], 0[., 1[0[., .], 0[., .]]]]\n sage: tip == TamariIntervalPosets.from_grafting_tree(tip.grafting_tree())\n True\n\n REFERENCES:\n\n - [Pons2018]_\n '
n = self.size()
if (n == 0):
return LabelledBinaryTree(None)
triplet = self.decomposition_to_triple()
assert (triplet is not None)
(left, right, r) = triplet
return LabelledBinaryTree([left.grafting_tree(), right.grafting_tree()], label=r)
def is_new(self) -> bool:
"\n Return whether ``self`` is a new Tamari interval.\n\n Here 'new' means that the interval is not contained in any\n facet of the associahedron.\n This condition is invariant under complementation.\n\n They have been considered in section 9 of [Cha2008]_.\n\n .. SEEALSO:: :meth:`is_modern`\n\n EXAMPLES::\n\n sage: TIP4 = TamariIntervalPosets(4)\n sage: len([u for u in TIP4 if u.is_new()])\n 12\n\n sage: TIP3 = TamariIntervalPosets(3)\n sage: len([u for u in TIP3 if u.is_new()])\n 3\n "
c_up = self.upper_binary_tree().single_edge_cut_shapes()
c_down = self.lower_binary_tree().single_edge_cut_shapes()
return (not any(((x in c_up) for x in c_down)))
def is_simple(self) -> bool:
"\n Return whether ``self`` is a simple Tamari interval.\n\n Here 'simple' means that the interval contains a unique binary tree.\n\n These intervals define the simple modules over the\n incidence algebras of the Tamari lattices.\n\n .. SEEALSO:: :meth:`is_final_interval`, :meth:`is_initial_interval`\n\n EXAMPLES::\n\n sage: TIP4 = TamariIntervalPosets(4)\n sage: len([u for u in TIP4 if u.is_simple()])\n 14\n\n sage: TIP3 = TamariIntervalPosets(3)\n sage: len([u for u in TIP3 if u.is_simple()])\n 5\n "
return (self.upper_binary_tree() == self.lower_binary_tree())
def is_synchronized(self) -> bool:
'\n Return whether ``self`` is a synchronized Tamari interval.\n\n This means that the upper and lower binary trees have the same canopee.\n This condition is invariant under complementation.\n\n This has been considered in [FPR2015]_. The numbers of\n synchronized intervals are given by the sequence :oeis:`A000139`.\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3)\n ....: if T.is_synchronized()])\n 6\n '
up = self.upper_binary_tree()
down = self.lower_binary_tree()
return (down.canopee() == up.canopee())
def is_modern(self) -> bool:
'\n Return whether ``self`` is a modern Tamari interval.\n\n This is defined by exclusion of a simple pattern in the Hasse diagram,\n namely there is no configuration `y \\rightarrow x \\leftarrow z`\n with `1 \\leq y < x < z \\leq n`.\n\n This condition is invariant under complementation.\n\n .. SEEALSO:: :meth:`is_new`, :meth:`is_infinitely_modern`\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3) if T.is_modern()])\n 12\n\n REFERENCES:\n\n - [Rog2018]_\n '
G = self.poset().hasse_diagram()
for x in G:
nx = G.neighbors_in(x)
nx.append(x)
if (min(nx) < x < max(nx)):
return False
return True
def is_infinitely_modern(self) -> bool:
'\n Return whether ``self`` is an infinitely-modern Tamari interval.\n\n This is defined by the exclusion of the configuration\n `i \\rightarrow i + 1` and `j + 1 \\rightarrow j` with `i < j`.\n\n This condition is invariant under complementation.\n\n .. SEEALSO:: :meth:`is_new`, :meth:`is_modern`\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3)\n ....: if T.is_infinitely_modern()])\n 12\n\n REFERENCES:\n\n - [Rog2018]_\n '
n = self.size()
found = False
for i in range(1, n):
if self.le(i, (i + 1)):
found = True
continue
if (self.le((i + 1), i) and found):
return False
return True
def is_exceptional(self) -> bool:
'\n Return whether ``self`` is an exceptional Tamari interval.\n\n This is defined by exclusion of a simple pattern in the Hasse diagram,\n namely there is no configuration ``y <-- x --> z``\n with `1 \\leq y < x < z \\leq n`.\n\n This condition is invariant under complementation.\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3)\n ....: if T.is_exceptional()])\n 12\n '
G = self.poset().hasse_diagram()
for x in G:
nx = G.neighbors_out(x)
nx.append(x)
if (min(nx) < x < max(nx)):
return False
return True
def is_dexter(self) -> bool:
'\n Return whether ``self`` is a dexter Tamari interval.\n\n This is defined by an exclusion pattern in the Hasse diagram.\n See the code for the exact description.\n\n This condition is not invariant under complementation.\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3) if T.is_dexter()])\n 12\n '
G = self.poset().hasse_diagram()
n = self.size()
for x in range(2, n):
nx = G.neighbors_out(x)
nx.append(x)
y = min(nx)
if ((y < x) and any(((z > x) for z in G.neighbor_out_iterator(y)))):
return False
return True
def is_indecomposable(self) -> bool:
'\n Return whether ``self`` is an indecomposable Tamari interval.\n\n This is the terminology of [Cha2008]_.\n\n This means that the upper binary tree has an empty left subtree.\n\n This condition is not invariant under complementation.\n\n .. SEEALSO:: :meth:`is_connected`\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3)\n ....: if T.is_indecomposable()])\n 8\n '
return (not self.upper_binary_tree()[0])
def is_connected(self) -> bool:
'\n Return whether ``self`` is a connected Tamari interval.\n\n This means that the Hasse diagram is connected.\n\n This condition is invariant under complementation.\n\n .. SEEALSO:: :meth:`is_indecomposable`, :meth:`factor`\n\n EXAMPLES::\n\n sage: len([T for T in TamariIntervalPosets(3) if T.is_connected()])\n 8\n '
return self.poset().is_connected()
|
class TamariIntervalPosets(UniqueRepresentation, Parent):
'\n Factory for interval-posets.\n\n INPUT:\n\n - ``size`` -- (optional) an integer\n\n OUTPUT:\n\n - the set of all interval-posets (of the given ``size`` if specified)\n\n EXAMPLES::\n\n sage: TamariIntervalPosets()\n Interval-posets\n\n sage: TamariIntervalPosets(2)\n Interval-posets of size 2\n\n .. NOTE::\n\n This is a factory class whose constructor returns instances of\n subclasses.\n '
@staticmethod
def __classcall_private__(cls, n=None):
'\n TESTS::\n\n sage: from sage.combinat.interval_posets import TamariIntervalPosets_all, TamariIntervalPosets_size\n sage: isinstance(TamariIntervalPosets(2), TamariIntervalPosets_size)\n True\n sage: isinstance(TamariIntervalPosets(), TamariIntervalPosets_all)\n True\n sage: TamariIntervalPosets(2) is TamariIntervalPosets_size(2)\n True\n sage: TamariIntervalPosets() is TamariIntervalPosets_all()\n True\n\n sage: TamariIntervalPosets(-2)\n Traceback (most recent call last):\n ...\n ValueError: n must be a nonnegative integer\n '
if (n is None):
return TamariIntervalPosets_all()
if (n not in NN):
raise ValueError('n must be a nonnegative integer')
return TamariIntervalPosets_size(Integer(n))
class options(GlobalOptions):
"\n Set and display the options for Tamari interval-posets.\n\n If no parameters are set, then the function returns a copy of\n the options dictionary.\n\n The ``options`` to Tamari interval-posets can be accessed as the method\n :meth:`TamariIntervalPosets.options` of :class:`TamariIntervalPosets`\n and related parent classes.\n\n @OPTIONS@\n\n EXAMPLES::\n\n sage: TIP = TamariIntervalPosets\n sage: TIP.options.latex_color_decreasing\n red\n sage: TIP.options.latex_color_decreasing='green'\n sage: TIP.options.latex_color_decreasing\n green\n sage: TIP.options._reset()\n sage: TIP.options.latex_color_decreasing\n red\n "
NAME = 'TamariIntervalPosets'
module = 'sage.combinat.interval_posets'
latex_tikz_scale = dict(default=1, description='the default value for the tikz scale when latexed', checker=(lambda x: True))
latex_line_width_scalar = dict(default=0.5, description='the default value for the line width as amultiple of the tikz scale when latexed', checker=(lambda x: True))
latex_color_decreasing = dict(default='red', description='the default color of decreasing relations when latexed', checker=(lambda x: True))
latex_color_increasing = dict(default='blue', description='the default color of increasing relations when latexed', checker=(lambda x: True))
latex_hspace = dict(default=1, description='the default difference between horizontal coordinates of vertices when latexed', checker=(lambda x: True))
latex_vspace = dict(default=1, description='the default difference between vertical coordinates of vertices when latexed', checker=(lambda x: True))
@staticmethod
def check_poset(poset) -> bool:
'\n Check if the given poset ``poset`` is a interval-poset, that is,\n if it satisfies the following properties:\n\n - Its labels are exactly `1, \\ldots, n` where `n` is its size.\n - If `a < c` (as numbers) and `a` precedes `c`, then `b` precedes\n `c` for all `b` such that `a < b < c`.\n - If `a < c` (as numbers) and `c` precedes `a`, then `b` precedes\n `a` for all `b` such that `a < b < c`.\n\n INPUT:\n\n - ``poset`` -- a finite labeled poset\n\n EXAMPLES::\n\n sage: p = Poset(([1,2,3],[(1,2),(3,2)]))\n sage: TamariIntervalPosets.check_poset(p)\n True\n sage: p = Poset(([2,3],[(3,2)]))\n sage: TamariIntervalPosets.check_poset(p)\n False\n sage: p = Poset(([1,2,3],[(3,1)]))\n sage: TamariIntervalPosets.check_poset(p)\n False\n sage: p = Poset(([1,2,3],[(1,3)]))\n sage: TamariIntervalPosets.check_poset(p)\n False\n '
if (not (set(poset._elements) == set(range(1, (poset.cardinality() + 1))))):
return False
for i in range(1, (poset.cardinality() + 1)):
stop = False
for j in range((i - 1), 0, (- 1)):
if (not poset.le(j, i)):
stop = True
elif stop:
return False
stop = False
for j in range((i + 1), (poset.cardinality() + 1)):
if (not poset.le(j, i)):
stop = True
elif stop:
return False
return True
@staticmethod
def final_forest(element) -> TIP:
"\n Return the final forest of a binary tree, an interval-poset or a\n Dyck word.\n\n A final forest is an interval-poset corresponding to a final\n interval of the Tamari lattice, i.e., containing only decreasing\n relations.\n\n It can be constructed from a binary tree by its binary\n search tree labeling with the rule: `b` precedes\n `a` in the final forest iff `b` is in the right subtree of `a`\n in the binary search tree.\n\n INPUT:\n\n - ``element`` -- a binary tree, a Dyck word or an interval-poset\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: TamariIntervalPosets.final_forest(ip)\n The Tamari interval of size 4 induced by relations [(4, 3)]\n\n From binary trees::\n\n sage: bt = BinaryTree(); bt\n .\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 0 induced by relations []\n sage: bt = BinaryTree([]); bt\n [., .]\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 1 induced by relations []\n sage: bt = BinaryTree([[],None]); bt\n [[., .], .]\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 2 induced by relations []\n sage: bt = BinaryTree([None,[]]); bt\n [., [., .]]\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 2 induced by relations [(2, 1)]\n sage: bt = BinaryTree([[],[]]); bt\n [[., .], [., .]]\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 3 induced by relations [(3, 2)]\n sage: bt = BinaryTree([[None,[[],None]],[]]); bt\n [[., [[., .], .]], [., .]]\n sage: TamariIntervalPosets.final_forest(bt)\n The Tamari interval of size 5 induced by relations [(5, 4), (3, 1), (2, 1)]\n\n From Dyck words::\n\n sage: # needs sage.combinat\n sage: dw = DyckWord([1,0])\n sage: TamariIntervalPosets.final_forest(dw)\n The Tamari interval of size 1 induced by relations []\n sage: dw = DyckWord([1,1,0,1,0,0,1,1,0,0])\n sage: TamariIntervalPosets.final_forest(dw)\n The Tamari interval of size 5 induced by relations [(5, 4), (3, 1), (2, 1)]\n\n TESTS::\n\n sage: TamariIntervalPosets.final_forest('mont')\n Traceback (most recent call last):\n ...\n ValueError: do not know how to construct the final forest of mont\n "
if isinstance(element, TamariIntervalPoset):
return element.final_forest()
try:
DW = DyckWords()
except ImportError:
DW = ()
if (element in DW):
binary_tree = element.to_binary_tree_tamari()
elif ((element in BinaryTrees()) or (element in LabelledBinaryTrees())):
binary_tree = element
else:
raise ValueError(f'do not know how to construct the final forest of {element}')
def get_relations(bt, start=1):
'\n Recursive method to get the binary tree final forest relations\n with only one recursive reading of the tree.\n\n The vertices are being labelled with integers starting with\n ``start``.\n\n OUTPUT:\n\n - the indices of the nodes on the left border of the tree\n (these become the roots of the forest)\n - the relations of the final forest (as a list of tuples)\n - the next available index for a node (size of tree +\n ``start``)\n '
if (not bt):
return ([], [], start)
(roots, relations, index) = get_relations(bt[0], start=start)
(rroots, rrelations, rindex) = get_relations(bt[1], start=(index + 1))
roots.append(index)
relations.extend(rrelations)
relations.extend([(j, index) for j in rroots])
return (roots, relations, rindex)
(_, relations, index) = get_relations(binary_tree)
P = FinitePoset(DiGraph([list(range(1, index)), relations], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
@staticmethod
def initial_forest(element) -> TIP:
"\n Return the initial forest of a binary tree, an interval-poset or\n a Dyck word.\n\n An initial forest is an interval-poset corresponding to an initial\n interval of the Tamari lattice, i.e., containing only increasing\n relations.\n\n It can be constructed from a binary tree by its binary\n search tree labeling with the rule: `a` precedes `b` in the\n initial forest iff `a` is in the left subtree of `b` in the\n binary search tree.\n\n INPUT:\n\n - ``element`` -- a binary tree, a Dyck word or an interval-poset\n\n EXAMPLES::\n\n sage: ip = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: TamariIntervalPosets.initial_forest(ip)\n The Tamari interval of size 4 induced by relations [(1, 2), (2, 3)]\n\n with binary trees::\n\n sage: bt = BinaryTree(); bt\n .\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 0 induced by relations []\n sage: bt = BinaryTree([]); bt\n [., .]\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 1 induced by relations []\n sage: bt = BinaryTree([[],None]); bt\n [[., .], .]\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 2 induced by relations [(1, 2)]\n sage: bt = BinaryTree([None,[]]); bt\n [., [., .]]\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 2 induced by relations []\n sage: bt = BinaryTree([[],[]]); bt\n [[., .], [., .]]\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: bt = BinaryTree([[None,[[],None]],[]]); bt\n [[., [[., .], .]], [., .]]\n sage: TamariIntervalPosets.initial_forest(bt)\n The Tamari interval of size 5 induced by relations [(1, 4), (2, 3), (3, 4)]\n\n from Dyck words::\n\n sage: # needs sage.combinat\n sage: dw = DyckWord([1,0])\n sage: TamariIntervalPosets.initial_forest(dw)\n The Tamari interval of size 1 induced by relations []\n sage: dw = DyckWord([1,1,0,1,0,0,1,1,0,0])\n sage: TamariIntervalPosets.initial_forest(dw)\n The Tamari interval of size 5 induced by relations [(1, 4), (2, 3), (3, 4)]\n\n TESTS::\n\n sage: TamariIntervalPosets.initial_forest('mont')\n Traceback (most recent call last):\n ...\n ValueError: do not know how to construct the initial forest of mont\n "
if isinstance(element, TamariIntervalPoset):
return element.initial_forest()
try:
DW = DyckWords()
except ImportError:
DW = ()
if (element in DW):
binary_tree = element.to_binary_tree_tamari()
elif ((element in BinaryTrees()) or (element in LabelledBinaryTrees())):
binary_tree = element
else:
raise ValueError(f'do not know how to construct the initial forest of {element}')
def get_relations(bt, start=1):
'\n Recursive method to get the binary tree initial forest\n relations with only one recursive reading of the tree.\n\n The vertices are being labelled with integers starting with\n ``start``.\n\n OUTPUT:\n\n - the indices of the nodes on the right border of the tree\n (these become the roots of the forest)\n - the relations of the initial forest (as a list of tuples)\n - the next available index for a node (size of tree +\n ``start``)\n '
if (not bt):
return ([], [], start)
(lroots, lrelations, index) = get_relations(bt[0], start=start)
(roots, relations, rindex) = get_relations(bt[1], start=(index + 1))
roots.append(index)
relations.extend(lrelations)
relations.extend([(j, index) for j in lroots])
return (roots, relations, rindex)
(_, relations, index) = get_relations(binary_tree)
P = FinitePoset(DiGraph([list(range(1, index)), relations], format='vertices_and_edges'))
return TamariIntervalPoset(P, check=False)
@staticmethod
def from_binary_trees(tree1, tree2) -> TIP:
'\n Return the interval-poset corresponding to the interval\n [``tree1``, ``tree2``] of the Tamari lattice.\n\n Raise an exception if\n ``tree1`` is not `\\leq` ``tree2`` in the Tamari lattice.\n\n INPUT:\n\n - ``tree1`` -- a binary tree\n - ``tree2`` -- a binary tree greater or equal than ``tree1`` for\n the Tamari lattice\n\n EXAMPLES::\n\n sage: tree1 = BinaryTree([[],None])\n sage: tree2 = BinaryTree([None,[]])\n sage: TamariIntervalPosets.from_binary_trees(tree1,tree2)\n The Tamari interval of size 2 induced by relations []\n sage: TamariIntervalPosets.from_binary_trees(tree1,tree1)\n The Tamari interval of size 2 induced by relations [(1, 2)]\n sage: TamariIntervalPosets.from_binary_trees(tree2,tree2)\n The Tamari interval of size 2 induced by relations [(2, 1)]\n\n sage: tree1 = BinaryTree([[],[[None,[]],[]]])\n sage: tree2 = BinaryTree([None,[None,[None,[[],[]]]]])\n sage: TamariIntervalPosets.from_binary_trees(tree1,tree2)\n The Tamari interval of size 6 induced by relations [(4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n\n sage: tree3 = BinaryTree([None,[None,[[],[None,[]]]]])\n sage: TamariIntervalPosets.from_binary_trees(tree1,tree3)\n Traceback (most recent call last):\n ...\n ValueError: the two binary trees are not comparable on the Tamari lattice\n sage: TamariIntervalPosets.from_binary_trees(tree1,BinaryTree())\n Traceback (most recent call last):\n ...\n ValueError: the two binary trees are not comparable on the Tamari lattice\n '
initial_forest = TamariIntervalPosets.initial_forest(tree2)
final_forest = TamariIntervalPosets.final_forest(tree1)
try:
return initial_forest.intersection(final_forest)
except ValueError:
raise ValueError('the two binary trees are not comparable on the Tamari lattice')
@staticmethod
def from_dyck_words(dw1, dw2) -> TIP:
'\n Return the interval-poset corresponding to the interval\n [``dw1``, ``dw2``] of the Tamari lattice.\n\n Raise an exception if the\n two Dyck words ``dw1`` and ``dw2`` do not satisfy\n ``dw1`` `\\leq` ``dw2`` in the Tamari lattice.\n\n INPUT:\n\n - ``dw1`` -- a Dyck word\n - ``dw2`` -- a Dyck word greater or equal than ``dw1`` for\n the Tamari lattice\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: dw1 = DyckWord([1,0,1,0])\n sage: dw2 = DyckWord([1,1,0,0])\n sage: TamariIntervalPosets.from_dyck_words(dw1, dw2)\n The Tamari interval of size 2 induced by relations []\n sage: TamariIntervalPosets.from_dyck_words(dw1,dw1)\n The Tamari interval of size 2 induced by relations [(1, 2)]\n sage: TamariIntervalPosets.from_dyck_words(dw2,dw2)\n The Tamari interval of size 2 induced by relations [(2, 1)]\n\n sage: # needs sage.combinat\n sage: dw1 = DyckWord([1,0,1,1,1,0,0,1,1,0,0,0])\n sage: dw2 = DyckWord([1,1,1,1,0,1,1,0,0,0,0,0])\n sage: TamariIntervalPosets.from_dyck_words(dw1,dw2)\n The Tamari interval of size 6 induced by relations\n [(4, 5), (6, 5), (5, 2), (4, 3), (3, 2)]\n sage: dw3 = DyckWord([1,1,1,0,1,1,1,0,0,0,0,0])\n sage: TamariIntervalPosets.from_dyck_words(dw1,dw3)\n Traceback (most recent call last):\n ...\n ValueError: the two Dyck words are not comparable on the Tamari lattice\n sage: TamariIntervalPosets.from_dyck_words(dw1,DyckWord([1,0]))\n Traceback (most recent call last):\n ...\n ValueError: the two Dyck words are not comparable on the Tamari lattice\n '
tree1 = dw1.to_binary_tree_tamari()
tree2 = dw2.to_binary_tree_tamari()
try:
return TamariIntervalPosets.from_binary_trees(tree1, tree2)
except ValueError:
raise ValueError('the two Dyck words are not comparable on the Tamari lattice')
@staticmethod
def recomposition_from_triple(left: TIP, right: TIP, r) -> TIP:
'\n Recompose an interval-poset from a triple (``left``, ``right``, ``r``).\n\n For the inverse method,\n see :meth:`TamariIntervalPoset.decomposition_to_triple`.\n\n INPUT:\n\n - ``left`` -- an interval-poset\n - ``right`` -- an interval-poset\n - ``r`` -- the parameter of the decomposition, an integer\n\n OUTPUT: an interval-poset\n\n EXAMPLES::\n\n sage: T1 = TamariIntervalPoset(3, [(1, 2), (3, 2)])\n sage: T2 = TamariIntervalPoset(4, [(2, 3), (4, 3)])\n sage: TamariIntervalPosets.recomposition_from_triple(T1, T2, 2)\n The Tamari interval of size 8 induced by relations [(1, 2), (2, 4),\n (3, 4), (6, 7), (8, 7), (6, 4), (5, 4), (3, 2)]\n\n REFERENCES:\n\n - [Pons2018]_\n '
root = (left.size() + 1)
rel = left.poset().cover_relations()
rel.extend(((i, root) for i in left))
rel.extend((((root + a), (root + b)) for (a, b) in right.poset().cover_relations()))
decroot = right.decreasing_roots()[:r]
rel.extend((((root + i), root) for i in decroot))
return TamariIntervalPoset(((left.size() + right.size()) + 1), rel)
@staticmethod
def from_grafting_tree(tree) -> TIP:
'\n Return an interval-poset from a grafting tree.\n\n For the inverse method,\n see :meth:`TamariIntervalPoset.grafting_tree`.\n\n EXAMPLES::\n\n sage: tip = TamariIntervalPoset(8, [(1,2), (2,4), (3,4), (6,7), (3,2), (5,4), (6,4), (8,7)])\n sage: t = tip.grafting_tree()\n sage: TamariIntervalPosets.from_grafting_tree(t) == tip\n True\n\n REFERENCES:\n\n - [Pons2018]_\n '
if tree.is_empty():
return TamariIntervalPoset(0, [])
r = tree.label()
left = TamariIntervalPosets.from_grafting_tree(tree[0])
right = TamariIntervalPosets.from_grafting_tree(tree[1])
return TamariIntervalPosets.recomposition_from_triple(left, right, r)
@staticmethod
def from_minimal_schnyder_wood(graph) -> TIP:
"\n Return a Tamari interval built from a minimal Schnyder wood.\n\n This is an implementation of Bernardi and Bonichon's bijection\n [BeBo2009]_.\n\n INPUT:\n\n a minimal Schnyder wood, given as a graph with colored and\n oriented edges, without the three exterior unoriented edges\n\n The three boundary vertices must be -1, -2 and -3.\n\n One assumes moreover that the embedding around -1 is the\n list of neighbors of -1 and not just a cyclic permutation of that.\n\n Beware that the embedding convention used here is the opposite of\n the one used by the plot method.\n\n OUTPUT:\n\n a Tamari interval-poset\n\n EXAMPLES:\n\n A small example::\n\n sage: TIP = TamariIntervalPosets\n sage: G = DiGraph([(0,-1,0),(0,-2,1),(0,-3,2)], format='list_of_edges')\n sage: G.set_embedding({-1:[0],-2:[0],-3:[0],0:[-1,-2,-3]})\n sage: TIP.from_minimal_schnyder_wood(G) # needs sage.combinat\n The Tamari interval of size 1 induced by relations []\n\n An example from page 14 of [BeBo2009]_::\n\n sage: c0 = [(0,-1),(1,0),(2,0),(4,3),(3,-1),(5,3)]\n sage: c1 = [(5,-2),(3,-2),(4,5),(1,3),(2,3),(0,3)]\n sage: c2 = [(0,-3),(1,-3),(3,-3),(4,-3),(5,-3),(2,1)]\n sage: ed = [(u,v,0) for u,v in c0]\n sage: ed += [(u,v,1) for u,v in c1]\n sage: ed += [(u,v,2) for u,v in c2]\n sage: G = DiGraph(ed, format='list_of_edges')\n sage: embed = {-1:[3,0],-2:[5,3],-3:[0,1,3,4,5]}\n sage: data_emb = [[3,2,1,-3,-1],[2,3,-3,0],[3,1,0]]\n sage: data_emb += [[-2,5,4,-3,1,2,0,-1],[5,-3,3],[-2,-3,4,3]]\n sage: for k in range(6):\n ....: embed[k] = data_emb[k]\n sage: G.set_embedding(embed)\n sage: TIP.from_minimal_schnyder_wood(G) # needs sage.combinat\n The Tamari interval of size 6 induced by relations\n [(1, 4), (2, 4), (3, 4), (5, 6), (6, 4), (5, 4), (3, 1), (2, 1)]\n\n An example from page 18 of [BeBo2009]_::\n\n sage: c0 = [(0,-1),(1,0),(2,-1),(3,2),(4,2),(5,-1)]\n sage: c1 = [(5,-2),(2,-2),(4,-2),(3,4),(1,2),(0,2)]\n sage: c2 = [(0,-3),(1,-3),(3,-3),(4,-3),(2,-3),(5,2)]\n sage: ed = [(u,v,0) for u,v in c0]\n sage: ed += [(u,v,1) for u,v in c1]\n sage: ed += [(u,v,2) for u,v in c2]\n sage: G = DiGraph(ed, format='list_of_edges')\n sage: embed = {-1:[5,2,0],-2:[4,2,5],-3:[0,1,2,3,4]}\n sage: data_emb = [[2,1,-3,-1],[2,-3,0],[3,-3,1,0,-1,5,-2,4]]\n sage: data_emb += [[4,-3,2],[-2,-3,3,2],[-2,2,-1]]\n sage: for k in range(6):\n ....: embed[k] = data_emb[k]\n sage: G.set_embedding(embed)\n sage: TIP.from_minimal_schnyder_wood(G) # needs sage.combinat\n The Tamari interval of size 6 induced by relations\n [(1, 3), (2, 3), (4, 5), (5, 3), (4, 3), (2, 1)]\n\n Another small example::\n\n sage: c0 = [(0,-1),(2,-1),(1,0)]\n sage: c1 = [(2,-2),(1,-2),(0,2)]\n sage: c2 = [(0,-3),(1,-3),(2,1)]\n sage: ed = [(u,v,0) for u,v in c0]\n sage: ed += [(u,v,1) for u,v in c1]\n sage: ed += [(u,v,2) for u,v in c2]\n sage: G = DiGraph(ed, format='list_of_edges')\n sage: embed = {-1:[2,0],-2:[1,2],-3:[0,1]}\n sage: data_emb = [[2,1,-3,-1],[-3,0,2,-2],[-2,1,0,-1]]\n sage: for k in range(3):\n ....: embed[k] = data_emb[k]\n sage: G.set_embedding(embed)\n sage: TIP.from_minimal_schnyder_wood(G) # needs sage.combinat\n The Tamari interval of size 3 induced by relations [(2, 3), (2, 1)]\n "
from sage.combinat.dyck_word import DyckWord
color_a = graph.incoming_edges((- 1))[0][2]
color_b = graph.incoming_edges((- 2))[0][2]
embedding = graph.get_embedding()
graph0 = DiGraph([e for e in graph.edges(sort=False) if (e[2] == color_a)], format='list_of_edges')
restricted_embedding = {u: [v for v in embedding[u] if ((v in graph0.neighbors_in(u)) or (v in graph0.neighbors_out(u)))] for u in graph0}
voisins_in = {}
for u in graph0:
if (u != (- 1)):
bad_emb = restricted_embedding[u]
sortie = graph0.neighbors_out(u)[0]
idx = bad_emb.index(sortie)
restricted_embedding[u] = (bad_emb[idx:] + bad_emb[:idx])
voisins_in[u] = restricted_embedding[u][1:]
else:
voisins_in[u] = list(restricted_embedding[u])
voisins_in[u].reverse()
graph0.set_embedding(restricted_embedding)
def clockwise_labelling(gr, vertex):
if (len(gr) == 1):
return [vertex]
lbl = [vertex]
for w in voisins_in[vertex]:
lbl += clockwise_labelling(gr, w)
return lbl
def profil(gr, vertex):
if (len(gr) == 1):
return []
lbl = []
for w in voisins_in[vertex]:
lbl += (([1] + profil(gr, w)) + [0])
return lbl
dyckword_bottom = profil(graph0, (- 1))
liste = clockwise_labelling(graph0, (- 1))[1:]
relabelling = {l: i for (i, l) in enumerate(liste)}
for l in [(- 1), (- 2), (- 3)]:
relabelling[l] = l
new_graph = graph.relabel(relabelling, inplace=False)
dyckword_top = []
for i in range(1, (len(graph) - 3)):
indegree1 = len([u for u in new_graph.incoming_edges(i) if (u[2] == color_b)])
dyckword_top += ([1] + ([0] * indegree1))
indegree1 = len([u for u in new_graph.incoming_edges((- 2)) if (u[2] == color_b)])
dyckword_top += ([1] + ([0] * indegree1))
dyckword_bottom = DyckWord(dyckword_bottom)
dyckword_top = DyckWord(dyckword_top)
tip = TamariIntervalPosets((len(dyckword_bottom) // 2))
return tip.from_dyck_words(dyckword_bottom, dyckword_top)
def __call__(self, *args, **keywords):
'\n Allows for a poset to be directly transformed into an interval-poset.\n\n It is some kind of coercion but cannot be made through the coercion\n system because posets do not have parents.\n\n EXAMPLES::\n\n sage: TIP = TamariIntervalPosets()\n sage: p = Poset( ([1,2,3], [(1,2)]))\n sage: TIP(p)\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: TIP(TIP(p))\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: TIP(3,[(1,2)])\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: p = Poset(([1,2,3],[(1,3)]))\n sage: TIP(p)\n Traceback (most recent call last):\n ...\n ValueError: this does not satisfy the Tamari interval-poset condition\n '
if isinstance(args[0], TamariIntervalPoset):
return args[0]
if ((len(args) == 1) and isinstance(args[0], FinitePoset)):
return self.element_class(self, args[0])
return super().__call__(*args, **keywords)
def le(self, el1, el2) -> bool:
'\n Poset structure on the set of interval-posets.\n\n The comparison is first by size, then using the\n cubical coordinates.\n\n .. SEEALSO:: :meth:`~TamariIntervalPoset.cubical_coordinates`\n\n INPUT:\n\n - ``el1`` -- an interval-poset\n - ``el2`` -- an interval-poset\n\n EXAMPLES::\n\n sage: ip1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])\n sage: ip2 = TamariIntervalPoset(4,[(1,2),(2,3)])\n sage: TamariIntervalPosets().le(ip1,ip2)\n False\n sage: TamariIntervalPosets().le(ip2,ip1)\n True\n '
cc1 = el1.cubical_coordinates()
cc2 = el2.cubical_coordinates()
return all(((x1 <= x2) for (x1, x2) in zip(cc1, cc2)))
|
class TamariIntervalPosets_all(DisjointUnionEnumeratedSets, TamariIntervalPosets):
'\n The enumerated set of all Tamari interval-posets.\n '
def __init__(self):
'\n TESTS::\n\n sage: from sage.combinat.interval_posets import TamariIntervalPosets_all\n sage: S = TamariIntervalPosets_all()\n sage: S.cardinality()\n +Infinity\n\n sage: it = iter(S)\n sage: [next(it) for i in range(5)]\n [The Tamari interval of size 0 induced by relations [],\n The Tamari interval of size 1 induced by relations [],\n The Tamari interval of size 2 induced by relations [],\n The Tamari interval of size 2 induced by relations [(2, 1)],\n The Tamari interval of size 2 induced by relations [(1, 2)]]\n sage: next(it).parent()\n Interval-posets\n sage: S(0,[])\n The Tamari interval of size 0 induced by relations []\n\n sage: S is TamariIntervalPosets_all()\n True\n sage: TestSuite(S).run() # long time (7s)\n '
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), TamariIntervalPosets_size), facade=True, keepkey=False, category=(Posets(), EnumeratedSets(), Monoids()))
def _repr_(self) -> str:
'\n TESTS::\n\n sage: TamariIntervalPosets()\n Interval-posets\n '
return 'Interval-posets'
def one(self) -> TIP:
'\n Return the unit of the monoid.\n\n This is the empty interval poset, of size 0.\n\n EXAMPLES::\n\n sage: TamariIntervalPosets().one()\n The Tamari interval of size 0 induced by relations []\n '
return TamariIntervalPoset(0, [])
def _element_constructor_(self, size, relations) -> TIP:
'\n EXAMPLES::\n\n sage: TIP = TamariIntervalPosets()\n sage: TIP(3,[(1,2)])\n The Tamari interval of size 3 induced by relations [(1, 2)]\n '
return self.element_class(self, size, relations)
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: S = TamariIntervalPosets()\n sage: 1 in S\n False\n sage: S(0,[]) in S\n True\n '
return isinstance(x, self.element_class)
Element = TamariIntervalPoset
|
class TamariIntervalPosets_size(TamariIntervalPosets):
'\n The enumerated set of interval-posets of a given size.\n '
def __init__(self, size):
'\n TESTS::\n\n sage: S = TamariIntervalPosets(3)\n sage: assert S is TamariIntervalPosets(3)\n sage: for i in range(5): TestSuite(TamariIntervalPosets(i)).run()\n '
super().__init__(category=(FinitePosets(), FiniteEnumeratedSets()))
self._size = size
def _repr_(self) -> str:
'\n TESTS::\n\n sage: TamariIntervalPosets(3)\n Interval-posets of size 3\n '
return f'Interval-posets of size {self._size}'
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: S = TamariIntervalPosets(3)\n sage: 1 in S\n False\n sage: S([]) in S\n True\n '
return (isinstance(x, self.element_class) and (x.size() == self._size))
def cardinality(self) -> Integer:
'\n The cardinality of ``self``. That is, the number of\n interval-posets of size `n`.\n\n The formula was given in [Cha2008]_:\n\n .. MATH::\n\n \\frac{2(4n+1)!}{(n+1)!(3n+2)!}\n = \\frac{2}{n(n+1)} \\binom{4n+1}{n-1}.\n\n EXAMPLES::\n\n sage: [TamariIntervalPosets(i).cardinality() for i in range(6)]\n [1, 1, 3, 13, 68, 399]\n '
from sage.arith.misc import binomial
n = self._size
if (n == 0):
return Integer(1)
return ((2 * binomial(((4 * n) + 1), (n - 1))) // (n * (n + 1)))
def __iter__(self) -> Iterator[TIP]:
'\n Recursive generation: we iterate through all interval-posets of\n size ``size - 1`` and add all possible relations to the last\n vertex.\n\n This works thanks to the fact that the restriction of an\n interval-poset of size `n` to the subset `\\{1, 2, \\ldots, k\\}` for\n a fixed `k \\leq n` is an interval-poset.\n\n TESTS::\n\n sage: TIP1 = TamariIntervalPosets(1)\n sage: list(TIP1)\n [The Tamari interval of size 1 induced by relations []]\n sage: TIP2 = TamariIntervalPosets(2)\n sage: list(TIP2)\n [The Tamari interval of size 2 induced by relations [],\n The Tamari interval of size 2 induced by relations [(2, 1)],\n The Tamari interval of size 2 induced by relations [(1, 2)]]\n sage: TIP3 = TamariIntervalPosets(3)\n sage: list(TIP3)\n [The Tamari interval of size 3 induced by relations [],\n The Tamari interval of size 3 induced by relations [(3, 2)],\n The Tamari interval of size 3 induced by relations [(2, 3)],\n The Tamari interval of size 3 induced by relations [(1, 3), (2, 3)],\n The Tamari interval of size 3 induced by relations [(2, 1)],\n The Tamari interval of size 3 induced by relations [(3, 2), (2, 1)],\n The Tamari interval of size 3 induced by relations [(3, 1), (2, 1)],\n The Tamari interval of size 3 induced by relations [(2, 3), (2, 1)],\n The Tamari interval of size 3 induced by relations [(2, 3), (3, 1), (2, 1)],\n The Tamari interval of size 3 induced by relations [(1, 3), (2, 3), (2, 1)],\n The Tamari interval of size 3 induced by relations [(1, 2)],\n The Tamari interval of size 3 induced by relations [(1, 2), (3, 2)],\n The Tamari interval of size 3 induced by relations [(1, 2), (2, 3)]]\n sage: all(len(list(TamariIntervalPosets(i)))==TamariIntervalPosets(i).cardinality() for i in range(6))\n True\n '
n = self._size
if (n <= 1):
(yield TamariIntervalPoset(n, [], check=False))
return
for tip in TamariIntervalPosets((n - 1)):
new_tip = TamariIntervalPoset(n, tip._cover_relations, check=False)
(yield new_tip)
for m2 in range((n - 1), 0, (- 1)):
if new_tip.le((n - 1), m2):
(yield TamariIntervalPoset(n, (new_tip._cover_relations + ((n, m2),)), check=False))
for m in range((n - 1), 0, (- 1)):
if (not new_tip.le(m, n)):
new_tip = TamariIntervalPoset(n, (new_tip._cover_relations + ((m, n),)), check=False)
(yield new_tip)
else:
continue
for m2 in range((m - 1), 0, (- 1)):
if new_tip.le((n - 1), m2):
(yield TamariIntervalPoset(n, (new_tip._cover_relations + ((n, m2),)), check=False))
def random_element(self) -> TIP:
'\n Return a random Tamari interval of fixed size.\n\n This is obtained by first creating a random rooted\n planar triangulation, then computing its unique\n minimal Schnyder wood, then applying a bijection\n of Bernardi and Bonichon [BeBo2009]_.\n\n Because the random rooted planar triangulation is\n chosen uniformly at random, the Tamari interval is\n also chosen according to the uniform distribution.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: T = TamariIntervalPosets(4).random_element()\n sage: T.parent()\n Interval-posets\n sage: u = T.lower_dyck_word(); u # random\n [1, 1, 0, 1, 0, 0, 1, 0]\n sage: v = T.lower_dyck_word(); v # random\n [1, 1, 0, 1, 0, 0, 1, 0]\n sage: len(u)\n 8\n '
from sage.graphs.schnyder import minimal_schnyder_wood
from sage.graphs.generators.random import RandomTriangulation
n = self._size
tri = RandomTriangulation((n + 3))
tip = TamariIntervalPosets
schnyder = minimal_schnyder_wood(tri, root_edge=((- 1), (- 2)), check=False)
return tip.from_minimal_schnyder_wood(schnyder)
@lazy_attribute
def _parent_for(self):
'\n The parent of the element generated by ``self``.\n\n TESTS::\n\n sage: TIP3 = TamariIntervalPosets(3)\n sage: TIP3._parent_for\n Interval-posets\n '
return TamariIntervalPosets_all()
@lazy_attribute
def element_class(self):
"\n TESTS::\n\n sage: S = TamariIntervalPosets(3)\n sage: S.element_class\n <class 'sage.combinat.interval_posets.TamariIntervalPosets_all_with_category.element_class'>\n sage: S.first().__class__ == TamariIntervalPosets().first().__class__\n True\n "
return self._parent_for.element_class
def _element_constructor_(self, relations) -> TIP:
'\n EXAMPLES::\n\n sage: TIP3 = TamariIntervalPosets(3)\n sage: TIP3([(1,2)])\n The Tamari interval of size 3 induced by relations [(1, 2)]\n sage: TIP3([(3,4)])\n Traceback (most recent call last):\n ...\n ValueError: the relations do not correspond to the size of the poset\n '
return self.element_class(self, self._size, relations)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.